QualityCode.com Essay: Avoid Boolean Parameters
Although boolean parameters seem like one of the easiest things to deal with, they can actually be a nightmare. They can be hard to understand, and can lead to maintenance problems.
I’m not talking about when you call a function to enable a mode, like SetBold(TRUE). That makes sense (although in some cases it might be better to replace it with separate EnableBold() and DisableBold() functions).
Rather, I’m talking about function calls like SelectItem(hWnd, TRUE, FALSE, FALSE). Just looking at the call, you have absolutely no idea what the parameters mean. And it is far too easy to accidentally switch the sequence and get unexpected results.
There are several approaches to avoiding (or fixing) function signatures like this:
First, question whether each parameter is even required. Perhaps there should be two separate functions to handle the TRUE/FALSE cases for one parameter. For example, SelectItem() and SelectAndOpenItem(), or SelectItem() and UnSelectItem(). Perhaps the function has a way to determine the appropriate value of one of the parameters based on the others. Perhaps it would be better to pass a higher-level structure (or class) instead of a handful of its members.
Another consideration is whether each parameter should really be a boolean. Perhaps today you have choices of open or don’t open. But tomorrow you might also have highlight; and open and select. Instead of adding still more boolean flags (ugh!), the appropriate solution would be to have an enum that defines all the possible values, and just pass one in. For example: : SelectAndOpenItem(hWnd, HIGHLIGHT)
There are three big benefits:
- Just looking at the function call, it is clear what is being attempted
- It is impossible to try to choose two mutually exclusive choices
- There are fewer parameters to understand and get right
Sometimes it really does make sense to pass a BOOL value (but aim for at most one per function!). And even those cases are far less common than you might think.
Any time you are about to create a function that takes a Boolean parameter, think twice.