There are many cases when Java primitive wrappers are useful, and where null have a different meaning than the default value. However, there are one case where it mostly causes problems: in the java.lang.Boolean.
Using a java.lang.Boolean instead of the primitive type boolean often causes problems, mainly because of its tri-state nature. At first we can find it nice to be able to "define" a boolean as "not defined" (null), but it is much better to define a good default value, and design boolean variables so that "not (actively) defined" and false actually has the same meaning. If we need three states it is better to use an enum.
One immediate advantage of using primitive booleans is that we now can get rid of null checks:
if (valid != null && valid)
becomes
if (valid)
The most important win, however, is that we now must take the right decision of what value the field should have at any particular moment. We cannot leave it in a state where we say ("I do not know what value to give this field, I just wait and see).
Sometimes the problem is inherited from a database table, in which a boolean field is not marked "NOT NULL" and therefore can have null, 0 or 1. I believe a system which allows this is badly designed.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment