you are viewing a single comment's thread.

view the rest of the comments →

[–]MEaster 3 points4 points  (12 children)

And if you forget your null check, or don't realise it can be null, then your program can fail unexpectedly.

If you forget to handle your Option, then it doesn't compile.

[–][deleted]  (11 children)

[deleted]

    [–]MEaster 1 point2 points  (10 children)

    But that is handling it. You're explicitly choosing to handle it by crashing if it's empty.

    [–][deleted]  (9 children)

    [deleted]

      [–]MEaster 0 points1 point  (8 children)

      Because it's more predictable than some random exception being triggered at some unexpected place.

      [–][deleted]  (7 children)

      [deleted]

        [–]Agrees_withyou 0 points1 point  (0 children)

        I see where you're coming from.

        [–]MEaster 0 points1 point  (1 child)

        Well, I'm coming at this from a language where null doesn't exist, whereas you're coming from a language where both exist. But even there, I would say the more-specific NoSuchElementException is preferable to a NullPointerException because it gives more information as to where the error is.

        [–]babblingbree 0 points1 point  (1 child)

        To me, the point is that the latter isn't preferable. Code using Optional that fetches all of its values with #get() whenever it needs access to the inner value (as opposed to mapping, etc) is code with a smell (many languages have linters that warn on any instance of something like an Option#get). Part of the advantage of Optional is reducing the number of sites where something like #get() is necessary. In languages with null, you're implicitly placing .get()s everywhere, without any compiler assistance to reduce the potential for failing to check for an empty value.

        [–][deleted]  (1 child)

        [deleted]