Explain Codes LogoExplain Codes Logo

'optional.get()' without 'isPresent()' check

java
prompt-engineering
best-practices
lazy-evaluation
Nikita BarsukovbyNikita Barsukov·Oct 29, 2024
TLDR
String value = optionalString.orElseThrow(NoSuchElementException::new);

Use orElseThrow as a shortcut. It fetches the value if it exists, otherwise throws an exception, making it obvious when an Optional is unwantedly absent.

Avoid using orElse(null) without a good reason. It reintroduces null checks, which Optional aims to supersede.

Making the most of Optional

When Optional is empty, handle it with style

Optional is not just a fancier "null". It offers semblances of control over absent values:

  • orElseThrow(): Convert absence into an exception.
  • ifPresent(): Perform an action if the value is available.
  • orElseGet(): Call a Supplier to provide an alternative when needed.

Better transformations with map

String mappedValue = optionalString.map(String::toUpperCase).orElse("DEFAULT");

Use map() to transform an Optional's value with a Function, elegantly providing an alternative for emptiness.

Conditional logic via filter

Optional<String> filtered = optionalString.filter(s -> s.contains("expected"));

To conditionally exclude values based on a Predicate, use filter().

Harnessing Optional in Stream operations

Don't misuse findFirst():

Optional<String> result = list.stream().filter( /* criteria */ ).findFirst(); return result.orElse("default");

Handle the Optional produced by findFirst() to provide a default value or allow further operations.

Tips for Unwrapping Optional

Using orElse for default values

String defaultValue = optionalString.orElse("Default String"); // even when life gives you null, make it a Default String!

Use orElse to specify an alternative value when an Optional is empty.

When to use orElseGet

String computedDefault = optionalString.orElseGet(() -> computeDefault()); // Why work hard when you can be lazy?

A more sophisticated option, orElseGet() uses a Supplier function and only calls it when necessary - a perfect example of lazy evaluation.

Avoiding blunders while unwrapping

Optional respects the saying - "look before you leap". Use orElseThrow() instead of get() to avoid a surprising NoSuchElementException.

Be Good and Return Optional

Forwarding Optional to caller

You don’t always have to unwrap Optional:

public Optional<String> findTitle(String bookId) { return books.stream().filter(book -> book.hasId(bookId)).findFirst().map(Book::getTitle); }

Let the caller take charge of the Optional.

Optional and Stream: True Friendship

public Stream<String> titlesStream() { return books.stream().map(Book::getTitle); }

Optional can complement Stream perfectly, allowing nuanced treatment of nullable values in sequences.