[erlang-questions] When to return {ok, Value} or just the Value
David Mercer
dmercer@REDACTED
Tue Nov 15 18:07:40 CET 2011
Why is your second alternative (viz., "f(X) -> Y | exit(..)") not the
default preferred option for all Erlang code? It seems to express your
meaning and intent better than a tuple return code. You can always wrap it
in a try if you want to catch the error.
Me, I always have trouble deciding between exit(.) and error(.).
Cheers,
DBM
From: erlang-questions-bounces@REDACTED
[mailto:erlang-questions-bounces@REDACTED] On Behalf Of Joe Armstrong
Sent: Monday, November 14, 2011 5:25 AM
To: Steve Davis
Cc: erlang-questions@REDACTED
Subject: Re: [erlang-questions] When to return {ok, Value} or just the Value
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/20111115/86077f9d/attachment.htm>
More information about the erlang-questions
mailing list