Using a familiar imperative programming style, you might do something like this
Optional<PickResult> pickResultOpt = pickRectangle(layoutScene.getX(), layoutScene.getY()); if( pickResultOpt.isPresent() ) { PickResult pr = pickResultOpt.get(); doSomething(pr); } else { throw new InitializationException("init error"); }
For functional programming, you're encouraged to use ifPresent (not IS_Present).
pickResultOpt.ifPresent((pr) -> doSomething(pr));
However, you're no longer handling the IntializationException case. If pr wasn't set, nothing happens. "InitializationException" is a needed custom checked exception (extends Exception) thrown as a fatal error back to a caller.
The Optional class has another method which will thrown an Exception if the Optional is not set and is attempting to be accessed.
PickResult pr = pickResultOpt.orElseThrow( () -> { return new InitializationException("init error"); }); doSomething(pr);
And, if you didn't care about the one-arg constructor, the orElseThrow() could be reduced with a static method reference.
PickResult pr = pickResultOpt.orElseThrow( InitializationException::new );
It remains to be seen whether or not Optional will actually reduce bugs or if we're just making "NoSuchElementException" the new NPE. I don't think Java goes far enough in controlling program state, having only the final keyword and this API add-on. Consider Swift which has the let keyword and gives a special Elvis operator (?) syntax to assist in de-referencing Optionals.
No comments:
Post a Comment