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.

I have seen a practice from time to time that "feels" wrong, but I can't quite articulate what is wrong about it. Or maybe it's just my prejudice. Here goes:

A developer defines a method with a boolean as one of its parameters, and that method calls another, and so on, and eventually that boolean is used, solely to determine whether or not to take a certain action. This might be used, for example, to allow the action only if the user has certain rights, or perhaps if we are (or aren't) in test mode or batch mode or live mode, or perhaps only when the system is in a certain state.

Well there is always another way to do it, whether by querying when it is time to take the action (rather than passing the parameter), or by having multiple versions of the method, or multiple implementations of the class, etc. My question isn't so much how to improve this, but rather whether or not it really is wrong (as I suspect), and if it is, what is wrong about it.

share|improve this question
10  
Martin Fowler has an article about this: martinfowler.com/bliki/FlagArgument.html –  Christoffer Hammarström May 10 '12 at 14:17
2  

17 Answers 17

up vote 26 down vote accepted

Yes, this is likely a code smell, which would lead to unmaintainable code that is difficult to understand and that has a lower risk of being easily re-used.

As other posters have noted context is everything (don't go in heavy-handed if it's a one off or if the practise has been acknowledged as deliberately incurred technical debt to be re-factored later) but broadly speaking if there is a parameter passed into a function that selects specific behaviour to be executed then further stepwise refinement is required; Breaking up this function in to smaller functions will produce more highly cohesive ones.

So what is a highly cohesive function?

It's a function that does one thing and one thing only.

The problem with a parameter passed in as you describe is that the function is doing more than two things; it may or may not check the users access rights depending on the state of the boolean parameter, then depending on that decision tree it will carry out a piece of functionality.

It would be better to separate the concerns of Access Control from the concerns of Task, Action or Command.

As you have already noted the intertwining of theses concerns seems off.

So the notion of Cohesiveness helps us identify that the function in question is not highly cohesive and that we could refactor the code to produce a set of more cohesive functions.

So the question could be restated; Given that we all agree passing behavioural selection parameters is best avoided how do we improve matters?

I would get rid of the parameter completely. Having the ability to turn off access control even for testing is a potential security risk. For testing purposes either or the access check to test both the access allowed and access denied scenarios.

Ref: Cohesion (computer science)

share|improve this answer
1  
Thanks Ray. Sounds like it will be easy enough to re-factor when time permits. Might be worth dropping a TODO comment in to highlight the issue, striking a balance between technical authority and sensitivity to the pressure that we are sometimes under to get things done. –  Rob May 10 '12 at 14:00

I stopped using this pattern a long time ago, for a very simple reason; maintenance cost. Several times I found that I had some function say frobnicate(something, forwards_flag) which was called many times in my code, and needed to locate all the places in the code where the value false was passed as the value of forwards_flag. You can't easily search for those, so this becomes a maintenance headache. And if you need to make a bugfix at each of those sites, you may have an unfortunate problem if you miss one.

But this specific problem is easily fixed without fundamentally changing the approach:

enum FrobnicationDirection {
  FrobnicateForwards,
  FrobnicateBackwards;
};

void frobnicate(Object what, FrobnicationDirection direction);

With this code, one would only need to search for instances of FrobnicateBackwards. While it's possible there is some code which assigns this to a variable so you have to follow a few threads of control, I find in practice that this is rare enough that this alternative works OK.

However, there is another problem with passing the flag in this way, at least in principle. This is that some (only some) systems having this design may be exposing too much knowledge about the implementation details of the deeply-nested parts of the code (which uses the flag) to the outer layers (which need to know which value to pass in this flag). To use Larry Constantine's terminology, this design may have over-strong coupling between the setter and the user of the boolean flag. Franky though it's hard to say with any degree of certainty on this question without knowing more about the codebase.

To address the specific examples you give, I would have some degree of concern in each but mainly for reasons of risk/correctness. That is, if your system needs to pass around flags which indicate what state the system is in, you may find that you've got code which should have taken account of this but doesn't check the parameter (because it was not passed to this function). So you have a bug because someone omitted to pass the parameter.

It's also worth admitting that a system-state indicator that needs to be passed to almost every function is in fact essentially a global variable. Many of the downsides of a global variable will apply. I think in many cases it is better practice to encapsulate the knowledge of the system state (or the user's credentials, or the system's identity) within an object which is responsible for acting correctly on the basis of that data. Then you pass around a reference to that object as opposed to the raw data. The key concept here is encapsulation.

share|improve this answer
7  
Really great concrete examples as well as insight into the nature of what we're dealing with and how it affects us. –  Ray May 9 '12 at 23:25
13  
+1. I use enums for this as much as possible. I've seen functions where extra bool parameters have been added later, and calls start to look like DoSomething( myObject, false, false, true, false ). It's impossible to figure out what the extra boolean arguments mean, whereas with meaningfully-named enum values, it's easy. –  Graeme Perrow May 10 '12 at 18:42

This is not necessarily wrong but it can represent a code smell.

The basic scenario that should be avoided regarding boolean parameters is:

public void foo(boolean flag) {
    doThis();
    if (flag)
        doThat();
}

Then when calling you'd typically call foo(false) and foo(true) depending on the exact behavior you want.

This is really a problem because it's a case of bad cohesion. You're creating a dependency between methods that is not really necessary.

What you should be doing in this case is leaving doThis and doThat as separate and public methods then doing:

doThis();
doThat();

or

doThis();

That way you leave the correct decision to the caller (exactly as if you were passing a boolean parameter) without create coupling.

Of course not all boolean parameters are used in such bad way but it's definitely a code smell and you're right to get suspicious if you see that a lot in the source code.

This is just one example of how to solve this problem based on the examples I wrote. There are other cases where a different approach will be necessary.

There is a good article from Martin Fowler explaining in further details the same idea.

PS: if method foo instead of calling two simple methods had a more complex implementation then all you have to do is apply a small refactoring extracting methods so the resulting code looks similar to the implementation of foo that I wrote.

share|improve this answer
1  
Thanks for calling out the term "code smell"--I knew it smelled bad, but couldn't quite get at what the smell was. Your example is pretty much spot-on with what I'm looking at. –  Ray May 10 '12 at 11:00
9  
There are lots of situations where if (flag) doThat() inside foo() is legitimate. Pushing the decision about invoking doThat() to every caller forces repetition that will have to be removed if you later find out for some methods, the flag behavior also needs to call doTheOther(). I'd much rather put dependencies between methods in the same class than have to go scour all of the callers later. –  Blrfl May 10 '12 at 13:46
2  
If calling two methods one after the other or one method alone can be considered redundant then it's also redundant how you write a try-catch block or maybe an if else. Does it mean you will write a function to abstract all of them? No! Be careful, creating one method that all it does is calling two other methods does not necessarily represent a good abstraction. –  Alex May 10 '12 at 20:46
1  
+1 for the link to Martin Fowler's article. –  Stefano Ricciardi Feb 25 at 14:49

First off: programming is not a science so much as it is an art. So there is very rarely a "wrong" and a "right" way to program. Most coding-standards are merely "preferences" that some programmers consider useful; but ultimately they are rather arbitrary. So I would never label a choice of parameter to be "wrong" in and of itself -- and certainly not something as generic and useful as a boolean parameter. The use of a boolean (or an int, for that matter) to encapsulate state is perfectly justifiable in many cases.

Coding decisions, by & large, should be based primarily on performance and maintainability. If performance isn't at stake (and I can't imagine how it ever could be in your examples), then your next consideration should be: how easy will this be for me (or a future redactor) to maintain? Is it intuitive and understandable? Is it isolated? Your example of chained function calls does in fact seem potentially brittle in this respect: if you decide to change your bIsUp to bIsDown, how many other places in the code will need to be changed too? Also, is your paramater list ballooning? If your function has 17 parameters, then readability is an issue, and you need to reconsider whether you are appreciating the benefits of object-oriented architecture.

