Hacker News new | ask | show | jobs
by Cthulhu_ 1747 days ago
But the mechanism is just wrong; Exceptions are heavyweight and should only trigger with unexpected issues, bugs that a developer wants to see a stacktrace for.

I mean in this case you could consider it developer error; a developer tried to parse an integer without first validating the input and checking if it COULD be parsed. But it's normalized to just "let it crash", instead of writing additional pre-check code.

With errors as values - like Go has normalized - instead of a big, expensive, potentially panicky exception, you just get a lightweight error option back. With the more functional approach of Either, you are basically forced to deal with the "but what if I can't parse it" code branch.

2 comments

> a developer tried to parse an integer without first validating the input and checking if it COULD be parsed

Is there a meaningful difference between validating that input can be parsed and parsing it?

Any validator that doesn't actually parse the data - according to the same rules the parser uses - runs a risk of incorrectly passing/failing certain cases, no?

So here's a pattern neophytes often end up implementing:

   if (isValidInput()) {
     parseInput();
   }
It seems like a good idea but it's not, for several reasons:

1. It requires an explicit second step. Worse, the behaviour of the second step may be undefined if the first step didn't take place. Either way it's just error-prone;

2. While this may be correct for a static string with static rules, what if this isn't stateless? You've now introduced a race condition;

3. If each step requires context (eg options) you need to correctly pass them to both. This is another potential source of error; and

4. You've created what's likely an artificial differentiation between valid and invalid input. What happens when that changes and you need to distinguish between invalid (not a number) and invalid (number out of range)?

(2) is particularly common in security contexts. You'll see this pattern as:

    if (userCanEditPhoto()) {
      editPhoto();
    }
Usually you can't do this, as in the primitives won't be there. This is for good reason. Engineers should instead change their mindset to implementing these things as an atomic action that gives reason for failure. Exceptions are one version of this. They're just bad for other reasons.