28 ms·
As I mentioned, I prefer early returns as well, and I wasn't recommending the if/else structure as an alternative to early returns. My only point in showing th
by Stratoscope 11y ago
As I mentioned, I prefer early returns as well, and I wasn't recommending the if/else structure as an alternative to early returns.
My only point in showing that code was to illustrate what I see as the bigger problem in the example: the use of nested if and else statements when non-nested ones could be used instead. Personally I would get rid of the nesting by using early returns, but for someone who objects to that for any reason, the non-nested if/else chain is a nice alternative.
Also, the series of returns you show here could easily be written as a chain of if/else for those who prefer that style. I'm not sure why you said it requires a complex boolean expression; this code is equivalent to the series of returns:
string result;
if( x == null ) {
result = "x is required";
} else if( x.length < 3 ) {
result = "too few elements in x";
} else if( x[0] == null ) {
result = "first element missing";
} else {
result = "the real result";
}
return result;
Again, I don't particularly like this style, although it is better than the deeply nested if/else. I prefer the series of returns that you listed in your comment.