Imagine I have, say, XML-generated entity in Java that holds some data I need. For example:
<Car>
<Engine>
<Power>
175
</Power>
</Engine>
</Car>
So if I need an engine power, I, followed by the best practices of business software development, will do the next thing:
Car car = dao.getCar()
Power power = car != null && car.engine != null ? power : null
return power
I hate this. Sometimes it seems that half of the code is just null checks.
Any ideas?
Take a look at Java 8 Optional class. It does exactly that: it avoids the ugly checks on
null.In your case, you could use this snippet of code to avoid them:
after writing a function that returns the
powerof a givencar: