Code Smell 140 - Short Circuit Evaluation
We learn short circuits in our first programming courses. We need to remember why.

I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.
Search for a command to run...
We learn short circuits in our first programming courses. We need to remember why.

I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.
No comments yet. Be the first to comment.
In this series, we will see several symptoms and situations that make us doubt the quality of our developments. We will present possible solutions. Most are just clues. They are no hard rules.
The perfect prompt doesn't instruct the model on what it already knows how to do.

Approve the logic once, then let it run the same way forever.

Different stages need different brains.

One Second Brain doesn't scale past one skull.

Style errors double when nobody enforces them.

TL;DR: Be lazy when evaluating boolean conditions
Side effects
Bijection Fault
Performance issues
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)
// Full evaluation
// Will fail since we cannot retrieve contents
// from not open file
<?
if (isOpen(file) && size(contents(file)) > 0)
// Short circuit evaluation
// If file is not open it will not 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.
Most programming languages support short-circuits.
Many of them have it as the only option.
We need to favor these kinds of expressions.
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
This article is part of the CodeSmell Series.