Boolean parameters are wrong

by havoc

Today’s simple way to improve your code.

Say you’re reading a program and you see some lines like this:

new ArrayBlockingQueue(10, false);
box.pack_start(child, false, true);

You don’t know what the booleans mean. Say you’re reading it and you see this:

new ArrayBlockingQueue(10, Policy.FAIR);
box.pack_start(child, Packing.FILL);

Which is better?

There’s only one time that a boolean is OK, and that’s when the name of the method (or keyword, in a language that has keyword args) already describes it:

box.set_expand(child, false);

Otherwise, no booleans. I know you’re too lazy to create an enum or flags type, but do it anyway.

Numeric types, for APIs where the number is expected to be a literal rather than a variable name, often have the same problem. But it’s a bit harder to solve in that case. The best solution may be for API users to use named constants.

Mystery-booleans are easy to avoid, though, so just do it.

My Twitter account is @havocp.
Interested in becoming a better software developer? Sign up for my email list and I'll let you know when I write something new.