I think your notion of "correctly" is a bit debatable. Your example seems to suggest that the returning of null
is incorrect. A method could be quite correct in returning null
and forcing you to account for that possibility somehow.
A well-written method will quite clearly define the domain of inputs and the range of outputs (a return type, exceptions under certain circumstances, null
, a null object, etc.) possible for the method. There should also be a suite of tests that convey how the method is to be called and how all those possibilities can be accounted for.
In the real world, especially if you are on a project with developers from other organizations that may be less disciplined, you may not be so lucky. Programming defensively is fine, but I believe you as the client have to make sure you don't do anything that covers up an error in a method that violates its contract. Exceptions are a good thing in development; don't be afraid of letting them notify you when something went wrong somewhere. Then the developers can be made aware that their code needs to be strengthened to meet its contract.
Finally, since one of the tags on the question refers to Effective Java...on the subject of null
in particular, you should test and document what you will do when a client calls your method with null
--like throwing IllegalArgumentException
. In your private methods, do an assert
of your preconditions so you get AssertionError
s.