Search
Tweets
Recent Changes
« Java: Convert MessageDigest output to hex | Main | Euro-only Ford Focus ST »
Saturday
Sep102005

Java Nibbles

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: 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

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>