Erlang中的非防御性编程(Non

编程入门 行业动态 更新时间:2024-10-26 21:36:01
Erlang中的非防御性编程(Non-defensive programming in Erlang)

以下内容出现在http://aosabook.org/en/riak.html中第15.1节的第二段中 Erlang的简要介绍

“使用负数调用函数会导致运行时错误,因为没有任何一个子句匹配,没有处理这种情况就是一个非防御性编程的例子,Erlang鼓励这种做法。”

两个问题:在Erlang中处理结果错误的惯用方式是什么? 为什么这会比明确涵盖所有情况更好,如OCaml或Haskell等语言?

The following lines appears in http://aosabook.org/en/riak.html, in the second paragraph of the section: 15.1. An Abridged Introduction to Erlang:

"Calling the function with a negative number will result in a run time error, as none of the clauses match. Not handling this case is an example of non-defensive programming, a practice encouraged in Erlang."

Two questions: What is the way the idiomatic way to handle the resulting error in Erlang; and Why would this be better than explicitly covering all cases, as in languages like OCaml or Haskell?

最满意答案

如果你对错误情况没有任何代码,让系统产生一个运行时错误你至少有3个好处:

代码更小,更易于阅读,侧重于实现的功能。

在出现错误的情况下,系统将提出符合OTP标准的错误,您将免费获得所有OTP机制以在适当的级别处理这种情况。

您会自动避免出现“烤宽面条”错误检测综合症,其中许多代码层跟踪相同的错误情况。

现在您可以专注于错误管理:您将在哪里处理错误。 Erlang通过try和catch语句提供了经典的方法,并且具有OTP监督树和链接和监视机制的更自然的方式。

简而言之,您可以控制一个进程崩溃的后果(哪些进程会随之崩溃,哪些进程将被通知)以及用于重新启动进程的复杂方法。

重要的是要记住,在erlang中,你通常会启动许多具有非常有限作用的小流程和责任,在这种情况下,让它们崩溃并重新启动确实很有意义。

我是learnyousomeerlang网站的粉丝,您将在其中找到与错误管理相关的3章:

错误和例外 错误和过程 谁监督监督员?

If you code nothing for error cases, letting the system generating a run time error you get at least 3 advantages:

the code is smaller, easier to read, focused on the function to realize.

in error cases, the system will raise an error compliant with the OTP standard, you will benefit for free of all OTP mechanisms to handle the situation at the appropriate level.

you automatically avoid the "lasagna" error detection syndrome, where many code layers track the same error case.

Now you can concentrate on the error management: where will you handle the errors. Erlang offers the classical way with the try and catch statements, and has a more idiomatic way with the OTP supervision tree and the link and monitor mechanism.

In a few words you have the control on the consequence of one process crash (which processes will crash with it, which processes will be informed) and sophisticated means to restart them.

It is important to keep in mind that in erlang you generally starts many small processes which have a very limited role an responsibility, and in this case, letting them crash and restart really makes sense.

I am a fan of the learnyousomeerlang web site where you will find 3 chapters related to the error management:

Errors and Exceptions Errors and Processes Who Supervises The Supervisors?

更多推荐

本文发布于:2023-08-01 03:58:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1354036.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:防御性   Erlang

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!