DEV Community

Serguey Asael Shinder
Serguey Asael Shinder

Posted on

Your Optional Already Had a Cart and orElse Created Another One Anyway

The shop kept one cart
per customer.

Load it if it exists.

Create it if it does not.

Somebody wrote it
in one tidy line:

Cart cart = carts.findByCustomer(id)
.orElse(carts.createFor(id));

It passed review.

It read like English.

Find the cart,
or else create one.

A month later
the carts table
had eleven million rows
for eighty thousand customers.

Every page view
had made a new, empty cart.

The customer still saw
the right one.

The database
saw all of them.

Here is the mechanism.

orElse is an ordinary method.

Java evaluates
every argument
before it calls a method.

So carts.createFor(id)
ran first,
every time,
and inserted a row.

Only then
did orElse look at the Optional,
find a cart already inside,
and throw the new one away.

The value was discarded.

The side effect
was not.

No exception.

No warning.

No failing test,
because every test
checked which cart came back,
and the right one always did.

Nobody counted
how many were made.

The word "else"
promised a branch.

The language
gave you an argument.

The fix is one word:

Cart cart = carts.findByCustomer(id)
.orElseGet(() -> carts.createFor(id));

orElseGet takes a Supplier.

A function,
not a value.

It is only called
when the Optional is empty.

The rule underneath:

orElse is for values
that already exist.

A constant.

A field.

An empty list.

orElseGet is for anything
that does work.

Saves a row.

Calls a service.

Sends an email.

Even builds
an expensive object
you are about to drop.

If you cannot tell
which one you have,
use orElseGet.

It is never wrong,
only occasionally unnecessary.

The same trap
sits in other places.

A logger
handed a string
built with heavy formatting,
when the level is off.

A map's getOrDefault
given a fresh object
it will never use.

Each one
reads like a condition
and runs like a statement.

When an expression
sits inside the brackets,
assume it has already happened.

Then decide
whether you can afford that.

– Serguey Asael Shinder

Top comments (0)