I have already written the code, but the thing is I feel there could be better way to write the below code,
This must be possible only from Java 8
private User getUser(String userId) {
Optional<User> optionalUser = userDAO.getUserById(userId);
if(optionalUser.isPresent())
return optionalUser.get();
throw new UserDefinedException("User not present");
}
I expect to write the above in one line
When we have an Optional object returned from a method or created by us, we can check if there is a value in it or not with the isPresent () method: This method returns true if the wrapped value is not null. Also, as of Java 11, we can do the opposite with the isEmpty method:
As discussed above, Optional is meant to be used as a return type. Trying to use it as a field type is not recommended. Additionally, using Optional in a serializable class will result in a NotSerializableException. Our article Java Optional as Return Type further addresses the issues with serialization.
It can help in writing a neat code without using too many null checks. By using Optional, we can specify alternate values to return or alternate code to run. This makes the code more readable because the facts which were hidden are now visible to the developer.
Optional s are not supposed to be passed into methods, they are only for returning optional values. Your code is perfectly fine as it is right now (might want to add a @Nullable annotation)
You can use orElseThrow
, which will return the value if present or throw the specified exception if not:
private User getUser(String userId) {
return userDAO.getUserById(userId)
.orElseThrow(() -> new UserDefinedException("User not present"));
}
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