Showing posts with label boolean. Show all posts
Showing posts with label boolean. Show all posts

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.

Thursday, April 21, 2011

Booleans

Booleans are named after George Boole, a nineteenth century logician. Each boolean variable has one of two values, true or false. These are not the same as the Strings "true" and "false". They are not the same as any numeric value like 1 or 0. They are simply true and false. Booleans are not numbers; they are not Strings. They are simply booleans.
Boolean variables are declared just like any other variable.
boolean test1 = true;
boolean test2 = false; 
Note that true and false are reserved words in Java. These are called the Boolean literals. They are case sensitive. True with a capital T is not the same as true with a little t. The same is true of False and false.

Chitika