Alex Rivera | Logout

Does it make sense to self check for null in Java

Asked 2012-01-26T13:11:04.130
8

I often see java SourceCode where a null as value for a method or constructor is not allowed. A Typical implementation of this looks like

public void someMethod(Object someObject){

    if(someObject == null) throw new NullPointerException()

    someObject.aMethodCall()

}

I see no sense for myself in that at all, because if I attempt to call a Method on a nullPointer the NullPointerException is thrown anyways. I would see a sense if this method would throw an IllegalArgumentException or some other custom-made exception. Can someone clearify , why this check seems to makes sense (as I see it very often I'm assuming, that there has to be sense behind that), or why it's complete nonsense

Edit
Report

2 Answers

9

The code you posted makes absolutely no sense at all. It looks like a strong case of cargo cult programming. Most likely, somebody implemented a useful test to check for pre-conditions once and somebody else adapted the test to look like this.

answered 2012-01-26T13:13:21.110
5

Of course you want to check for null. This is a pre-condition for your method, part of its contract with clients. If your method cannot accept null input, you need to enforce that.

The choice of exception could be better. I usually go with an IllegalArgumentException.

If it's the brevity of the method that bothers you, I have to say I agree. No new info there.

answered 2012-01-26T13:15:42.607

Your Answer