Else Considered Smelly
wiki.c2.com
wiki.c2.com
$x=a
if (condition) then $x=bI don't care that its not the most efficient way to do things, programming languages exist to make things easier for me.
$x=a
if (condition) then $x=b
If you think of programs as logic then I see the lines above as a logical expression written in CNF conjunctive normal form, where each line is a clause.whereas this...
$x = condition ? b : a;
...is like a nested logical expression.And breaking the program down into clauses makes it easier to understand, for humans and computers.
> Use "if (condition()) { ifBlock(); } if (!condition()) { elseBlock(); }" -- assuming that ifBlock() can't possibly change the result of condition().
What?? That seems terrible to me - just asking for `condition` to be updated to be modifiable by `ifBlock`, or for some completely undebuggable race condition to occur.
My team has an ongoing style war about guard clauses:
if foo:
bar()
baz()
vs if foo:
bar()
else:
baz()
Consensus seems to favor the first option but I prefer the second because it helps me keep in mind the conditions that lead me to `baz()`. Otherwise I have to scan up the whole function to figure out the restriction `!foo`.If foo is true, bar() and baz() are both executed in your first scenario. Only bar() is executed in the second.
https://wiki.c2.com/?ElseConsideredHelpful
if you really can’t abide early returns.
This is a high-quality site, though.
Apart from the psychosomatics of it, it’s unnecessary and childish and dishonest.
It asserts a physical repugnance when the truth is the author simply dislikes something.
Mention smell, and I have a much harder time taking you seriously.
Code smells themselves aren’t problems, they’re just useful track marks that might indicate a problem is lurking nearby. Worth looking into and making the decision yourself.
The term “smell” over something more concrete like “rotten” is quite perfect as what smells for me might not smell for you; whereas if something is rotten there’s little dispute.
Additionally, a code smell can describe code that feels wrong, but you can’t quite put your finger on it. Similar to catching a whiff of a new smell when out. You can’t quite discern where it came from, but it’s there.