4 ms·
What about actually using early returns ? I feel like the implicitness of exceptions is more of a downside than an advantage def handle(request): if !val
by eddd-ddde 4y ago
What about actually using early returns ? I feel like the implicitness of exceptions is more of a downside than an advantage
def handle(request):
if !validate_signature(request):
return 400
if !check_authorization(request):
return 403
person = fetch_from_database(request.object_id)
if !person:
return 404
return { "first_name":person.first_name }
- kstrauser 4y agoThat's twice the code for the same result. Also, `validate_signature` itself might have lots of similar code, like def validate_signature(request): signature = sig_from_request(request) payload = payload_from_request(request) check_signature(payload, signature) where each of those nested calls follows the same pattern. Yeah, you can do all of that with passing around error objects. A lot of people writing Go do that every day, so obviously it works and it's not overwhelmingly tedious. I highly prefer the Python style of EAFP though.
- deleted 4y ago[deleted]
- the_gipsy 4y agoThe most ergonomic error handling is a Result<Value,Error> with some syntax sugar to get-value-or-return-early-error like rust's ? operator.
- PartiallyTyped 4y agoIOW the most ergonomic error handling is a monad, and I agree.
- int_19h 4y agoAnd exceptions can be considered a syntactic sugar on top of just such a monad. It's just that many believe it's too much sugar to be good for you, particularly the implicit rebind part.
- the_gipsy 4y agoToo much sugar can be bad, for flavor and health.
- eddd-ddde 4y agoThere's this language called zig, and there errors are represented as union values and have this kind of syntax to work with but way more explicit, really like the idea of how they do it.
- PartiallyTyped 4y agoNot exactly. You may catch exceptions in between the computations, whereas with monads you have to unpack and match the error. You can replicate the monad behaviour by catching the exceptions at the top level. I find that this approach is generally cleaner than intermediate exceptions but is more restrictive.
- int_19h 4y agoThat's what I meant by "implicit rebind". But the fact that it's implicit for every expression doesn't make it any less of a monad.
- PartiallyTyped 4y agoI see, thanks for the clarification.
- yccs27 4y ago> That's twice the code for the same result. Only if you ignore that the exception-throwing solution _needs_ comments like `# this might throw a 404` to understand the control flow. The early-return solution is what I'd call self-documenting code.
- kstrauser 4y agoNo more than you'd need comments like `# this might actually return None`. As long as you're consistent, either approach should be understandable by the people working with it. Note that you can also name functions like `validate_signature_or_raise` if you want to be very explicit.