When to “let it crash” and when to defend the code

2020-07-22 09:50发布

问题:

So, with "let it crash" mantra Erlang code is meant to be resistant to cruel world events like unexpected pulling the plug, hardware failure, and unstable network connections.

On the other hand, there is defensive programming.

Being new to Erlang, I wonder, how to know when I want the process just crash and when I want it to defend the flow with if, case..of, type guards?

Say, I have an authentication module, which can return true/false result if authenticated successfully or not. Should it just have successful scenario and crash if the user authentication fails due to wrong login/password?

What about other scenarios, like, if a product is not found in the database, or search results are empty?

I suppose, I can't ignore defensive constructs completely, as any guards are in their nature to defend the "normal" flow of the app?

Is there a rule of thumb when to defend and when to crash?

回答1:

As Fred Hebert says at http://ferd.ca/the-zen-of-erlang.html -

If I know how to handle an error, fine, I can do that for that specific error. Otherwise, just let it crash!

I'd say that authentication errors, empty search results, etc., are expected errors and those that warrant an appropriate response to the user.



回答2:

I don't think there is actually a Rule of Thumb in this case.

As I see it, whenever you know how to handle an expected error - handle it. In case of authentication, I don't really think it's an actual error, it's a normal behavior so go ahead and write few lines of code to handle this specific case.
In contrast, network failure is something that might happen for various of reasons, they are not actually expected as part of your code normal behaviour, so in this case I would go with the "let it crash" philosophy.

Anyway, when going with let it crash - you of course still need to handle the case where the process crashed (i.e. using links and monitors and restarting the process).

Please check also this very good answer. And you may read more about it here and here.



标签: erlang