Java Magazine, September/October 2017
ORACLE COM JAVAMAGAZINE SEPTEMBER OCTOBER 2017 35 java 9 displayMissingBookingPage Now in Java 8 you could have refactored lookupBooking to return an Optional value which would give you an explicit indication whether the booking can be found The Optional would also help you think about the distinction between the booking being present and absent This approach is better than checking for null because it forces you to explicitly think in terms of the domain model The simplest refactoring for this code would have been to the following Optional Booking booking lookupBooking bookingRefer If booking isPresent displayCheckIn booking get else displayMissingBookingPage This pattern of taking an Optional and calling isPresent and get isnt a particularly idiomatic use because it makes the code verbose In fact it basically leaves you with code that is similar to the null check version Ideally you want to be able to call a method on the Optional that is appropriate for your use case effectively moving to a tell dont ask style of coding Optional from Java 8 has an ifPresent method that will invoke its callback if the value inside the Optional is present for example lookupBooking bookingReference ifPresent this displayCheckIn Unfortunately this doesnt meet your needs here because it wont handle the case in which the value is absent and you want to display the missing booking page This is the use case that Java 9 s Optional improvements address You could refactor your original code as follows
You must have JavaScript enabled to view digital editions.