Saturday
Sep102005
Java Nibbles
Saturday, September 10, 2005 at 12:19PM
As part of a Top Secret project I'm working on, I've been thinking really hard about the quality of the code I am writing. I've noticed something that I thought I'd mention out loud:
It seems easy, right? You've got a
What about
If the object we are comparing ourselves to does not have a null property, then we are save to do an
equals() and toString() in Java are tricky.It seems easy, right? You've got a
User object and you want toString() to return the user's name. What if the name wasn't set? Do you really want to return null? Better put a check and return "" if not.What about
equals()? Most of these are huge blocks of if(!obj.someProperty().equals(this.property)) type mumbo-jumbo. What if the object you are comparing youself to has some nulls? All those internal calls to equals() could generate an NPE. My usual solution is something like:
if(obj.getProperty() != null) {
if(!obj.getProperty().equals(this.property)) {
return false;
}
} else if(this.property != null) {
return false;
}
If the object we are comparing ourselves to does not have a null property, then we are save to do an
equals(). If the property IS null, then we just check if our instance of that property is null. If it's not, this thing isn't equal!

Reader Comments