3 ms·
If you return null, there is no way to discern between invalid input data and 'null' as input. If you return null for 'null' as input and undefined for invalid
by pilif 15y ago
If you return null, there is no way to discern between invalid input data and 'null' as input.
If you return null for 'null' as input and undefined for invalid data, then you don't have to look at the input again to check whether you just failed to parse json or whether the input was just 'null'.
if (HypotheticalJSON.parse(input) === null && input.trim() != 'null'){ alert('invalid input'); }
instead of just
if (HypotheticalJSON.parse(input) === undefined){ alert('invalid input'); }
Though as I said in my comment, I do believe throwing an exception to be a valid action here - at least in any other environment than server-side JS where you have to be a bit careful.
- dkersten 15y agoOk, so its the case that null is valid data and makes for a bad "invalid value". Personally, this demonstrates a core reason why return values (and returning null in particular, in any language) are a bad way of handling errors - they're a leaky abstraction and too much inside knowledge is required to use them safely. For example, if I have code like a = foo() if (a is valid) bar(a) I have to know about the possible values of a before I can pass it to bar. Exceptions are better because I don't have to know the internal details (foo and bar could be library functions that return some data I don't know all the valid values of): try { a = foo() bar(a) } catch (e) { handle error here } But I also agree with the post that exceptions aren't always great either. Instead of returning null, I like haskells Maybe. You either return a valid value (which can be null, in this case) or it returning Nothing, which can never be something which is also valid data. This removes the possible ambiguity of whether null is an error value or a valid value and the haskell compiler makes sure you hanbdle the error case, but its still a signal-error-through-return-value method of error handling and is not always ideal. I also like the ideas behind common lisps condition system, though I have never used it in real code. I like the idea of abstracting the error signalling, handling and routing into separate entities that can happen at various parts of the hierarchy. I also like Go's defer/panic/recover mechanism, though, again, I have never used it in real code, so don't know how well it works in reality.