StringBuffer in Action

10/05/2006

Generous to a Fault

As i've worked off and on as a consultant, i've encountered a lot of styles of coding. On one end of the spectrum, you have people who throw caution to the wind and write code to accomplish a task using the most brittle code possible. On the other end, it's very possible to write code so safe, that it becomes perhaps just as difficult to maintain. Recently, i've run into a lot of methods that look like this:

public void doSomething(Object o1, Object o2, Object o3) {

if (o1 != null && o2 != null && o3 != null) {
// do something with o1, o2, and o3.
}

}

and this:

public void doSomething(Collection c) {

if (c != null && c.iterator() != null) {
// loop over the iterator and do something
}

}

Now, I don't mean to single these particular developers out, but quit being so polite. When things will never be null, make sure they aren't. And in the case of calling iterator(), it can't possibly be null. Commons-lang has a Validate utility class which can help you achieve this. Of course, if you're commons-phobic, it would take you about a half hour to write the class yourself and add functionality specific to your company.

So instead, do this:

public void doSomething(Object o1, Object o2, Object o3) {

Validate.notNull(o1, "o1 can't be null");
Validate.notNull(o2, "o2 can't be null");
Validate.notNull(o3, "o3 can't be null");

// do something with o1, o2, and o3.

}


Not only do you begin removing the ugly arrow antipattern, but you'll fail early, and fail with error messages more meaningful than the dreaded NullPointerException on a line of code that has 3+ objects on it of which any could be null. Or worse yet, in the case of the above code, your method will simply return after doing nothing, and you'll have to debug your way in to realize that your temporary null-valued variable that you used to get your code to compile got left in because you realized you were 5 minutes late for a meeting because whomever scheduled it didn't turn the reminder on.

So, quit being so generous. trim() and iterate() will never return null. I promise.