Coding Style – Are Boolean Arguments Code Smell?

coding-styleparameters

Martin Fowler describes the Flag Argument code smell as a "kind of function argument that tells the function to carry out a different operation depending on its value".

Answers to Is it wrong to use a boolean argument to determine behavior? seem to conflate all boolean arguments with flag arguments. I think that question doesn't fully explore the problem of boolean arguments.

However, I have a feeling that not all boolean arguments are equal.

A use-case for boolean arguments

Imagine a popup that shows a message that is partly dependant on whether a user is logged in or not. We would define a method

show(boolean isLoggedIn)

The method would be called in this way:

popup.show(session.isLoggedIn())

It seems to me that in this example readability and cohesion are not impacted negatively. Furthermore, I don't think that this is a flag argument. It doesn't tell the method how exactly to behave, but conveys the information necessary for the method to make that decision.

Alternatives

I can't think of a way to improve this method using the solutions proposed in the discussion above.

Enum would look something like this:

popup.show(session.isUserLoggedIn()
    ? Popup.ContentType.LoggedIn
    : Popup.ContentType.LoggedOut);

Splitting the method would look like this:

if (session.isUserLoggedIn()) {
    popup.showLoggedInMessage();
} else {
    popup.showLoggedOutMessage();
}

This seems longer and also leads to code duplication if they have common parameters:

if (session.isUserLoggedIn) {
    popup.showLoggedInMessage(commonIntro);
} else {
    popup.showLoggedOutMessage(commonIntro);
}

In my opinion, using a boolean argument is better than both of these approaches.

So, are all boolean arguments a code smell, or can they be a valid technique?

Best Answer

No rule is absolute in software development and everything depends on context.

That being said, I would not consider your example to be necessarily a good case for boolean arguments. An API like show(bool isLoggedIn) does not tell me what is going to happen without me reading documentation or code, whereas functionality of show(string messageToDisplay) would be quite obvious from the signature.

Are boolean arguments a code smell? Yes. As it is something "that possibly indicates a deeper problem". That does not mean they should never ever be used, just that you should consider twice before using them.

Related Topic