share|improve this answer
2  
I appreciate the caveat in the first paragraph. I was being intentionally provocative by saying "wrong", and certainly acknowledge that we're dealing in the realm of "best practices" and design principles, and that these sorts of things are often situational, and one must weigh multiple factors –  Ray May 9 '12 at 23:23
1  
+1 for philosophical flavor in the answer –  Maksee May 10 '12 at 3:44
5  
Your answer reminds me of a quote that I can't remember the source of - "if your function has 17 parameters, you're probably missing one". –  Joris Timmermans May 10 '12 at 10:25

I think Robert C Martins Clean code article states that you should eliminate boolean arguments where possible as they show a method does more than one thing. A method should do one thing and one thing only I think is one of his mottos.

share|improve this answer

I think the most important thing here is to be practical.

When the boolean determines the entire behavior, just make a second method.

When the boolean only determines a little bit of behaviour in the middle, you might want to keep it in one to cut down on code duplication. Where possible, you might even be able to split the method in three: Two calling methods for either boolean option, and one that does the bulk of the work.

For example:

private void FooInternal(bool flag)
{
  //do work
}

public void Foo1()
{
  FooInternal(true);
}

public void Foo2()
{
  FooInternal(false);
}

Of course, in practice you'll always have a point in between these extremes. Usually I just go with what feels right, but I prefer to err on the side of less code duplication.

