Check is not empty in Java

Imagine that I generated an XML generated entity in Java, which contains some data I need

<Car>
   <Engine>
      <Power>
         175
      </Power>
   </Engine>
</Car>

Therefore, if I need an engine power supply, then next is the best practice of commercial software development, and I 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 empty checking

Any ideas?

Solution

Look at Java 8 optional class

In your case, you can use this snippet 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 can return to a given vehicle power:

public static Optional<Power> getPowerIfPresent(Optional<Car> car) {
    return car
        .flatMap(c -> c.getEngine())
        .map(e -> e.getPower());
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>