[erlang-questions] When to return {ok, Value} or just the Value

Garrett Smith <>
Mon Nov 14 21:47:48 CET 2011


On Sat, Nov 12, 2011 at 6:35 PM, Steve Davis
<> wrote:
> Is there a rule-of-thumb guidance as to when it is the right "time" to
> return {ok, Value} and when to return just the raw value.
>
> Both are valid approaches according to the coding guidelines. The
> libraries do both.
>
> All and any comments/observations appreciated.

I think either approach has its place.

Consider dict:find/2 and dict:fetch/2. Both forms are used for the
same operation.

I read the API's intent as: use dict:fetch/2 if you expect the item,
use dict:find/2 if there's a legitimate case of the item not being
there.

Rather than this form (which is still pretty clear):

{ok, Val} = dict:find("foo", D)

use this (which is clearer):

Val = dict:fetch("foo", D)

You could argue that having both forms needlessly complicates the dict module.

But I think it illustrates the legitimate use of both forms.

In practice, I tend to use tagged tuples (e.g. {ok, Success} | {error,
Error}) for lower level APIs where you tend to exert or require more
control and untagged values + exceptions in higher level APIs when
you're "happy path" is clearer. I think this is very much API /
application specific.

Garrett



More information about the erlang-questions mailing list