share|improve this answer

I like the approach of customizing behavior through builder methods that return immutable instances. Here's how Guava Splitter uses it:

private static final Splitter MY_SPLITTER = Splitter.on(',')
       .trimResults()
       .omitEmptyStrings();

MY_SPLITTER.split("one,,,,  two,three");

The benefits of this are:

  • Superior readibility
  • Clear separation of configuration vs. action methods
  • Promotes cohesion by forcing you to think about what the object is, what it should and shouldn't do. In this case it's a Splitter. You'd never put someVaguelyStringRelatedOperation(List<Entity> myEntities) in a class called Splitter, but you'd think about putting it as a static method in a StringUtils class.
  • The instances are pre-configured therefore readily dependency-injectable. The client doesn't need to worry about whether to pass true or false to a method to get the correct behavior.
share|improve this answer
1  
I'm partial to your solution as a big Guava lover and evangelist... but I can't give you a +1, because you skip over the part I'm really looking for, which is what is wrong (or smelly) about the other way. I think it's actually implicit in some of your explanations, so maybe if you could make that explicit, it would answer the question better. –  Ray May 10 '12 at 11:04

Taking an OO perspective, it would be nicer to use different implementations, depending on the value calculated at first.

But I don't think that's pratical all the time.

share|improve this answer

Its not necessarily wrong, but in your concrete example of the action depending on some attribute of the "user" I would pass through a reference to the user rather than a flag.

This clarifies and helps in a number of ways.

Anyone reading the invoking statement will realize that the result will change depending on the user.

In the function which is ultimately called you can easily implement more complex business rules because you can access any of the users attributes.

If one function/method in the "chain" does something different depending on a user attribute, it is very likely that a similar dependency on user attributes will be introduced to some of the other methods in the "chain".

share|improve this answer

I can't quite articulate what is wrong about it.

If it looks like a code smell, feels like a code smell and - well - smells like a code smell, it's probably a code smell.

What you want to do is:

1) Avoid methods with side-effects.

2) Handle necessary states with a central, formal state-machine (like this).

share|improve this answer

Most of the time, I would consider this bad coding. I can think of two cases, however, where this might be a good practice. As there are a lot of answers already saying why it's bad, I offer two times when it might be good:

The first is if each call in the sequence makes sense in its own right. It would make sense if the calling code might be changed from true to false or false to true, or if the called method might be changed to use the boolean parameter directly rather than passing it on. The likelihood of ten such calls in a row is small, but it could happen, and if it did it would be good programming practice.

The second case is a bit of a stretch given that we're dealing with a boolean. But if program has multiple threads or events, passing parameters is the simplest way to track thread/event specific data. For example, a program may get input from two or more sockets. Code running for one socket may need to produce warning messages, and one running for another may not. It then (sort of) makes sense for a boolean set at a very high level to get passed through many method calls to the places where warning messages might be generated. The data can't be saved (except with great difficulty) in any sort of global because multiple threads or interleaved events would each need their own value.

To be sure, in the latter case I'd probably create a class/structure whose only content was a boolean and pass that around instead. I'd be almost certain to need other fields before too long--like where to send the warning messages, for instance.

share|improve this answer

I'm surprised no one has mentioned named-parameters.

The problem I see with boolean-flags is that they hurt readability. For example, what does true in

myObject.UpdateTimestamps(true);

do? I have no idea. But what about:

myObject.UpdateTimestamps(saveChanges: true);

Now it's clear what the parameter we're passing is meant to do: we're telling the function to save its changes. In this case, if the class is non-public, I think the boolean parameter is fine.


Of course, you can't force the users of your class to use named-parameters. For this reason, either an enum or two separate methods are usually preferable, depending on how common your default case is. This is exactly what .Net does:

//Enum used
double a = Math.Round(b, MidpointRounding.AwayFromZero);

