Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should an Erlang function return ok?

Tags:

erlang

I often see Erlang functions return ok, or {ok, <some value>}, or {error, <some problem>}.

Suppose my function returns an integer 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

like image 368
Lloyd R. Prentice Avatar asked Jul 25 '11 17:07

Lloyd R. Prentice


2 Answers

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, _} or ok. Good examples are: orddict:find/2 and application: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 if bar/1 returns {ok, _}. Good examples are: lists:nth/2 and math:cos/1.
  • If the function has only a success case without a meaningful result, the common idiom is to return ok or true as opposed to whatever the last returned value in the function happened to be. Good examples are: ets:delete/1 and io:format/1.
like image 85
David Weldon Avatar answered Oct 13 '22 01:10

David Weldon


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.

like image 38
Alexey Romanov Avatar answered Oct 13 '22 00:10

Alexey Romanov