Readability of boolean parameters
Take the following Java code fragment:
List widgets = ...; PrintWriter writer = ...; WidgetFormatter formatter = new WidgetFormatter(); formatter.formatWidgets(widgets, writer, true);
Given no more context than this, it is fairly easy for anyone to look at this bit of code and determine that a collection of widgets is being formatted to a textual output source. However, it’s hard to determine that the true
parameter means to recursively format elements. I find this is often the case with boolean parameters nestled in a long parameter list.
Booleans on their own are not necessarily unreadable. Look at the getter/setter pair for this “recursive” property:
formatter.setRecursive(true); if (formater.isRecursive() { ... }
It is quite clear that true
means recursive.
In order to make the constructor more readable, you can create constants:
public static final boolean RECURSIVE = true; public static final boolean NOT_RECURSIVE = false;
Now the constructor becomes:
formatter.formatWidgets(widgets, writer, RECURSIVE);
Much better. The only problem is that an undisciplined programmer could still use true
, rather than using the constant. By using an enum, rather than a boolean, you could force people to use the constants. Unfortunately, enums are a bit of a pain to use in Java. But they’re not a pain enough that they should be avoided. The Jakarta commons-lang library has a great Enum class where all you have to do is subclass it. And finally Java will get real enums in version 1.5.
I prefer the enum alternative, even if it is a bit more anal and more code. I still use boolean constants occasionally, especially if I do not want to change the signature of an existing method. However, the 10 extra lines of code to create an enum (if you’re using commons-lang) is usually well worth it. And a good editor or IDE will help you create these 10 lines of code automatically, too. Remember, code is read many more than it is written, so the extra time to write those 10 lines of code often pays for itself many times over in the future.