I was pondering about removing unnecessary null
condition checks from my code today mostly involving deep nested objects.
For example:
I have a class Big
and it has a reference to Small
object and its getters and setters, likewise Small
has reference to
Tiny
object and its getters and setters and Tiny
object has the tinyLength
variable which is an Integer
variable.
So, for example, if I'm writing a method that take in a Big
object parameter and returns tinyLength
at the very end, I usually do something
like this:
public Integer getTinyLength (Big big) {
if (big!=null && big.getSmall()!=null && big.getSmall().getTiny()!=null &&
big.getSmall().getTiny().getTinyLength()!=null) {
return big.getSmall().getTiny().getTinyLength();
}
else {
// throw exception or return null or do whatever
}
So my question here is rather than doing all this gunk, why don't I just do something like:
try {
return big.getSmall().getTiny().getTinyLength();
}
catch (Exception e){
//null pointer exception being a subclass of Exception class
log your error here
throw new NullPointerException();
}
I feel like the second code snippet is very concise and to the point. Is there any disadvantages to doing something like this? Especially when there are multiple nested objects, and dereferencing each one them usually results in highly unreadable code / also prone to mistakes if you miss one of them and it results in null.