Why would you avoid the else clause in an if statement or default clause in a switch statement?
In java, this is much cleaner (checking if a String is "true" or not):
String abc;
...
if ("true".equals(abc)){
// if true
} else {
// if false
}
than this:
Boolean abc;
....
if (abc != null){
if (abc.eqals("true"){
// if true
return;
}
if (!abc.equals("true"){
// if false
return;
}
}
if (abc == null){
// handle like false
return
}
In javascript it would be much messier since javascript has null and undefined, so you'd have to check for undefined first, then null, then for the value you're looking for and then for the value you're not looking for ... or you could have just used an else, saved yourself a lot of code.
Assembler on every platform that I know of supports if and else, so you're not gaining anything by not using it and on those CPUs where it's not supported, it's fairly easy to push a variable into a register based on the result of the condition and then simply executing it as two if statements, on with condition and one with not condition.
The ife directive is used exactly like the if directive, except it assembles the code after the ife directive only if the expression evaluates to zero (false), rather than true (non-zero).
If it reads more clearly and logically with an else then use it.
If it doesn't then don't.
Whenever you change the logic then revisit this question and refactor if needed.
Readability and clarity usually trumps any other factor (aside from cases where performance is genuinely critical)
If-Else blocks add branches and complexity to your programm. Switch statements do the same.
To avoid this, I mostly rely on short circuiting, ternary operators, action objects or the strategy pattern.
Jan Vladimir Mostert
Idea Incubator
Tyler James Thompson
Hack the world
Denny Trebbin
Lead Fullstack Developer. Experimenting with bleeding-edge tech. Irregularly DJ. Hobby drone pilot. Amateur photographer.
I try to avoid else clauses whenever possible. My reason for doing so is, it forces me to write all conditions, required to process the data, at the beginning of each function. It's easier for me, to have all requirements visible at one place. Below them, I can describe pure how to process business data, without the need to check again for something being what I expect it to be.
I see developers doing redundant checks just because they overuse 'else' everywhere. Or developers tend to nest everything regardless of their error handlings in any 'else' clause.
The 'else' clause should be used for branching of data processing steps exclusively. Not for putting your 'throws' and 'return's in there.