File: OptionalMapToOptional.md

package info (click to toggle)
error-prone-java 2.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 23,204 kB
  • sloc: java: 222,992; xml: 1,319; sh: 25; makefile: 7
file content (31 lines) | stat: -rw-r--r-- 858 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Using `Optional#map` (or `Optional#transform`) to map to another `Optional`
might indicate an error, or at least quite hard-to-reason-about code that may
turn into an error.

For example,

```java
class AccountManager {
  /** Retrieves the current user, or absent if not logged in. */
  Optional<Account> getUser() {
    ...
  }

  /**
   * Returns an administrative token for the user, or absent if they do not have
   * such privileges.
   */
  Optional<Token> getAdminToken() {
  }

  void doScaryAdminThings() {
    if (getUser().map(AccountManager::getAdminToken).isPresent()) {
      // do privileged things.
    }
  }
}
```

In this case, assuming `getAdminToken` does not throw, the conditional is
equivalent to `getUser().isPresent()`, which is not what was intended.
`getUser().flatMap(AccountManager::getAdminToken).isPresent()` would be correct.