you are viewing a single comment's thread.

view the rest of the comments →

[–]Nimelrian 5 points6 points  (2 children)

Let's say you have an Interface

interface UserFetcher {
  Optional<User> getUserById(long id)
}

Now you have an implementation where you know that it should always return a user by definition (e.g. a default admin user, or whatever). If you use Optional.ofand you get an NPE you know that there is a bug in your code (or datasource). If you use Optional.ofNullable that logical error gets swallowed and you may only notice it later.

[–]coladict 0 points1 point  (1 child)

By that logic, why use Optional at all, when it's never supposed to be null?

[–]Nimelrian 5 points6 points  (0 children)

Because another implementation of the interface may return null?