Reputation: 4902
I have a custom StringUtils class in my project, I would like to return Optional, but I notice in Apache's String Utils they are not returning Optional.
In general, is it ok to return Optional in StringUtils? or it is an overkill?
Upvotes: 2
Views: 545
Reputation: 5748
The point of Optional is to indicate that a function/method can have no return value (i.e. null). If that's your case, and returning Optional makes more sense than returning null (it does most of the time in my opinion), then go ahead.
Returning null is bad in general because it can cause unexpected bugs if you or someone else forgets to check for null in the future, so you should return a default value in most cases. One advantage that Optional gives you is the possibility to determine that default value dynamically through orElse
or orElseGet
and forces you to do it to get the value out of the Optional, preventing most NullPointerException
s
Upvotes: 5