//Two separate methods used
IEnumerable<Stuff> ascendingList = c.OrderBy(o => o.Key);
IEnumerable<Stuff> descendingList = c.OrderByDescending(o => o.Key); 
share|improve this answer
1  
The question is not about what is preferable to a behavior determining flag, it's whether such a flag a smell, and if so, why –  Ray May 10 '12 at 17:03
2  
@Ray: I don't see a difference between those two questions. In a language where you can enforce the use of named parameters, or when you can be sure named-parameters will always be used (eg. private methods), boolean parameters are fine. If named parameters can't be enforced by the language (C#) and the class is part of a public API, or if the language doesn't support named parameters (C++), so that code like myFunction(true) might be written, it's a code-smell. –  BlueRaja - Danny Pflughoeft May 10 '12 at 17:32

Definitely a code smell. If it doesn't violate Single Responsibility Principle then it probably violates Tell, Don't Ask. Consider:

If it turns out not to violate one of those two principles, you should still use an enum. Boolean flags are the boolean equivalent of magic numbers. foo(false) makes as much sense as bar(42). Enums can be useful for Strategy Pattern and have the flexibility of letting you add another strategy. (Just remember to name them appropriately.)

Your particular example especially bothers me. Why is this flag passed through so many methods? This sounds like you need to split your parameter into subclasses.

share|improve this answer

It would seem wrong to me. It's actually against our company standard.

What's wrong about it? A boolean field is insufficient for documenting what it means when it's turning on and off behavior.

share|improve this answer
1  
Could you elaborate on this? –  JeffO May 10 '12 at 11:35
2  
It's essentialy James Youngman's answer: BOOL isn't self-documenting but FrobnicationDirection is. –  MSalters May 10 '12 at 12:35

I agree with all the concerns of using Boolean Parameters to not determine performance in order to ; improve, Readability, Reliability, lowering Complexity, Lowering risks from poor Encapsulation & Cohesion and lower Total Cost of Ownership with Maintainability.

I started designing hardware in the mid 70's which we now call SCADA (supervisory control and data acquisition) and these were fine tuned hardware with machine code in EPROM running macro remote controls and collecting high speed data.

The Logic is called Mealey & Moore machines which we call now Finite State Machines. These also must be done in the same rules as above, unless it is a real time machine with a finite execution time and then shortcuts must be done to serve the purpose.

The data is synchronous but commands are asynchronous and the command logic follows memoryless Boolean logic but with sequential commands based on memory of previous, present and desired next state. In order for that to function in the most efficient machine language (only 64kB), great care was taken to define every process in a heuristic IBM HIPO fashion. That sometimes meant passing Boolean variables and doing indexed branches.

But now with lots of memory and ease of OOK, Encapsulation is an essential ingredient today but a penalty when code was counted in bytes for real time and SCADA machine code..

share|improve this answer

Context is important. Such methods are pretty common in iOS. As just one often-used example, UINavigationController provides the method -pushViewController:animated:, and the animated parameter is a BOOL. The method performs essentially the same function either way, but it animates the transition from one view controller to another if you pass in YES, and doesn't if you pass NO. This seems entirely reasonable; it'd be silly to have to provide two methods in place of this one just so you could determine whether or not to use animation.

It may be easier to justify this sort of thing in Objective-C, where the method-naming syntax provides more context for each parameter than you get in languages like C and Java. Nevertheless, I'd think that a method that takes a single parameter could easily take a boolean and still make sense:

file.saveWithEncryption(false);    // is there any doubt about the meaning of 'false' here?
share|improve this answer
13  
Actually I have no clue what false means in the file.saveWithEncryption example. Does it mean that it will save without encryption? If so, why in the world would the method have "with encryption" right in the name? I could understand have a method like save(boolean withEncryption), but when I see file.save(false), it is not at all obvious at a glance that the parameter indicates that it would be with or without encryption. I think, in fact, this makes James Youngman's first point, about using an enum. –  Ray May 9 '12 at 23:20
6  
An alternative hypothesis is that false means, don't overwirte any existing file of the same name. Contrived example I know, but to be sure you'd need to check the documentation (or code) for the function. –  James Youngman May 9 '12 at 23:34
4  
A method named saveWithEncryption that sometimes doesn't save with encryption is a bug. It should possiby be file.encrypt().save(), or like Javas new EncryptingOutputStream(new FileOutputStream(...)).write(file). –  Christoffer Hammarström May 10 '12 at 14:09
2  
Actually, code that does something else than what it says doesn't work, and is thus a bug. It does not fly to make a method named saveWithEncryption(boolean) that sometimes saves without encryption, just like it doesn't fly to make a saveWithoutEncryption(boolean) that sometimes saves with encryption. –  Christoffer Hammarström May 10 '12 at 15:10
2  
The method is bad, because there is obviously "doubt about the meaning of 'false' here". Anyway, i would never write a method like that in the first place. Saving and encrypting are separate actions, and a method should do one thing and do it well. See my earlier comments for better examples how to do it. –  Christoffer Hammarström May 10 '12 at 17:27

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.