I want to replace the following code using java8 Optional
:
public Obj getObjectFromDB() { Obj obj = dao.find(); if (obj != null) { obj.setAvailable(true); } else { logger.fatal("Object not available"); } return obj; }
The following pseudocode does not work as there is no orElseRun
method, but anyways it illustrates my purpose:
public Optional<Obj> getObjectFromDB() { Optional<Obj> obj = dao.find(); return obj.ifPresent(obj.setAvailable(true)).orElseRun(logger.fatal("Object not available")); }
The orElseThrow() method of java. util. Optional class in Java is used to get the value of this Optional instance if present. If there is no value present in this Optional instance, then this method throws the exception generated from the specified supplier.
In Java, the Optional object is a container object that may or may not contain a value. We can replace the multiple null checks using the Optional object's isPresent method. The empty method of the Optional method is used to get the empty instance of the Optional class. The returned object doesn't have any value.
If you just want an Optional returning false for isPresent() , you don't need to mock the Optional at all but just create an empty one. Of course this test only tests that the mock object actually returns the stubbed return value, but you get the idea.
With Java 9 or higher, ifPresentOrElse
is most likely what you want:
Optional<> opt = dao.find(); opt.ifPresentOrElse(obj -> obj.setAvailable(true), () -> logger.error("…"));
Currying using vavr or alike might get even neater code, but I haven't tried yet.
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