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

Hynek Vychodil vychodil.hynek@REDACTED
Mon Mar 23 23:51:29 CET 2009


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

>
> ----- "Hynek Vychodil" <vychodil.hynek@REDACTED> wrote:
> > 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
>
> This could be rewritten with a try and a throw (as I previously showed), so
> the developer is still able to choose. It is about the same amount of code
> as a case statement. The try statement also have the benefit of being able
> to fit more lines of code in a single statement than catch can.
>
> >
> > or as
> >
> > ok = is_new_email(Email);
>
> This will still throw a badmatch when the email address is in use. I don't
> see how that is so much better than a throw. Both will go uncatched if you
> don't do anything.
>
> > 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)
>
> Like I said, there is no big difference. I just like throw since it allows
> for bigger flexibility when combining several statements.
>
> In the end, I guess it is a matter of taste and style.
>
> Cheers,
> Adam
>

1/ Exception costs more than checking return value. In most cases it will
not be issues but you can't assume that it will not be. When it happen, your
code is less flexible.
2/ Flexibility is throw out when I want code like: is_new_email(Email1),
is_new_email(Email2).
Now I can't distinguish which one Email is wrong without catching throw in
each statement. With my code it is easy:
{ok, first_one} = {is_new_email(Email1), first_one},
{ok, second_one} = {is_new_email(Email2), second_one}.
Again, your code is less flexible.

Throwing exception when it is not necessary is less flexible. I can easily
turn return value to exception but opposite way is harder. Explicit throwing
exception *is* slower and less flexible!

-- 
--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/fa3b2c3b/attachment.htm>


More information about the erlang-questions mailing list