• Post Reply Bookmark Topic Watch Topic
  • New Topic

Prof Horstmann's Take on the Optional class.  RSS feed

 
Campbell Ritchie
Sheriff
Posts: 53779
128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now, I have mentioned before that Urma Fusco and Mycroft think the Optional class should be used to obviate nulls. I think they would use Optionals everywhere if given half a chance. Do you agree with them?
 
Cay Horstmann
author
Ranch Hand
Posts: 172
15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, yes, I think Optional is good, and you should use it instead of returning null when a method has no result.

Conversely, when someone gives you an Optional, then don't call isPresent and get. That's no safer than a possibly null pointer. Instead, use orElse, ifPresent, map, or flatMap to process the wrapped value.

For example,



Cheers,

Cay
 
Campbell Ritchie
Sheriff
Posts: 53779
128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you.
 
Winston Gutkowski
Bartender
Posts: 10573
65
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cay Horstmann wrote:Conversely, when someone gives you an Optional, then don't call isPresent and get. That's no safer than a possibly null pointer. Instead, use orElse, ifPresent, map, or flatMap to process the wrapped value.

I totally agree, being a proponent of tell, don't ask, but I can't help feeling that Optional is a bit of a kludge.

Winston
 
Stephan van Hulst
Saloon Keeper
Posts: 7003
110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it's a big shame that ifPresent() doesn't return an object on which I can call orElse(), because I've found a few scenarios in which I had to resort to calling isPresent() anyway.
 
Cay Horstmann
author
Ranch Hand
Posts: 172
15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That sometimes happens to me too. I'd like something like an ifElse with two lambdas.

Stephan van Hulst wrote:I think it's a big shame that ifPresent() doesn't return an object on which I can call orElse(), because I've found a few scenarios in which I had to resort to calling isPresent() anyway.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!