Rule #1: Go for immutable references -- use "final" while declaring data members as much as you can.
Rule #2: Use transparent (and less verbose) NPE checks
For example, do NOT do this:
if (x == null) {
throw new IllegalArgumentException("'x' is null");
}
x.doSomething();
Rather define a static method like this:
public static <T>T assertNotNull(final T object, final String errorMsg) {
if (object == null) {
throw new IllegalArgumentException(errorMsg);
}
return object;
}
and use it in a fluent style:
assertNotNull(x, "'x' is null").doSomething();
You can probably put the validating method in a utility class to reuse it everywhere. The good thing about this style is this can be used for cases other than NPEs -- for example you can use it to validate other things as well.
Hmm, I'm usually for not creating too much custom syntactic sugar as it tends to hide things, but this looks pretty elegant!
ReplyDeleteYeah, this is a cool little trick. I can see myself using it a lot.
ReplyDeleteExcept that with this message you have to continually use the same code throughout a method using the object under test.
ReplyDeleteCreating pre-conditions either via AOP or at the beginning of the method handles it through the method.
@Anonymous
ReplyDelete> Except that with this message you have to continually use the same code throughout a method using the object under test.
I agree. There is a certain way to use it.
1. Simply call assertNotNull(x) in the beginning of the method (as you suggested).
assertNotNull(x);
//...assert some more...
x.doSomething();
Another way could be something like (this one sucks):
validX = assertNotNull(x);
validX.doSomething();
> Creating pre-conditions either via AOP or at the beginning of the method handles it through the method.
I am interested in practically seeing some AOP code that is just as simple as above to setup.
i do agree this approach with 49%.adding more methods decrease the readablility of the code...
ReplyDelete+1 to separating assertion and invocation of methods on the object. IMHO this:
ReplyDeleteassertNotNull(x);
x.doSomething();
is much more readable than this:
assertNotNull(x).doSomething();
@ppow
ReplyDeleteI agree. The Spring framework uses the same kind of assertion that you suggested.
Sometimes I am so annoyed with Java's verbosity that I just go ahead with the fluent style.
this is good for assignment of members from constructor args as well.
ReplyDeletethis.whatever = notNull(whatever "whatever")
note that if you use google collections you already have exactly this kind of validation, along with a bunch of others.
ReplyDeletesee http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/base/Preconditions.html#checkNotNull(T)
the semantics of the word "assert" is already quite overused, as it is used in Junit, and as a java keyword. checkNotNull looks slightly better.
@Andreas checkNotNull looks good, or perhaps just notNull is a useful candidate too.
ReplyDelete