简体   繁体   中英

Java - How to switch old way block of code null check to Optional null check?

Trying to refactor my whole project.

l want this block to be simpler with Optional Java 8 null checks if possible to be the same results at the end? Thanks

List<EntityDto> ventolinLogs = new ArrayList<>();
 for (VentolinLog logs : ventolinLogsList) {
   for (String ventolinId : logs.getVentolinIds()) {

   Ventolin ventolin = persistence.get(Ventolin.class, ventolinId);
   String ventolinName= "";
   String ventolinFirstName= "";

   if (ventolin != null) {
     ventolinName= ventolin.getVentolinName();
     ventolinFirstName= ventolin.getFirstName();
   }

   VentolinProfile ventolinProfile = persistence.get(VentolinProfile.class, ventolinId);
   String ventolinProfileName= "";

   if (ventolinProfile != null) {
     ventolinProfileName= ventolinProfile.getName();
   }

   EntityDto LogDto = EntityDto.builder()
            .ventolinId(ventolinId)
            .ventolinName(ventolinName)
            .ventolinFirstName(ventolinFirstName)
            .ventolin

      ventolinLogs.add(LogDto);
   }
}

Make persistence.get return an Optional. You can use return Optional.ofNullable(result) to do this in your Persistence Class.

In your code use can now use:

Optional<VentolinProfile> ventolinProfile = persistence.get(VentolinProfile.class, ventolinId);
String ventolinProfileName = ventolinProfile.map(VentolinProfile::getName).orElse("");

For more information check out some tutorials on optionals like here: https://www.baeldung.com/java-optional

But as you see, it won't shorten the code very much.

In case you can return an optional from the Persistence class or, like in the example, just create an optional, you can do the following:

ventolinProfileName = Optional.ofNullable(ventolinProfile).map(VentolinProfile::getName).orElse(ventolinProfileName); // or just "" in the last brackets

I would also extract the builder to a variable and pass it to a lambda:

EntityDtoBuilder builder = EntityDto.builder();
Optional.ofNullable(ventolin).ifPresent(vp-> builder.ventolinName(vp.getVentolinName())
.ventolinFirstName(vp.getFirstName()))

But you should take care of the default values, which are initialized as empty strings in your code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM