Optional usage - uyuni-project/uyuni GitHub Wiki

Basic ideas

  1. Avoid using Optional#get(). The only place where it is ok to use is in tests where you expect the Optional to have a value and want the test to fail if it does not.

  2. If you need to transform the Optional to a concrete value you need to supply a fallback value in case the Optional does not have a value. There are two options to do that.

  3. Optional#orElse(fallback value) is suitable if you already have a fallback value or it is inexpensive to create one.

  4. Optional#orElseGet(function returning fallback value) should be used if you don't have the fallback value yet and creating it is expensive (for example db lookup). The function you give it will only be called if the Optional is empty so you avoid expensive computations if you don't need the fallback value.

  5. If you need to do some computation on the Optional value there are multiple ways to do that in a safe way.

  6. If the result of your computation is a new value (can be a different type the before) then you want to use Optional#map. You give it the function that takes the content of the Optional and transforms it into a new value. The result of your computation will be wrapped up into a new Optional.

  7. If your computation does not result in a new value and is only side-effecting then you should use Optional#ifPresent it is like map but does not result in a new value.

  8. If your computation results in a second Optional value you should use Optional#flatMap. It is similar to map but function you give it returns a new Optional which will be the overall result of the flatMap.