Optional in Java and anti-patterns using it

In most cases the plan to filter first before mapping lead to more readable code, since it was directly stating what you want to achieve, instead of hiding it behind a chain of maybe mapping, filtering and then mapping.

private boolean isIdEnum(String id) { return Stream.


values()) .

map(IdEnum::name) .

anyMatch(name -> name.


)List<String> identifiers = (.

)List<IdEnum> mapped = identifiers.

stream() .

filter(this::isIdEnum) .

map(IdEnum::valueOf) .


toList());If you imagine the isEnum-method to be owned by the IdEnum itself, it would become even more clear, but for the sake of having a readable code example it is not in the example.

But just by reading the above example, you can easily understand what is going on, even without really having to jump into the referenced isIdEnum-method.

So long story short — if you do not need the absence of a value expressed in a list, you do not need Optional — you just need its content, so optional is obsolete inside collections.

Optional in method parametersAnother pattern we encountered, especially when code is getting migrated from the “old-fashioned” way of using a null-reference to using the optional-type is having optional-typed parameters in function-definitions.

This typically happens if you find a function that does null-checks on it’s parameters and apply different behaviour then — which in my opinion was bad-practice before anyways.

void addAndUpdate(Something value) { if (value != null) { somethingStore.

add(value); } updateSomething();}If you “naively” refactor this method to make use of the optional-type, you might end up with a result like this, using an optional-typed parameter.

void addAndUpdate(Optional<Something> maybeValue) { if (maybeValue.

isPresent()) { somethingStore.


get()); } updateSomething();}In my opinion, having an optional-typed parameter in a function shows a design-flaw in every case.

You either way have some case of decision to make if you do something with the parameter if it is there, or you do something else if it is not — and this flow is hidden inside the function.

In an example like above, it is clearer to split the function into two functions and conditionally calling them (which would also happen to fit to the “one intention per function”-principle).

private void addSomething(Something value) { somethingStore.


)// somewhere, where the function would have been calledOptional.


ifPresent(this::addSomething);updateSomething();In my experience, if I ever encountered examples like above in real code, it always was worth refactoring “‘till the end”, which means that I do not have functions or methods with optional-typed parameters.

I ended up with a much cleaner code-flow, which was much easier to read and maintain.

Speaking of which — in my opinion a function or method with an optional parameter does not even make sense, since I can have one version with and one version without the parameter, and decide in the point of invocation what to do, instead of deciding it hidden in some complex function.

So to me, this was an anti-pattern before (having a parameter that can intentionally be null, and is handled differently if it is) and stays an anti-pattern now (having an optional-typed parameter).

Optional::isPresent followed by Optional::getThe old way of thinking in Java to do null-safe programming is to apply null-checks on values where you are not sure if they actually hold a value or are referencing to a null-reference.

if (value != null) { doSomething(value);}To have an explicit expression of the possibility that value can actually be either something or nothing, one might want to refactor this code, so you have an optional-typed version of value.

Optional<Value> maybeValue = Optional.

ofNullable(value);if (maybeValue.

isPresent()) { doSomething(maybeValue.

get());}The example above shows the “naive” version of the refactoring, which I encountered quite often in several code examples.

This pattern of isPresent followed by a get might be caused by the old null-check pattern leading one in that direction.

Having written so many null-checks has somehow trained us to automatically think in this pattern.

But Optional is designed to be used in another way to reach more readable code.

The same semantics can simply be achieved using ifPresent in a more readable way.

Optional<Value> maybeValue = Optional.


ifPresent(this::doSomething);“But what if I want to do something else instead, if the value is not present” might be something you think right now.

Since Java-9 Optional comes with a solution for this popular case.


ofNullable(valueOrNull) .

ifPresentOrElse( this::doSomethingWithPresentValue, this::doSomethingElse );Given the above possibilities to achieve the typical use-cases of a null-check without using isPresent followed by a get makes this pattern sort of a anti-pattern, since Optional is per API designed to be used in another way which in my opinion is more readable.

Complex calculations, object-instantiation or state-mutation in orElseThe Optional-API of Java comes with the ability to get a guaranteed value out of an optional.

This is done with orElse which gives you the opportunity to define a default value to fall back to, if the optional you are trying to unpack is actually empty.

This is useful every time you want to specify a default behaviour for something that can be there, but it does not have to.

// maybeNumber represents an Optional containing an int or not.

int numberOr42 = maybeNumber.

orElse(42);This basic example illustrates the usage of orElse.

At this point you are guaranteed to either get the number you have put into the optional or you get the default value of 42.

Simple as that.

But a meaningful default value does not always have to be a simple constant value.

Sometimes a meaningful default value may need to be computed in a complex and/or time-consuming way.

This would lead you to extract this complex calculation into a function and pass it to orElse as a parameter like this.

int numberOrDefault = maybeNumber.

orElse(complexCalculation());Now you either get the number or the calculated default value.

Looks good.

Or does it?.Now you have to remember that Java is passing parameters to a function by the concept of call by value.

One consequence of this is that in the given example the function complexCalculation will always be evaluated, even if orElse will not be called.

Now imagine this complexCalculation is really complex and therefore time-consuming.

It would always get evaluated.

This would cause performance issues.

Another point is, if you are handling more complex objects as integer values here, this would also be a waste of memory here, because you would always create an instance of the default value.

Needed or not.

But because we are in the context of Java, this does not end here.

Imagine you do not have a time-consuming but a state-changing function and would want to invoke it in the case where the Optional is actually empty.

int numberOrDefault = maybeNumber.

orElse(stateChangingStuff());This is actually an even more dangerous example.

Remember — like this the function will always be evaluated, needed or not.

This would mean you are always mutating the state, even if you actually would not want to do this.

My personal opinion about this is to avoid having state mutation in functions like this at all cost.

To have the ability to deal with issues like described, the Optional-API provides an alternative way of defining a fallback using orElseGet.

This function actually takes a supplier that will be invoked to generate the default value.

// without method referenceint numberOrDefault = maybeNumber.

orElseGet(() -> complex());// with method referenceint numberOrDefault = maybeNumber.

orElseGet(Something::complex);Like this the supplier, which actually generates the default value by invoking complex will only be executed when orElseGet actually gets called — which is if the optional is empty.

Like this complex is not getting invoked when it is not needed.

No complex calculation is done without actually using its result.

A general rule for when to use orElse and when to use orElseGet can be:If you fulfill all three criteriaa simple default value that is not hard to calculate (like a constant)a not too memory consuming default valuea non-state-mutating default value functionthen use orElse.

 Otherwise use orElseGet.

Conclusion (TL;DR)Use Optional to communicate an intended possible absence of a value (e.


the return value of a function).

Avoid having Optionals in collections or streams.

Just fill them with the present values directly.

Avoid having Optionals as parameters of functions.

Avoid Optional::isPresent followed by Optional::get.

Avoid complex or state changing calculations in orElse.

Use orElseGet for that.

Feedback & QuestionsWhat is your experience so far with using Java Optional?.Feel free to share your experiences and discuss the points we brought up in the comment section.


. More details

Leave a Reply