Consider the following code snippet:
let a;
if (obj === undefined ||
obj.prop === undefined ||
(a = await getResultFromLongOperation(obj.prop)) === undefined) {
// Perform actions to handle errors due to incorrect parameters
}
console.log(a); // Value of 'a' is not undefined
I want to find a way to avoid setting the value of a
within the if statement. However, I also want to minimize calls to getResultFromLongOperation
and prevent duplication of error handling logic.
How can this be refactored?
The only solution I've come up with is to refactor as follows:
function handleIncorrectParams() {
// Perform actions to handle errors due to incorrect parameters
}
if (obj === undefined ||
obj.prop === undefined) {
handleIncorrectParams();
}
let a = getResultFromLongOperation(obj.prop);
if (a === undefined) {
handleIncorrectParams();
}
console.log(a); // Value of 'a' is not undefined
Do you think this approach is an improvement?