Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

From some open source projects, I gathered the following coding style

void someFunction(bool forget);

void ourFunction() {
  someFunction(false /* forget */);
}    

I always have doubt about what false means here. Does it mean "forget", or does the "forget" refer to its corresponding parameter (like in the case above), and "false" is meant to negate it?

What style is used most often and what is the best way (or some of the better ways) to avoid the ambiguity?

share|improve this question
37  
use enums (even if there is just 2 options) instead of bools –  Esailija Sep 20 '13 at 15:27
20  
Some languages support named arguments. In such languages, you could use someFunction(forget: true); –  Brian Sep 20 '13 at 17:05
3  
I feel obligated to provide Martin Fowler's arguments on Flag Arguments (also talks about boolean setters). In general, try to avoid them. –  FGreg Sep 20 '13 at 18:25
2  
To belabor the obvious, comments can lie. Thus is always better to make your code self-documenting, because some will change true to false and not update the comment. If you can't change the API, then the best way to comment this is someFunction( false /* true=forget, false=remember */) –  Mark Lakata Sep 20 '13 at 21:27
1  
@Bakuriu - actually, I'd probably still have the public API have two separate methods (sortAscending and sortDescending, or similar). Now, inside, they may both call the same private method, which might have this kind of parameter. Actually, if the language supported it, probably what I'd pass in would be a lambda function that contained the sorting direction... –  Clockwork-Muse Sep 21 '13 at 11:56

12 Answers 12

In the sample code you posted, it looks like forget is a flag argument. (I cannot be certain because the function is purely hypothetical.)

Flag arguments are a code smell. They indicate that a function does more than one thing, and a good function should do only one thing.

To avoid the flag argument, break up the function into two functions that explain the difference in the function name.

Flag argument

serveIceCream(bool lowFat)

No flag argument

serveTraditionalIceCream()
serveLowFatIceCream()

edit: Ideally, you don't need to keep around a function with the flag parameter at all. There are cases along the lines of what Fowler calls a tangled implementation where completely separating the functions creates duplicated code. However, the higher the cyclomatic complexity of the parameterized function, the stronger is the argument for getting rid of it.


This is only a hunch, but a parameter named forget sounds like feature envy. Why would a caller tell another object to forget something? There may be a bigger design issue.

share|improve this answer
4  
+17, helmet on. What do the bodies of serveTraditionalIceCream and serveLowFatIceCream look like? I have an enum with 14 types of ice cream. –  JohnMark13 Sep 20 '13 at 21:49
11  
For public methods, this convention is good, but as JohnMark alludes, the other half of SRP is "a good method should be the only method that does what it does". I see there being N+1 variants of this method; N public with no parameters, all of which call one private method with the parameter you're trying to avoid exposing. At some point, you just give up and expose the damn parameter. Code smells don't necessarily mean code should be refactored; they're just things that deserve a second look in a code review. –  KeithS Sep 20 '13 at 21:54
    
@Aaron By "feature envy" what you meant? –  Geek Sep 21 '13 at 3:07

In layman's words:

  • false is a literal.
  • you are passing a literal false
  • you are telling someFunction to not forget
  • you are telling someFunction that the parameter forget is false
  • you are telling someFunction to remember

In my opinion it would be better if the function was like this:

void someFunction(bool remember);

the you can call it

void ourFunction() {
  someFunction(true);
} 

or keep the old name but change your wrapper function to

void ourFunctionWithRemember() {
  someFunction(false);
} 

EDIT:

As @Vorac stated, always strive to use positive words. Double negation is confusing.

share|improve this answer
13  
+1 for the idea to always strive to use positive words. Double negation is confusing. –  Vorac Sep 20 '13 at 15:47
1  
Agreed, great idea. Telling the system to not not do something is confusing. If accepting a boolean parameter, express it positively. –  Brandon Sep 20 '13 at 18:15
    
In most cases, I think you'd also want to be more specific than remember, unless the function name made the meaning of remember very obvious. rememberToCleanUp* or *persist or something. –  itsbruce Sep 21 '13 at 9:17

The parameter may be well-named; it's hard to tell without knowing the name of the function. I assume that the comment was written by the original author of the function, and it was a reminder of what passing false into someFunction means, but for anyone coming along afterward, it's a little unclear at first glance.

Using a positive variable name (suggested in Code Complete) may be the simplest change that would make this snippet easier to read, e.g.

void someFunction(boolean remember);

then ourFunction becomes:

void ourFunction() {
    someFunction(true /* remember */);
}

However, using an enum makes the function call even easier to understand, at the expense of some supporting code:

public enum RememberFoo {
    REMEMBER,
    FORGET
}

...

void someFunction(RememberFoo remember);

...

void ourFunction() {
    someFunction(RememberFoo.REMEMBER);
}

If you're unable to change the signature of someFunction for whatever reason, using a temporary variable makes the code easier to read as well, sort of like simplifying conditionals by introducing a variable for no other reason than to make the code easier to parse by humans.

void someFunction(boolean remember);

...

void ourFunction() {
    boolean remember = false;
    someFunction(remember);
}
share|improve this answer
1  
Setting remember to true means to forget (in your example of someFunction(true /* forget */);) ? –  Brian Sep 20 '13 at 17:11
    
