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
In any case, it is always good practice to CHECK for nulls on ANY parameters passed in before you attempt to operate on them, so you don't get NullPointerExceptions when someone passes you bad data.
It is safe : foo. bar() will never be executed if foo == null. It prevents from bad practice such as catching NullPointerExceptions (most of the time due to a bug in your code) It should execute as fast or even faster than other methods (even though I think it should be almost impossible to notice it).
It is a good idea to check for null explicitly because: You can catch the error earlier. You can provide a more descriptive error message.
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.
There is a corner case where something like that would make sense. If you don't use someObject immediately short-circuiting the error case to the start of the function can be useful.
public void someMethod(Object someObject){
if(someObject == null) throw new NullPointerException();
expensiveOperationNotUsingSomeObject();
someObject.aMethodCall();
}
No, that doesn't make much sense as it stands, but only because throwing an NPE doesn't add any useful info.
You could make the error nicer by throwing (for example) an IllegalStateException:
if (someObject == null) throw new IllegalStateException("someObject was null");
But that doesn't add a great deal of value either - other than being specific about what is null (which can be useful in more complex methods)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With