I'm against the idea of blindly defending against null for each field available in the code and inside each method.
The following help me deciding about where to check against null values:
1- Who will be invoking your methods?
If a method is private and you have control over how's it's being accessed, I don't see it makes sense to protect against null checks unless it's part of the method's logic to expect null values.
If a method is exposed to the public (Such as an API), then of course null checks should be a huge concern.
2- Software Design:
Image you have are calling method1(fromAnimalToString(animal));
and for some reason fromAnimalToString()
never returns null (Though might return an empty string instead).
Then in such case, it wouldn't make sense to check animal != null
in method1()'s body
3- Testing:
In software engineering, it's almost impossible to test all possible scenarios that can ever execute. However, test normal and alternative scenarios and make sure the flow is as expected.
null
? You could also go another route, and make sure object you do use, cannot be null. – Wigan