DEV Community

Cover image for Code Smell 140 - Short Circuit Evaluation
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

5 2

Code Smell 140 - Short Circuit Evaluation

We learn short circuits in our first programming courses. We need to remember why.

TL;DR: Be lazy when evaluating boolean conditions

Problems

  • Side effects

  • Biyection Fault

  • Performance issues

Solutions

  1. Use a short circuit instead of a complete evaluation

Context

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.

Sample Code

Wrong

<?

if (isOpen(file) & size(contents(file)) > 0)
  // Full evaluation 
  // Will fail since we cannot retrieve contents 
  // from not open file
Enter fullscreen mode Exit fullscreen mode

Right

<?

if (isOpen(file) && size(contents(file)) > 0)
  // Short circuit evaluation 
  // If file is not open it will not get the contents  
Enter fullscreen mode Exit fullscreen mode

Detection

[X] Automatic

We can warn our developers when they use full evaluation.

Tags

  • Boolean

Exceptions

Don't use short-circuit as an IF alternative.

if the operands have side effects, this is another code smell.

Conclusion

Most programming languages support short-circuits.

Many of them have it as the only option.

We need to favor these kinds of expressions.

Relations

More Info


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.

Scale globally with MongoDB Atlas. Try free.

Scale globally with MongoDB Atlas. Try free.

MongoDB Atlas is the global, multi-cloud database for modern apps trusted by developers and enterprises to build, scale, and run cutting-edge applications, with automated scaling, built-in security, and 125+ cloud regions.

Learn More

Top comments (0)

Feature flag article image

Create a feature flag in your IDE in 5 minutes with LaunchDarkly’s MCP server ⏰

How to create, evaluate, and modify flags from within your IDE or AI client using natural language with LaunchDarkly's new MCP server. Follow along with this tutorial for step by step instructions.

Read full post

👋 Kindness is contagious

Explore this insightful write-up embraced by the inclusive DEV Community. Tech enthusiasts of all skill levels can contribute insights and expand our shared knowledge.

Spreading a simple "thank you" uplifts creators—let them know your thoughts in the discussion below!

At DEV, collaborative learning fuels growth and forges stronger connections. If this piece resonated with you, a brief note of thanks goes a long way.

Okay