When should an Erlang function return ok?
I often see Erlang functions return ok
, or {ok, <some value>}
, or {error, <some problem>}
.
Suppose my function returns an in开发者_开发百科teger N. Should my function return just N, or {ok, N}
?
Or suppose my function includes the call io:function("Yada yada")
. Should it return ok
or nothing at all?
Or suppose I'm making a record or fun. Should I return {ok, R}
or (ok, F}
?
Thanks,
LRP
It's a matter of style, but making reasonable choices goes a long way toward making your code more readable and maintainable. Here are some thoughts based on my own preferences and what I see in the standard library:
- If the function can return with both a success and a recoverable failure case, you may want the success case to look like
{ok, _}
orok
. Good examples are:orddict:find/2
andapplication:start/1
. We do this so both cases can be easily pattern matched when making the call. - If the function has only a success case with a meaningful result, then just return the result as there is no need to add additional information. In fact if you were to wrap the result in a tuple, then you can't easily chain calls together e.g.
foo(bar(N))
may not work ifbar/1
returns{ok, _}
. Good examples are:lists:nth/2
andmath:cos/1
. - If the function has only a success case without a meaningful result, the common idiom is to return
ok
ortrue
as opposed to whatever the last returned value in the function happened to be. Good examples are:ets:delete/1
andio:format/1
.
Suppose my function returns an integer N. Should my function return just N, or {ok, N}?
If there is no possibility of error at all, or any error indicates a programming error, N
. If there may be a good reason to fail, return {ok, N}
(and {error, Reason}
in case of failure).
Should it return ok or nothing at all?
In Erlang, you can't return nothing at all. If you don't have a meaningful return value, ok
will do fine.
This is a conundrum I find myself in many atimes. The rule of the thumb (atleast my thumb) is that if a function is to be used primarily with other functions (higher order functions like map(), filter() etc..) or if the function is designed to be "purely" functional (no side effects), then I would prefer to NOT return an {ok, _} and simply return the result. Errors in this case must be due to some logical/algorithmic error which should be fixed and the client of the function should be made aware of any such error.
精彩评论