I was writing some code and while unit testing I got a Null Pointer Exception...Now I'm wondering how often should we be checking that object is not null before doing get operations on it?
For example, code was:
HashMap paramMap = new HashMap();
getSqlMapClientTemplate().queryForObject("reexamination.isAuthorized", paramMap);
return ((List)paramMap.get("Return0")).get(0).toString().equalsIgnoreCase("true");
I got error on the return statement because "Return0" does not exist in the HashMap. Turns out I made a typo..it was supposed to be "Result0".
I could modify the code like this:
getSqlMapClientTemplate().queryForObject("reexamination.isAuthorized", paramMap);
String returnValue = "";
if (paramMap.get("Result0")!=null)
returnValue = ((List)paramMap.get("Result0")).toString();
return returnValue.equalsIgnoreCase("true");
Is it a good practice to always check that the object is not null before calling any of its properties? Should we be following the A B C motto? :)
A - Always
B - Be
C - Checking
Or Is it a good practice to check when we dont know what the state of the object is (like in example above). However, if we create an object like 10 lines above and know it wont be null then we can skip the null check.
I'd love to get some links that talk about this.