In the common situation where classes are embedded as attributes of other classes, what is the best way to check for nulls?
To illustrate what I’m talking about, say I want to access this.getObject1().getObject2().someMethod() where getObject1() or getObject2() could return null. Right now I am doing the following, and it’s ugly, and there has to be a better way:
if (this.getObject1() != null)
if (this.getObject1().getObject2() != null)
if (this.getObject1().getObject2().someMethod())
return whatever;
To avoid a NPE, I have to check for nulls at each step before accessing someMethod(). What is a better way to accomplish this?
This style is to be avoided as far as possible – see the Law of Demeter – though I appreciate that library or legacy code may not leave you much option.
Functional programming languages (in particular) avoid this problem through the use of
OptionorMaybeobjects, which can be used in Java to some extent. See this article, for example. Long sequences of null checks can be avoided concisely using Scala for-comprehensions, for eaxmple. But back to Java…Ideally, assuming you can modify the code you are calling, you would restructure so you can call the ‘outer’ object, which will then call the ‘inner’ object, with only one null check at each stage. Or restructure the code to avoid such deep nesting.