Code Smell 119 - Stairs Code
Nested boolean conditions express a business rule. Not an IF

TL;DR: Avoid checking for boolean expressions and returning an explicit boolean.
Problems
Declarativeness
Ninja Code
Readability
Solutions
- Return a boolean business formula value.
Context
When dealing with boolean formulas, it is more readable to show a business boolean formula than a stair of boolean checks followed by returning an explicit true/false;
Sample Code
Wrong
def is_platypus(self):
if self.is_mammal():
if self.has_fur():
if self.has_beak():
if self.has_tail():
if self.can_swim():
return True
return False
# This is also wrong since it is polluted with IFs and not readable by a biologist
def is_platypus(self):
if not self.is_mammal():
return False
if not self.has_fur():
return False
if not self.has_beak():
return False
if not self.has_tail():
return False
if not self.can_swim():
return False
return True
Right
def is_platypus(self):
return self.is_mammal() && self.has_fur() && self.has_beak() && self.has_tail() && self.can_swim()
#We can even group conditions according to animal taxonomies
Detection
[X] Automatic
Based on syntax trees, we can safely refactor the code removing the explicit boolean value.
Tags
- Boolean
Conclusion
Beware of returning booleans.
After the return, you will need an If statement which is also a code smell.
Relations
More Info
Credits
Photo by Jukan Tateisi on Unsplash
Thanks again to Nico K. for this suggestion.
The real hero of programming is the one who writes negative code.
Douglas McIlroy
This article is part of the CodeSmell Series.
About the author
I鈥檓 a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.
Comments
Join the discussionI often use object literals in place of if/else or switch statements. JS is nice about that.
That's ok if it brings more declarativeness
But switches violate open closed principle so they are yet another code smell
Thanks Maxi for this great writing. I totally agree with you. I very often introduce methods additional local variables just to make my code more understandable. 馃槉
This case might be (or may not) be another smell.
Do you have a code snippet ?
No I do not have a code snipet, but introducing a variable for betternunderstandg is a widely accepted method in clean code. 馃槈馃槉Maxi Contieri
Code Smells
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.





