We learn short circuits in our first programming courses. We need to remember why.
TL;DR: Be lazy when evaluating boolean conditions
-
Side effects
-
Bijection Fault
-
Performance issues
- Use a short circuit instead of a complete evaluation
We learn booleans in our 101 computer courses.
Boolean's truth tables are great for mathematics, but we need to be more intelligent as software engineerings.
Short circuit evaluation helps us to be lazy and even build invalid full evaluations.
<?
if (isOpen(file) & size(contents(file)) > 0)
// It performs a full evaluation since it is the bitwise AND
// will fail since you cannot retrieve contents
// from a file that is not open
<?
if (isOpen(file) && size(contents(file)) > 0)
// Short circuit evaluation
// If the file is not open it willtry to get the contents
[X] Automatic
We can warn our developers when they use full evaluation.
Don't use short-circuit as an IF alternative.
if the operands have side effects, this is another code smell.
- Boolean
Most programming languages support short-circuits.
Many of them have it as the only option.
We need to favor these kinds of expressions.
Code Smell 101 - Comparison Against Booleans
Code Smell 69 - Big Bang (JavaScript Ridiculous Castings)
Code Smell 145 - Short Circuit Hack
Writing a class without its contract would be similar to producing an engineering component (electrical circuit, VLSI (Very Large Scale Integration) chip, bridge, engine...) without a spec. No professional engineer would even consider the idea.
Bertrand Meyer
Software Engineering Great Quotes
This article is part of the CodeSmell Series.