Featured Post

Applying Email Validation to a JavaFX TextField Using Binding

This example uses the same controller as in a previous post but adds a use case to support email validation.  A Commons Validator object is ...

Thursday, May 12, 2016

Handling Checked Exceptions in Java Optionals

This post presents a syntax for handling checked exceptions when using Java Optionals.  Java Optionals are a library extension design to fend of NullPointerExceptions.  When using Optionals, you can use an isPresent/get pair that starts to look a lot like !=null/access.  An alternative is to use functional programming with the ifPresent method.  However, you'll run into a problem with Java Lambdas and checked exceptions.


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