The benefit of using else statements is that it forces you to think what should happen when the condition is not true.
For guard clauses this does not matter because you are already thinking about that: in case of error return early, and otherwise keep executing the function. In all other cases you should be using else clauses, even if it's just to add a comment like // otherwise, do nothing because we don't care.
76
u/apieceoffruit Apr 17 '21
its funny for all the versions in the comments, I am surprised to see nobody has a version with a guard clause and no cyclomatic complexity:
Obviously the silly order dependent names make it more confusing. but a standard for this kind of thing is:
one of the below comments says to always add an else statement, I 100% disagree.
else statements are flow statements that increase the cognitive complexity of a statement and tie two conceptually unrelated concepts.
Instead, evaluate your "guard" statements, exit early if you can, so as you get down further the code gets simpler, not more complex.
instead of nesting in a tree of conditionals, knock down and remove ones you can evaluate early.
In fact Jeff Bay in his thoughtworks anthology book suggests his own rules for "object calisthenics" that includes never using the else keyword.
Not sure I subscribe to that one myself, but I do admit I don't use it very often. rarely does it make code easier to read.