1

Is it able to write this code embedded into Optional method chain:

Optional<Application> appOpt = this.applicationDao.findById(application.getCode());

Application app = appOpt.orElse(Application::new);

if (!appOpt.isPresent()) {
    app.get().setUserCreation("user");
    app.get().setTimestampCreation(new Date());
}

I'd like to avoud using again the previous appOpt object. I would like to embed all this logic inside an Optional method chain.

I guess there should be another more elegant way to get it.

I've tried to play with ifPresent but it returns void and so I'm not able to chain orElse method:

appOpt.ifPresent(a -> {
    a.setUserCreation("userCreation"));
    app.setTimestampCreation(new Date());
})
.orElse(Application::new);

I hope I've explained so well.

Any ideas?

Holger
  • 285,553
  • 42
  • 434
  • 765
Jordi
  • 20,868
  • 39
  • 149
  • 333
  • 3
    https://stackoverflow.com/questions/23773024/functional-style-of-java-8s-optional-ifpresent-and-if-not-present – J-Alex Jan 15 '19 at 10:22
  • 3
    `app.get` seems like an error (it's not an optional after all). The code at the start does something very different from your proposed one (why once app and then a? Presumably should both be a). – Voo Jan 15 '19 at 10:25
  • The general idea of configuring the new application objects if not loaded from database has a very simple solution though: Just do it in the orElse instead of splitting it up and then needing an additional check. From a DDD PoV I'd expect this to be in the constructor anyhow, but you can certainly use a lambda. – Voo Jan 15 '19 at 10:26
  • In addition to @Voo’s comment, `appOpt.ifPresent` is the opposite of `if (!appOpt.isPresent())`. – Holger Jan 15 '19 at 10:27

1 Answers1

7

After looking again at your original code, it looks like the logic should run if the Optional is empty:

Application application = appOpt.orElseGet(() -> {
    Application app = new Application();
    app.setUserCreation("userCreation"));
    app.setTimestampCreation(new Date());
    return app;
});
Eran
  • 387,369
  • 54
  • 702
  • 768