In the current software I am working on, I'm seeing this pattern quite extensively and it seems that they're trying to avoid return statements as much as possible. Even at some places in the code this is taken almost to the extreme.
I've somehow heard a long time ago that return statements should be minimized or avoided but I can't remember (or search about) the exact reason or origin of this line of thought. I believe it was due to some performance implication in some PL.
I do not personally adhere to this since it doesn't make code that readable but, giving it the benefit of the doubt, I'm curious whether using this pattern has its merits in javascript in terms of performance.
if (err) {
if (err.message) {
message = err.message;
} else {
if (err.errorCode) {
message = err.errorCode;
} else {
message = "Unknown error";
}
}
} else {
message = "Unknown error.";
}
deferred.reject(message);
If I were to decide, I'd casually use the return statement to terminate sequence like this:
if(!err || (!err.message && !err.errorCode)){
deferred.reject("Unknown error.");
return;
}
if(err.message){
deferred.reject(err.message);
return;
}
if(err.errorCode){
deferred.reject(err.errorCode);
}
Are there advantages in the first pattern over the second one?
Your code example also have nickname - christmas tree, and in real projects, it is extremely hard support such code.
For example you need add another condition - you will put another if
block inside existing and so on and so forth and it is gonna be a nightmare... and as result, you will have an awfull tree...
As alternative, you can something like this:
if (err) {
if (err.message) {
return err.message;
}
if (err.errorCode) {
return err.errorCode;
}
}
return "Unknown error.";
Such code looks simpler, isn't it?
So I truly believe it makes sense use return
for such purposes.
BUT, I think that main point here is - don't loose consistency! In our example, we always return a result in same data type and with same business logic, and for example:
if (err) {
if (err.message) {
return err;
}
// Here some stuff...
// Few lines of code...
//
return -1;
}
// Another code...
//
if (!user) {
return null;
}
// And somewhere in the end on anothere scrollin screen
//
return user.email;
this example returns object
or number
or null
or string
- and it is another nightmare...
And in real projects in big functions, it is really easy to get such code because of lot returns...
So here better have less count of returns, again because it is easy to support...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With