Booleans as Function Parameters Considered Harmful

Let’s start with a quick quiz. What do the following completely made-up lines of code do?:

  1. thing.SetIsVisible( true );
  2. thing.SetVisibile( true );
  3. var item = factory.CreateThing( true );

Although they’re made-up, they could just as easily not be. When you jump into someone else’s code for the first time, all the code might as well be made-up. Some code is easier to understand on first reading than others.

Number 1 is fairly self-explanatory: we want to make ‘thing’ be visible. We can pretty much assume that ‘true’ is visible and ‘false’ is hidden.

Number 2 is getting a little trickier. We would probably assume that ‘true’ makes ‘thing’ visible, but we might have doubts. I say doubts because the function prototype might be something like this:

void SetVisible( bool alsoHighlightIt ) { ... }

In which case, passing ‘false’ still makes it visible, but just without a highlight.

Number 3 is awful. Who’s to say what ‘true’ indicates?

  • Store the item in a cache?
  • Return a new instance?
  • Return a singleton instance?
  • Log the creation?
  • Pass ‘true’ to the item’s constructor?
  • Etc…

Basically, we have no idea.

But, you say, we can just hover over the function and IntelliSense will tell us! True. But who wants to do that? When you’re scanning unknown code, isn’t your mouse cursor over the scrollbar or solution explorer? Why should we have to when there’s such a simple fix?

Here’s the fix: Use Two-State Enums.

Let’s revisit my made-up code:

  1. thing.SetIsVisible( Visibility.Visible );
  2. thing.SetVisibile( VisibilityOptions.WithHighlight );
  3. var item = factory.CreateThing( LifeTimeControl.Singleton );

Much, much easier to understand. A little more typing, admittedly, but worth it.

Bonus Result: When you realise that actually you need more than two states (say visible, hidden, and collapsed, to follow our example), you can just add an enum value, instead of needing to go through all the rest of your coding, changing booleans to the enum you should have used in the first place.

2 Responses to “Booleans as Function Parameters Considered Harmful”

  1. If it’s a Boolean state, provide a single method to test it with a name like isVisible() and then two other methods to turn it on/off, with names like beVisible() and beInvisible()

  2. Enums are never the answer. In this situation I’d either go with a real class for Higlight or Visibility or both! That would make it obvious what the parameter was for. Also an object initializer would do the trick, i.e. “new Thing { Visible = false }”. That comes with new drawbacks such as unability to specify required parameters and readonly fields. Perhaps named parameters comes to c# soon!

Leave a Reply