|
Pankaj Kumar's WeblogRandom thoughts, musings, experiences, ideas, and opinions |
November 29, 2006How hard is test for equality in Java -- the answer will surprise youA post at THE DAILY WTF includes a function with a compound if statement consisting of eight lines of code to set a flag when the Boolean argument is not equal to a Boolean member, suggesting that the code is correct but overly complex and verbose. /** Set the value of the isRecordLocked attribute. @param newValue is the new isRecordLocked value. */ public void setIsRecordLocked(Boolean newValue) { // Update state if required. if (isRecordLocked != null) { if (newValue == null || !isRecordLocked.equals(newValue)) { context.setDirty(true); } } else if (newValue != null) { context.setDirty(true); } // Change the value. isRecordLocked = newValue; } The post also includes a suggestion that the compound if statement can be replaced entirely by a much more understandable one-liner, but doesn't really include the one-liner (perhaps obvious to the submitter). I struggled for few minutes to figure out the obvious one liner, but couldn't come up with anything signficantly better. The problem is that a simple (A != B) doesn't work for Java Objects (and Boolean is an Object), for either A or B could be null and invoking equals method on null would result in a NullPointerException. I clicked to see the comments, hoping to find the elusive one-liner in the copious comments (137, when I checked). No luck there. Though some people pointed out that there was nothing wrong with the code, most attempts to better the code resulted in buggy code. Posted by pankaj at November 29, 2006 03:39 PMComments
Post a comment
|
|
|
Disclaimer: Views expressed here are my own and do not represent those of my employer.
© 2001-2005 Pankaj kumar. All Rights Reserved. |
|