Widgets How Not To Code #2: Don’t Use Boolean Method Parameters

How Not To Code #2: Don’t Use Boolean Method Parameters

By Nick at August 04, 2012 04:16
Filed Under: Delphi, How Not To Code

Okay, let’s start off with a question.  What do you think this little code snippet does?


Well, I’ll bet your first guess is that it processes customer input.  Good guess!  But what the heck does that False there mean?  It’s a parameter, and presumably it means something is, well, false, or that you don’t want the ProcessCustomerInput to do something, but how can you know?  You can’t.

Using Boolean parameters means that lose information for the reader of your code.  A Boolean parameter communicate nothing about the purpose or meaning of the parameter being passed.  Is False good or bad?  Safe or not safe?  Who knows?  Just as above, you can’t figure out at all what the parameter is supposed to mean or do if all you see is True or False

So if you see that in code, the first thing you’ll probably do is to go to the method declaration, and if the parameter is well named, you might figure out what the parameter does:

procedure ProcessCustomerInput(aKeepDuplicates: Boolean);

So there you go, now you know what the Boolean parameter does – apparently it tells you whether to keep the duplicates or not.  That’s great, but the original coder may not always be so kind and clear.  So if you must use a Boolean parameter, at least make the parameter name descriptive. 

Okay, I take it back – don’t actually ever use a Boolean parameter.  Instead, here’s what I suggest would make for much clearer code:

  TKeepDuplicates = (DoKeepTheDuplicates, DoNotKeepTheDuplicates);

procedure ProcessCustomerInput(aKeepDuplicates: TKeepDuplicates);

and that way you can call


And then your code is eminently readable and clear without having to look up the method declaration.

In addition, this way of doing things is expandable.  If your business rules change, and a third way of processing customer input appears, your code is ready.  With a Boolean parameter, you are stuck with the two options of True and False.

Easy to read, clear, and ready for the future.  Just like code should be.

blog comments powered by Disqus

My Book

A Pithy Quote for You

"Go confidently in the direction of your dreams. Live the life you have imagined."    –  Henry David Thoreau

Amazon Gift Cards

General Disclaimer

The views I express here are entirely my own and not necessarily those of any other rational person or organization.  However, I strongly recommend that you agree with pretty much everything I say because, well, I'm right.  Most of the time. Except when I'm not, in which case, you shouldn't agree with me.