Thursday, June 9, 2011

Don't use Evil Boolean Constructors

This is something straight out of the Effective Java book, which every, really, every Java developer should read. But I still find a lot of calls to Boolean constructors, to this very day, 6 years after the book was out. (Has doing code review turned me into a grumpy nagging old man or what?)
The twin constructors of java.lang.Boolean, namely, Boolean(String) and Boolean(boolean) should never be called from within your application. The only legit user of these two constructors is the Boolean class itself. The reason is simple: you only need two Boolean instances, really. One to represent true, one to represent false. That’s it. And these two objects already exist as class variables of Boolean, namely, Boolean.TRUE, and Boolean.FALSE. You only need these two.
You don’t need the constructors for converting from the primitive boolean and String either. There are two static methods available just for this purpose. Boolean.valueOf(String) and Boolean.valueOf(boolean). Instead of saying:
Boolean isMad = new Boolean(true);
Boolean isNotCrazy = new Boolean("TRUE");

say -
Boolean isMad = Boolean.valueOf(true);
Boolean isNotCrazy = Boolean.valueOf("TRUE");

Because valueOf() returns either Boolean.TRUE or Boolean.FALSE, instead of creating another unnecessary Boolean instance. For the case when you already know whether to pass true or false, instead of saying:
book.setRegurgitable(new Boolean(false));

simply say
book.setRegurgitable(Boolean.FALSE);

So, be very suspicious of the existence of “new Boolean” in your codebase. If your code is based on JDK 1.4 or above, really, there shouldn’t be any “new Boolean” anymore, anywhere. In fact, if there’s a legit case when one just have to use the Boolean constructors in their code, please let me know, I’ll be grateful.

No comments:

Post a Comment

Chitika