Nested boolean conditions express a business rule. Not an IF
TL;DR: Avoid checking for boolean expressions and returning an explicit boolean.
-
Declarativeness
-
Ninja Code
-
Readability
- Return a boolean business formula value.
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;
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
def is_platypus(self):
return self.is_mammal() &&
self.has_fur() &&
self.has_beak() &&
self.has_tail() &&
self.can_swim()
# You can even group conditions according to animal taxonomies
[X] Automatic
Based on syntax trees, we can safely refactor the code removing the explicit boolean value.
- Boolean
Beware of returning booleans.
After the return, you will need an If statement which is also a code smell.
Code Smell 101 - Comparison Against Booleans
Code Smell 24 - Boolean Coercions
Code Smell 62 - Flag Variables
Code Smell 80 - Nested Try/Catch
Code Smell 184 - Exception Arrow Code
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
Software Engineering Great Quotes
This article is part of the CodeSmell Series.