1

I've got a simple method that checks there are no null in attributes:

public boolean isValid(){
     return session.getX() != null && session.getX().getY() != null &&
     session.getX().getY().getZ() != null;
}

This works, but, Is there any way to do this in a more elegant way?

Thanks a lot in advance.

stack man
  • 2,303
  • 9
  • 34
  • 54

3 Answers3

1

This works, but, Is there any way to do this in a more elegant way?

With a utility class which performs reflection to retrieve the nested fields and do the check, it may be more elegant but it is surely less safe and slower:

public boolean isValid(){
     return NullAnalyser.isNotNull(session, "x.y.z");
}

Another idea would be to return a special type that allows to avoid NPE in the getter. But it makes them more complex. Is it desirable ?

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • Thanks for your answer @davidxxx. I was thinking in reflection as well, but I'd like to get an existing library, if possible, in order to avoid "reinventing the wheel" – stack man Jan 13 '17 at 11:35
  • You are welcome. BeanUtils should do the job. For example `BeanUtils.getProperty(session, "x.y.z");` https://commons.apache.org/proper/commons-beanutils/apidocs/org/apache/commons/beanutils/BeanUtils.html – davidxxx Jan 13 '17 at 11:44
1

This way is elegant if you are using java 8:

public boolean isValid(){
     return Optional.of(session)
                    .map(x -> x.getX())
                    .map(x -> x.getY())
                    .map(x -> x.getZ())
                    .isPresent());
}
Dmitry Gorkovets
  • 2,208
  • 1
  • 10
  • 19
0

Similarly to what Dimitry said if you are using Java 8 and have control over Session, X, Y and Z then you can change the signatures to return Optionals.

You can also use method references instead of lambdas which are arguably easier to read.

public boolean isValid(){
     return Optional.of(session)
                    .map(Session::getX)
                    .map(X::getY)
                    .map(Y::getZ)
                    .isPresent());
}
  • Yes, references are good but we don't know actual class names from the question, moreover you should remove "()" in all maps to avoid compile error. – Dmitry Gorkovets Jan 13 '17 at 12:04