Good catch, thanks. –  Mike Partridge Sep 20 '13 at 17:19
2  
The enum is by far the best solution. Just because a type can be represented as a bool—i.e., they are isomorphic—it doesn’t mean that it should be represented as such. The same argument applies to string and even int. –  Jon Purdy Sep 20 '13 at 23:03

Rename the variable so a bool value makes sense.

This a million times better than adding a comment to explain arguments to a function because the name is ambiguous.

share|improve this answer
3  
That doesn't answer the question. All things are obvious when the method is defined and called in the same file 4 lines apart. But what if all you see at the moment is the caller? What if it has multiple booleans? Sometimes a simple in-line comment goes a long way. –  Brandon Sep 20 '13 at 18:17
    
@Brandon That is not an argument against calling the boolean doNotPersist (or, better, Persist). Calling it "forget" without saying what to forget is frankly unhelpful. Oh, and a method which takes several booleans as an option stinks to high heaven. –  itsbruce Sep 21 '13 at 9:15

Create a local boolean with a more descriptive name, and assign the value to it. That way the meaning will be more clear.

void ourFunction() {
    bool takeAction = false;  /* false means to forget */
    someFunction( takeAction );
}    

If you can't rename the variable, then the comment should be a little more expressive:

void ourFunction() {
    /* false means that the method should forget what was requested */
    someFunction( false );
}    
share|improve this answer
1  
Definitely good advice, but I don't think it addresses the issue that the /* forget */ comment is there to address, which is that without the function declaration right in front of you, it can be difficult to remember what is being set to false. (Which is why I think @Esailija's advice to add an enum is better, and why I love languages that allow named parameters.) –  Steven Burnap Sep 20 '13 at 18:00
    
@StevenBurnap - thanks! You're right in that my old answer wasn't clear enough in addressing the OP's question. I have edited it to make it more clear. –  GlenH7 Sep 20 '13 at 18:11

There is a good article that mentions this exact situation as it refers to Qt-Style APIs. There, it's called The Boolean Parameter Trap and it's worth a read.

The gist of it is:

  1. Overloading the function so that the bool isn't needed is better
  2. Using an enum (as Esailija suggests) is best
share|improve this answer

This is a bizarre comment.

From the compiler's perspective, someFunction(false /* forget */); is actually someFunction(false); (the comment is stripped). So, all that line does is call someFunction with the first (and only) argument set to false.

/* forget */ is just the name of the parameter. It's probably nothing more than a quick (and dirty) reminder, that doesn't really need to be there. Just use a less ambiguous parameter name, and you won't need the comment at all.

share|improve this answer

One of advices of Clean code is to minimize number of unnecessary comments1 (because they tend to rot), and to name functions and methods properly.

Following that, I would just remove the comment. After all, modern IDEs (like eclipse) pop a box with code when you put a mouse over the function. Seeing the code should clear the ambiguity.


1 Commenting some complex code is ok.

share|improve this answer
    
btw Who said something like this : "the worst programmer's problem is how to name variable, and offset by one"? –  BЈовић Sep 20 '13 at 18:45
4  
You're likely looking for martinfowler.com/bliki/TwoHardThings.html as the source of it. I've heard tweaked to "There are only two hard things in Computer Science: cache invalidation, naming things, and off by one errors." –  MichaelT Sep 20 '13 at 18:50
    
@MichaelT Right. Thank you –  BЈовић Sep 20 '13 at 18:53

To belabor the obvious, comments can lie. Thus is always better to make your code self-documenting without resorting to comments to explain, because some person (perhaps you) will change true to false and not update the comment.

If you can't change the API, then I resort to 2 options

  • Change the comment so that it always true, regardless of the code. If you only call this once, this is a good solution, since it keeps the documention local.
     someFunction( false /* true=forget, false=remember */);`
  • Use #defines, especially if you call it more than once.
     #define FORGET   true
     #define REMEMBER false
     someFunction(REMEMBER);
share|improve this answer

I like the answer about making the comment always true, but while good I think it misses the fundamental problem with this code -- it is being called with a literal.

You should avoid using literals when calling methods. Local variables, optional parameters, named parameters, enums -- how you best avoid them will depend upon the language and whats available, but do try to avoid them. Literals have values, but they don't have meaning.

share|improve this answer

In C#, I used named parameters to make this clearer

someFunction(forget: false);

Or enum:

enum Memory { Remember, Forget };

someFunction(Memory.Forget);

Or overloads:

someFunctionForget();

Or polymorphism`:

var foo = new Elephantine();

foo.someFunction();
share|improve this answer

The naming should always resolve ambiguity for booleans. I always name boolean something like 'isThis' or 'shouldDoThat', for example:

void printTree(Tree tree, bool shouldPrintPretty){ ... }

and so on. But when you are referencing someone else's code, its best to just leave comment when passing values.

share|improve this answer
    
how does this answer the question asked? –  gnat Sep 21 '13 at 7:03
    
@gnat I was answering his question about resolving ambiguity with boolean parameters. Maybe I read his question wrong. –  user814628 Sep 22 '13 at 2:32

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.