Code Smell 62 - Flag Variables
16 April, 2023
0
0
0
Contributors
TL;DR: Fun with Flags
Flags indicate what happened. Unless their name is too generic.
Problems
- Readability
- Maintainability
- Coupling
Solutions
- Use meaningful names
- Try to avoid flags. They generate coupling.
Sample Code
Wrong
<?
function dummy() {
$flag = true;
while ($flag == true) {
$result = doSomething();
if ($result) {
$flag = false;
}
}
}
Right
<?
function dummyFunction()
{
$atLeastOneElementWasFound = false;
while (!$atLeastOneElementWasFound) {
$elementSatisfies = doSomething();
if ($elementSatisfies) {
$atLeastOneElementWasFound = true;
}
}
}
Detection
We can search all the code for bad named flags.
Tags
- Readability
Conclusion
Flags are widespread on production code. We should restrict their usage and use clear and intention revealing names.
Relations
Code Smell 51 - Double Negatives
Code Smell 07 - Boolean Variables
More Info
%[https://en.wikipedia.org/wiki/Boolean_flag]
What exactly is a name - Part II Rehab
If you lie to the compiler, it will get its revenge.
Henry Spencer
Software Engineering Great Quotes
This article is part of the CodeSmell Series.
How to Find the Stinky Parts of your Code