This question already has an answer here:
- null pointers vs. Null Object Pattern 5 answers
Various programming books suggest that methods should not return
null values (Clean Code for example). Instead of returning
null default values (0 or empty string or empty object) should be returned or an exception should be thrown. This is recommended in order to avoid many
!= null checks or to avoid
I really don't understand how this helps. If you return a default value you have to make
!= DEFAULT checks; more over, the default value might mean something (like 0 for a credit amount). Throwing a specific exception is not worth with, because if you don't handle your code well, an exception is thrown anyway -
I've thought about this when I found a bug caused by a method which returned an empty object (e.g.
new MyBean()) instead of returning
null. The code didn't worked functionally and the logs didn't warn anything, so detection and fixing was not that easy; with
NullPointerException would have been thrown so spotting and fixing the bug would have been trivial.
The only case where it makes sense to me to return a default value instead of returning
null is when returning arrays/collections; here they are usually consumed
for each element in collection so if its empty nothing happens but if it's
null NPE is thrown.