DEV Community

Discussion on: Be careful Of This Java Optional Method

Collapse
 
alexismanin profile image
Alexis Manin

Good article, with simple but good example.

However, I think there's some room for improvement. Mostly, The "Why is that" section looks like a bad reason for me. You could make a lot more value of your post if you take the time to properly explain what happens.

The method "orElse" does not take a function or lambda as argument, it takes a value. There's no JVM performance reason here. To give the value as argument of orElse, the method that produces it must be called "on-site".

It is a basic language understanding, and it is the same for any function in java.

To add emphasis why it is independent of performances :
JVM cannot really know how much it costs to call your method, and let you, the developper, choose if it should be called:

  • eagerly using orElse(Object) to provide a default value when assembling your Optional object, when it is created.

  • lazily, using orElseGet(Supplier) to provide a function that will compute a default value when the matching part of the optional is executed.

I think it would be far better to give users a proper understanding of this kind of difference (assembly vs execution, on-site vs defered execution). You could also give potential improvement solutions (like really caching default value yourself, to be sure the default value is computed a minimum amount of time).

Collapse
 
jarjanazy profile image
Abdulcelil Cercenazi

Yes you are right, I might have gone about explaining it the wrong way :D thanks for the feedback.
I will adjust the post accordingly