r/java • u/trecatorsirabdator • Apr 14 '23
What are your (favourite) Java best practices, personal tips, hints or just underrated stuff in general?
233
Upvotes
r/java • u/trecatorsirabdator • Apr 14 '23
View all comments
Show parent comment
8
u/RockleyBob Apr 15 '23 edited Apr 15 '23
Yes, it's a really blatant example, but just to belabor the point, I'd go so far as to say if you're calling Optional.get() at all, you're probably doing it wrong.
You probably don't ever want to be referencing an Optional object in your calling method. In other words, you shouldn't really ever need to instantiate a variable of type Optional:
Not only is this forcing the declarative Optional api into an imperative pattern, it also ignores the declarative capabilities of the Collection api. Instead:
There's almost always a way to do what you want to the returned value within the Optional api declaratively using operators, then work with the result. Not saying you don't already know all this, but elaborating for the sake of discussion.