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?
The IS NOT NULL condition is used in SQL to test for a non-NULL value. It returns TRUE if a non-NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
== and !=The comparison and not equal to operators are allowed with null in Java. This can made useful in checking of null with objects in java.
To conclude this post and answer the titular question Does null equal null in Java? the answer is a simple yes.
isEmpty(< string >) Checks if the <string> value is an empty string containing no characters or whitespace. Returns true if the string is null or empty.
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:
Car car = dao.getCar();
Optional<Car> optionalCar = Optional.ofNullable(car);
Optional<Power> optionalPower = getPowerIfPresent(optionalCar);
Power power = Optional.empty();
if(optionalPower.isPresent()) {
power = optionalPower.get();
}
after writing a function that returns the power
of a given car
:
public static Optional<Power> getPowerIfPresent(Optional<Car> car) {
return car
.flatMap(c -> c.getEngine())
.map(e -> e.getPower());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With