OK, that’s maybe a bit of an exaggeration. I mean never check null for mandatory input.
I am thoroughly sick of code that doesn’t know what to do returning null. If you don’ t know what to do you should throw an exception. There are only 2 exceptions to this rule:
Here, you can return null and let the calling class figure out to do. But as soon as you have logic in you code, you should stop checking.
If you need something, it can’t be null. Simple. So it’s an exception. Get over it, get a stack trace ASAP, and we can find out what’s wrong.
Don’t cover it with some if null then null crap and pass the buck to the caller. The bug is still there, you’re only making it harder to find.
And if anyone tells you NullPointerException is wrong, don’t worry about them. They haven’t yet realised the truth that is
NullPointerException tells you what’s wrong, where and if you throw it early enough, why.
It’s infinitely prefereable to have a NullPointerException to a mysterious oh where’s my output scenario.
Oh, and I nearly forgot to mention the benefits:
- Your code becomes shorter and more readable, because you stop checking what’s null (no more checking before your call to Collection.iterator())
- You become forced to document that your input shouldn’t be null in your Javadoc, which helps your users and covers your ass
- You only have to handle one type of exceptions: real exceptions, and not exceptions dressed as nulls.