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

Joe Armstrong erlang@REDACTED
Mon Nov 14 12:24:57 CET 2011


You have several alternatives

      f(X) -> Y                  uses if you know computing f(X) always
returns Y for all X

      f(X) -> Y | exit(..)     if "most" values of f(X) are valid and you
could not take care of the
                                     error case in the caller

      f(X) -> {ok, Y} | {error, Z}   if some values of X cause f(X) to fail
and you want to take care
                                                of the error in the caller.

      returning {ok, Y} | {error,Z} is a strong signal to the person
reading the code that the caller will
      do something with *both* return values.

      The caller might just write {ok,Val} = f(X) and not handle the error
case, but the reader of the
code will think - "ahh something might go wrong, and this code may need to
be fixed later."
it's not just what you write but what will be inferred by the reader.

      Code using {ok, Val} | {error, Why} tends to lead to messy cascades
of nested cases, so the
      Y | exit(...) code style looks prettier.

      The entire picture gets complicated sing catch/throw/try etc. so
there is no "right" answer.

      I guess you should choose be locally consistent in your code - choose
a convention and stick to it
in your code and chose the variant that will be easiest to read and
maintain. If you end up with
loads of nested cases/trys you might have chosen the wrong convention.

Cheers

/Joe




On Sun, Nov 13, 2011 at 1:35 AM, Steve Davis <steven.charles.davis@REDACTED
> 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.
>
> best,
> /s
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20111114/580c616e/attachment.htm>


More information about the erlang-questions mailing list