[erlang-questions] How do I elegantly check many conditions?

Hynek Vychodil vychodil.hynek@REDACTED
Mon Mar 23 14:22:39 CET 2009


On Mon, Mar 23, 2009 at 1:39 PM, Adam Lindberg
<adam@REDACTED>wrote:

> ----- "Hynek Vychodil" <vychodil.hynek@REDACTED> wrote:
>
> > One of Joe's suggestion: program success case code separated from
> > error
> > handling. You can make it in this way
> >
> > create_user(Email, UserName, Password) ->
> >   try
> >     ok = new_email(Email),
> >     ok = valid_user_name(UserName),
> >     ok = new_user(UserName),
> >     ok = strong_password(Password),
> >     ...
> >     _create_user(Email, UserName, Password)
> >   catch
> >     error:{badmatch, email_in_use} -> do_something();
> >     error:{badmatch, invalid_user_name} -> do_something();
> >     error:{badmatch, user_exists} -> do_something();
> >     error:{badmatch, weak_password} -> do_something();
> >     ...
> >   end.
>
> Why use badmatch?
>
> create_user(Email, UserName, Password) ->
>  try
>     is_new_email(Email),
>    is_valid_user_name(UserName),
>    is_new_user(UserName),
>    is_strong_password(Password),
>     ...
>    _create_user(Email, UserName, Password)
>  catch
>     email_in_use      -> do_something();
>     invalid_user_name -> do_something();
>     user_exists       -> do_something();
>     weak_password     -> do_something();
>    ...
>  end.
>
>
> Validation functions can use throw:
>
> is_new_email(Email) ->
>  case mnesia:dirty_read(email, Email) of
>    []    -> ok;
>    _Else -> throw(email_in_use)
>  end.
>
> Cheers,
> Adam
>

If I have function like

is_new_email(Email) ->
 case mnesia:dirty_read(email, Email) of
   []    -> ok;
   _Else -> email_in_use
 end.

I can choose if use it as

case is_new_email(Email) of
  ok -> do_something();
  email_in_use -> do_something_other()
end

or as

ok = is_new_email(Email);

When You trow exception, I can't choose.
Don't make assumptions about what the caller will do with the results of a
function (http://www.erlang.se/doc/programming_rules.shtml#HDR3)

-- 
--Hynek (Pichi) Vychodil

Analyze your data in minutes. Share your insights instantly. Thrill your
boss.  Be a data hero!
Try Good Data now for free: www.gooddata.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20090323/e099f6dd/attachment.htm>


More information about the erlang-questions mailing list