True, False, or New?

        Submitter: Tal Rotbart

        Language: Java

        Date:        2003/12/12

This particular instance of stupid code has more than one skin. A common manifestation is, for instance, returning from a function with

return new Boolean(true);
return new Boolean(false);

Why would anyone instantiate a new instance of class java.lang.Boolean?! Clearly it is obvious that there are only two possible instances of class Boolean - Boolean.TRUE and Boolean.FALSE

Looking under the outer skin, we find another piece of stupid code: the Java implementation itself sucks. Why did Sun engineers leave a non-private constructor in the Boolean wrapper class?

The Java 2 documentation weasels out:

Note: It is rarely appropriate to use this constructor. Unless a new
instance is required, the static factory valueOf(boolean) is
generally a better choice. It is likely to yield significantly
better space and time performance.

Note that valueOf(boolean) appeared only in 1.4. Before that the preferred method was

Boolean instance = bool ? Boolean.TRUE : Boolean.FALSE; 

In either case only the static instances are used.

Actually, the documentation is a cover-up. If you are a registered member of Sun Developer Network, you can look at this bug report (#4792325).

I am not sure if I can reproduce the bug description verbatim here - it might break all sorts of IP restrictions. Anyway, it basically says that the bug is real, exists on all platforms, is always reproducible, is simple to fix, and won't be fixed because it's too late and will break tons of existing code that calls the public constructor. If it were fixed though programs would use much less memory and Booleans could be compared for identity with "==" & "!=".

A classic example of stupid code that cannot even be fixed.