DEV Community

Cover image for Code Smell 62 - Flag Variables
Maxi Contieri
Maxi Contieri

Posted on • Edited on • Originally published at maximilianocontieri.com

1

Code Smell 62 - Flag Variables

Flags indicate what happened. Unless their name is too generic.

Problems

  • Readability

  • Maintainability

  • Coupling

Solutions

  1. Use meaningful names

  2. Try to avoid flags. They generate coupling.

Sample Code

Wrong

<?
function dummy() {
$flag = true;
while ($flag == true) {
$result = checkSomething();
if ($result) {
$flag = false;
}
}
}
view raw uselessFlag.php hosted with ❤ by GitHub

Right

<?
function dummy()
{
$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

More Info

Wikipedia


If you lie to the compiler, it will get its revenge.

Henry Spencer


Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (1)

Collapse
 
michaelcurrin profile image
Michael Currin

You suggested to restrict usage but didn't say how or provide and example.

Can I provide an alternative without the flag? Which is shorter and more readable.

while(true) {
  $elementSatisfies = doSomething();
  if (!$elementSatisfies) {
    break;
  }
}
Enter fullscreen mode Exit fullscreen mode

Or even

while(doSomething()) {
  pass
}
Enter fullscreen mode Exit fullscreen mode

MongoDB Atlas runs apps anywhere. Try it now.

MongoDB Atlas runs apps anywhere. Try it now.

MongoDB Atlas lets you build and run modern apps anywhere—across AWS, Azure, and Google Cloud. With availability in 115+ regions, deploy near users, meet compliance, and scale confidently worldwide.

Start Free

👋 Kindness is contagious

Dive into this thoughtful piece, beloved in the supportive DEV Community. Coders of every background are invited to share and elevate our collective know-how.

A sincere "thank you" can brighten someone's day—leave your appreciation below!

On DEV, sharing knowledge smooths our journey and tightens our community bonds. Enjoyed this? A quick thank you to the author is hugely appreciated.

Okay