Is using flags very often in code advisable?
Asked Answered
N

14

8

I came across lot of flags while reading someone else code,

if (condition1) 
    var1 = true
else
    var1 = false

then later,

if (var1 == true)
    // do something.

There are lot of flags like this. I eager to know, is using flags very often in code advisable?

Nerveracking answered 30/4, 2009 at 7:4 Comment(3)
this looks like coding horror :) i keep expressing my distaste about this kind of coding in every question i can find related to this. If (condition) {return true;} else {return false;} OMG!Sall
@MasterPeter: I agree, in fact I listed that as one of my "programmer ignorance" pet peeves: stackoverflow.com/questions/423823.Capstan
@Brian: I may have got there before you #424323Coly
C
14

This:

if (condition1)
   var1= true;
else
   var1 = false;

Is a classic badly written code.
Instead you should write:

var1 = condition1;

And yes, flags are very useful for making the code be more readable and possibly, faster.

Carduaceous answered 30/4, 2009 at 7:18 Comment(0)
H
7

It's advisable if condition1 is something quite complicated - like if (A && (B || C) && !D) or contains a lot of overhead (if (somethingTimeConsumingThatWontChange())) then it makes sense to store that result instead of copy-pasting the code.

If condition1 is just a simple comparison then no, I wouldn't use a flag.

Hairline answered 30/4, 2009 at 7:10 Comment(1)
"It's advisable if condition1 is something quite complicated - like if (A && (B || C) && !D)" Of course, then you would just do: bool var1 = A && (B || C) && !D, rather than making an entire 'ii' statement. Also if 'var1' is a flag, just do if (var1), not if (var1==true)Buhrstone
T
4

This is pretty subjective, and depends on the rest of the code. "Flags" as you call them have their place.

Tananarive answered 30/4, 2009 at 7:9 Comment(0)
K
2

First of all, this code should read like this:

var1 = condition1;

if( var1 )

// No need to compare *true* to *true* when you're looking for *true*

As for the number of flags, there are more elegant ways of branching your code. For instance , when using javascript you can do stuff like this:

var methodName = someFunctionThatReturnsAString();

// assuming you name the method according to what's returned
myObject[ methodName ]();

instead of

if( someFunctionThatReturnsAString === 'myPreferedMethod' ){
    myObject.myPreferedMethod();
}else{
    myObject.theOtherMethod();
}

If you're using a strongly typed language, polymorphism is your friend. I think the technique is refered to as polymorphic dispatch

Kendricks answered 30/4, 2009 at 7:17 Comment(0)
P
2

I remember this Replace Temp var with Query method from the refactoring book. I think this refactoring will make the code more readable, but, I agree that it might affect performance when the query method is expensive ... (But, maybe the query method can be put in its own class, and the result can be cached into that class).

Planoconvex answered 30/4, 2009 at 7:22 Comment(0)
R
2

This is question is a bit generic. The answer depends on what you want to do and with which language you want it to do. Assuming an OO context than there could be better approaches.

If the condition is the result of some object state than the "flag" should propably be a property of the object itself. If it is a condition of the running application and you have a lot of these things it might could be that you should think about a state pattern/state machine.

Rhetic answered 30/4, 2009 at 7:24 Comment(0)
G
2

Flags are very useful - but give them sensible names, e.g. using "Is" or similar in their names.

For example, compare:

if(Direction)    {/* do something */}
if(PowerSetting) {/* do something else */}

with:

if(DirectionIsUp) {/* do something */}
if(PowerIsOn)     {/* do something else */}
Guanabara answered 30/4, 2009 at 17:26 Comment(0)
S
1

If it is readable and does the job then there's nothing wrong with it. Just make use of "has" and "is" prefix to make it more readable:

var $isNewRecord;
var $hasUpdated;

if ($isNewRecord)
{
}

if ($hasUpdated)
{
}
Swordbill answered 30/4, 2009 at 7:48 Comment(0)
J
0

That depends on the condition and how many times it's used. Anyway, refactoring into function (preferably caching the result if condition is slow to calculate) might give you a lot more readable code.

Consider for example this:

def checkCondition():
  import __builtin__ as cached
  try:
      return cached.conditionValue
  except NameError:
      cached.conditionValue = someSlowFunction()
      return cached.conditionValue

As for coding style:

if (condition1)
   var1= true
else
   var1 = false

I hate that kind of code. It should be either simply:

var1 = condition1

or if you want to assure that's result is boolean:

var1 = bool(condition1)

if (var1 == true)

Again. Bad coding style. It's:

if (var1)
Judicative answered 30/4, 2009 at 7:50 Comment(0)
S
0

Bearing in mind that that code could be more readably written as

var1 = condition1

, this assignment has some useful properties if used well. One use case is to name a complicated calculation without breaking it out into a function:

user_is_on_fire = condition_that_holds_when_user_is_on_fire

That allows one to explain what one is using the condition to mean, which is often not obvious from the bare condition.

If evaluating the condition is expensive (or has side effects), it might also be desirable to store the result locally rather than reevaluate the condition.

Some caveats: Badly named flags will tend to make the code less readable. So will flags that are set far from the place where they are used. Also, the fact that one wants to use flags is a code smell suggesting that one should consider breaking the condition out into a function.

D'A

Sensualism answered 30/4, 2009 at 7:59 Comment(0)
C
0

Call it flags when you work in a pre-OO language. They are useful to parameterize the behaviour of a piece of code.

You'll find the code hard to follow, soon, however. It would be easier reading/changing/maintaining when you abstract away the differences by e.g. providing a reference to the changeable functionality.

In languages where functions are first-class citisens (e.g. Javascript, Haskell, Lisp, ...), this is a breeze.

In OO languages, you can implement some design patterns like Abstract Factory, Strategy/Policy, ...

Too many switches I personally regard as code smell.

Cappadocia answered 30/4, 2009 at 8:0 Comment(0)
P
0

What i dont like about flags, is when they are called flags, with no comment whatsoever.

e.g

void foo(...){

     bool flag;

    //begin some weird looking code

    if (something)
       [...]
      flag = true; 
 }

They attempt against code redeability. And the poor guy who has to read it months/years after the original programmer is gone, is going to have some hard time trying to understand what the purposse of it originally was.

However, if the flag variable has a representative name, then i think they are ok, as long as used wisely (see other responses).

Pit answered 30/4, 2009 at 17:36 Comment(0)
K
0

Yes, that is just silly nonsensical code.

You can simplify all that down to:

if (condition1)
{
  // do something
}
Klinges answered 30/4, 2009 at 17:46 Comment(0)
W
0

Here's my take. Code using flags:

...
if (dogIsBarking && smellsBad) {
  cleanupNeeded = true;
}
doOtherStuff();
... many lines later
if (cleanupNeeded) {
  startCleanup();
}
...

Very unclean. The programmer simply happens to code in whatever order his mind tells him to. He just added code at a random place to remind himself that cleanup is needed later on... Why didn't he do this:

...
doOtherStuff();
... many lines later
if (dogIsBarking && smellsBad) {
  startCleanup();
}
...

And, following advise from Robert Martin (Clean Code), can refactor logic into more meaningful method:

...
doSomeStuff();
... many lines later
if (dogTookADump()) {
  startCleanup();
}
...
boolean dogTookADump() {
  return (dogIsBarking && smellsBad);
}

So, I have seen lots and lots of code where simple rules like above could be followed, yet people keep adding complications and flags for no reason! Now, there are legit cases where flags might be needed, but for most cases they are one style that programmers are carrying over from the past.

Werra answered 18/4, 2016 at 18:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.