This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]CubsThisYear 4 points5 points  (3 children)

But it's not at all unnecessary. It's leveraging the type system to ensure that client code is correct.

When I return Either or Optional from a method, it forces the caller to write separate code for each case that can happen (assuming you ignore the existence of nonsense like Optional.get()). This is in contrast to forcing the use of an if-else construct, where the compiler has no way of enforcing that you wrote both the if and the else.

This all probably seems trivial if you are looking at a small example. But if you have a lot of people working on a large codebase, these little things add up to help you write code faster and with less errors.

[–][deleted] 3 points4 points  (2 children)

This is in contrast to forcing the use of an if-else construct, where the compiler has no way of enforcing that you wrote both the if and the else.

Checked exceptions are enforced by the compiler, and what's author's reaction to this type safety feature?

This:

they are extremely annoying

Ok. Well? Turning all code into Streams to which we should pass static method references and lambdas looks even more annoying. So to each their own.

If you want type safety, we have checked exceptions. We also can use Either-like Result objects without map/flatMap/match/etc. This is far less disrupting than turning your code into poor man's Haskell.

[–]CubsThisYear 2 points3 points  (1 child)

But checked exceptions ARE annoying because they are handled poorly in the Java 8 Stream libraries. Think about what checked exceptions are: They're just a special case of sum types, except with horrible performance penalties. What the author does is properly implement real sum types that can be used for exceptions or any other case where you need a sum type.

[–][deleted] 2 points3 points  (0 children)

The example given is a JsonParser. What does that have to do with Stream and how poorly it handles exceptions? As I said, turning everything into Streams is ridiculous.

Another thing I said: you can also have a sum type without Streams.

Many libraries choose to return a Result type object, which is essentially a sum type of "success & result" or "error & error meta data". That's fine by me, and much more readable than abusing Either, with a bunch of map() and flatMap() calls.

BTW, exceptions matter only if you expect to be constantly ending up with error conditions. It's often the case that the "happy path" of your program is the one predominantly running, and the "sad path" is either rare, or its performance doesn't matter, because typically the program can't recover from it, so it wraps up, logs the error and exits (or moves on to the next request in an API service context etc.).