4 ms·
> I'm not sure how often you want to recover from such a state though. Pretty much always in real systems software. Imagine a multithreaded server that handle
by otabdeveloper1 8y ago
> I'm not sure how often you want to recover from such a state though.
Pretty much always in real systems software.
Imagine a multithreaded server that handles HTTP requests. A catastrophic invariant failure when handling one requests shouldn't bring down the whole server.
Or imagine an application that calls into a money transaction routine. (This routine can itself call other routines, and so on for 12 stack frames deep.) A catastrophic failure in sending money shouldn't bring down the whole app, it should show a clean "money transfer failed, please try again" message.
- qwertycrackers 8y agoThat's why you would return a Result from all those and handle any failures that way. The Result type is meant to be used any time an operation could fail.
- setr 8y agoWhen I'm talking about invariants, I mean something much more fundamental than a web-request failing. It's not a necessarily invalid state (and I'm not sure ever should be for any well-behaved program). It would be invalid if you've explicitly decided not to handle the scenario, but at least in Rust (and assuming the function properly returns Result<>), you can't forget to not handle it. Essentially where you'd have asserts() in C. eg Your in-place sort function is meant to maintain a sorted list for all elements traversed so far: you add a panic check to guarantee this. It fails; the invariant is broken, and there's no recovering from such a state (your sort is not sorting! you're going to add a handler for this..?). A web-request failing is a simple, normal, expected failure (hence the Result<> type). Adding 1+1 and getting 3 is a broken invariant, and there's no coming back from it. Again, you can (probably) catch it in Java since it throws exceptions on anything and everything... but why would you want to? If you take its to its conclusion, you're not trusting any aspect of the language anymore: you'll have to check every bit of code for arbitrary outcomes. It seems to me similar to javascript allowing you to basically pass in anything to everything and get ...some... output, but its an extremely bug-prone methodology. panic! is, afaik, intended for those situations where it should bring down the whole application (before you start adding $3 to person A, but subtracting $2 from person B); primarily to catch programmer errors, not execution errors. Errors that can be recovered from are Result<>, and the Result<> type forces you to handle all possible outcomes (which the caller might decide is a panic!). A failed web-request is most certainly a Result<> in this model, not a panic!.