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

CGS cgsmcmlxxv@REDACTED
Mon Nov 14 11:56:43 CET 2011


As Ulf said, when "all success values must be clearly distinguishable 
from the error values." Just to give a simple example (file test.erl):

-module(test).

-export([can_divide/2,divide/2]).

can_divide(a,b) -> case b of 0 -> {error,"Attempt to divide by 0."}; 
_ELSE -> {ok,"Division allowed."} end.

divide(a,b) -> case can_divide(a,b) of {error,Error} -> 
io:format("~s~n",[Error]), Result = 0; {ok,_} -> Result = a/b end, Result.

This is very useful when you attempt any operation with another 
server/application. Also, it is useful in search or any other operation 
where you don't have control over the result and you don't want your 
code to break due to errors (e.g., you expect floating point number from 
the previous example, but you register the following crash:

** exception error: bad argument in an arithmetic expression
      in operator  '/'/2
         called as 2 / 0

when you try to divide 2 to 0).

CGS





On 11/13/2011 01:35 AM, 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.
>
> best,
> /s
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions




More information about the erlang-questions mailing list