Thursday 10 December 2020

The Three options with Optional

There are basically three ways to deal with an optional, when receiving one.

  1. throw an exception if the optional is empty, because it's a faulty situation. (.orElseThrow)
  2. do not do anything, but proceed with the next step. (.ifPresent(dosomething))
  3. provide a default value. (.orElse(default))

I'm writing it down here, because each of these three cases is highly dependent on context.

And I've noticed in my work that I have a tendency to take option 2, even though it might be considered an error.

No comments:

Post a Comment