Thursday, 9 May 2019

Proper use of Optional

Using Optional is hard in the beginning.

Especially for first-timers one has a tendency to use the wrong methods.

Take the following sequence of refactoring for example:

First without any kind of Optional:

A first bad attempt at an optional:

It looks like the person just... kind of removed the Optional back to a situation that he knew and was more familiar with.

Let's try this again:

Now this is a good try. It is very common to see the two Optional class methods being used together. isPresent() and get().

But we can do better.

It's often the same: we wish to do something, only when there's a value available.

Like so:

Of course, it's sometimes better to create a method reference:

But I do find this proliferates the number of methods, but it's an acceptable side effect.

We finally arrive at something concise and easy to read, once you get the hang of it.

No comments:

Post a Comment