No booleans as parameters, please

Ok, first of all; why are boolean parameters bad?

Because they are not input data to the method, but control values. This means that someone from the outside (e.g. the upper level method that calls yours) has explicit control over the method: It simply tells the function what to do. It’s like someone talks to you like: “Draw a smiley face USING A PENCIL” and after that “Sign this paper WITH YOUR PEN”.

You probably know how a drawing is usually created, and you don’t need anyone to tell you what tool to use. The same is true for the signature. There’s a very good example which is usually used for explaining encapsulation: “I don’t need to know how an engine works in order to be able to drive a car”. It’s similar with methods. The caller should not know how the called method achieves a certain goal; it knows that the lower method CAN achieve that goal and that’s it.

They’re also bad because they make your code unreadable. You see that you have to pass  boolean value to a method, but you have no idea what is it used for. So you go to the implementation and check it, wasting precious seconds (or even minutes, if the code is complicated enough)

So, how do we get rid of such methods? Simple. Write two functions:

  1. copy your original function, and give it a self-explanatory name
  2. eliminate the parameter from the newly created method. Replace all the occurrences of the parameter with the value ‘true’
  3. replace the old method call with the new one everywhere where the method was called with true
  4. now rename your original method
  5. eliminate the parameter and replace it with the value ‘false’
  6. solve your compilation problems
  7. refactor the new methods, simplifying boolean expressions (remember? you have trues and falses explicitly hardwired into your code. Those should be eliminated), extracting the common parts and renaming if its needed
  8. be happy, you’ve got rid of your control values

If your booleans are getting out of control, you can try to consider introducing polymorphism. That may lead to even more beautiful design.

Author: tamasgyorfi

Senior software engineer, certified enterprise architect and certified Scrum master. Feel free to connect on Twitter: @tamasgyorfi

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s