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

mats cronqvist masse@REDACTED
Tue Mar 24 16:27:37 CET 2009


Hynek Vychodil <vychodil.hynek@REDACTED> writes:

> 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.

  If the exception is generated. Presumably, the exception is only
  thrown relatively rarely, in which case you win.

> 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!

  Well, no.

  mats



More information about the erlang-questions mailing list