Tuesday, January 1, 2019

Erlang 的啟發 --- part 2

研讀 Joe Armstrong 的 Erlang 論文,在最後的附錄,發現了 Programming Rules and Conventions 。也是少數讓我大受啟發的 rules and conventions

比方說: Don't make assumptions about what the caller will do with the results of a function


do_something(Args) ->
case check_args(Args) of
ok ->
{ok, do_it(Args)};
{error, What} ->
{error, What}
end.
error_report({error, What}) ->
format_the_error(What).
do_something(Args) ->
case check_args(Args) of
ok ->
{ok, do_it(Args)};
{error, What} ->
String = format_the_error(What),
%% Don’t do this
io:format("* error:~s\n", [String]),
error
end.
view raw WrongSample.erl hosted with ❤ by GitHub
在 WrongSample 的例子, error string 會直接列印於標準輸出 。而在 CorrectSample 的例子, error descriptor 會傳回給使用 module 的 application 。application 可以選擇去使用 error_report 這個函數,或是不去使用它。重點在於: application 才有權力去決定,如何做錯誤處理。