NestedOptionals

WARNING

FragileCode

View source code on GitHub

Summary

Avoid nesting Optionals inside Optionals; the resultant code is hard to reason about

Suppression

Suppress false positives by adding the suppression annotation @SuppressWarnings("NestedOptionals") to the enclosing element.

Disable this pattern completely by adding -Xep:NestedOptionals:OFF as compiler argument. Learn more.

Samples

Replacement

Shows the difference in example code before and after the bug pattern is applied.

Identification

Shows code lines which will (not) be flagged by this bug pattern.
A //BUG: Diagnostic contains: comment is placed above any violating line.

import java.util.Optional;
import java.util.stream.Stream;

class A {
  void m() {
    Optional.empty();
    Optional.of(1);
    // BUG: Diagnostic contains:
    Optional.of(Optional.empty());
    // BUG: Diagnostic contains:
    Optional.of(Optional.of(1));

    Optional.ofNullable(null);
    // BUG: Diagnostic contains:
    Optional.ofNullable((Optional) null);

    Optional.of("foo").map(String::length);
    // BUG: Diagnostic contains:
    Optional.of("foo").map(Optional::of);

    Stream.of("foo").findFirst();
    // BUG: Diagnostic contains:
    Stream.of("foo").map(Optional::of).findFirst();
  }
}

Copyright © 2017-2024 Picnic Technologies BV