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

Adam Lindberg adam@REDACTED
Tue Mar 24 14:48:37 CET 2009

----- "Hynek Vychodil" <vychodil.hynek@REDACTED> wrote:
> 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.

Well, just throw {email_in_use, Email} then?

Using tagged tuples just for pattern matching (and really just to make the badmatch error more informative) isn't very readable. It just adds a lot of clutter.

With the try statement, you CAN have several expression in the same block. You can't have that with a case statement. Unless you accept executing them both to know if either one failed, like in case {a(), b() of {true, true} or something.
> 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!

Performance is rarely an issue in real life code with these kind of constructs. If it is, you probably have bigger problems than changing all your try statements to catch statements.

It is not harder to change throw to a return value, than a return value to a throw. Either way you're doing it, it is the same amount of code.

Exceptions are used for exceptional things, like for example when a user tries to register with an email already in use. Probably the same user or another user who misspelled, not really that common to be a performance bottleneck.

It is also nice to use throw since it is a developer intended exception and is very visible when it is not catched. If you get a badmatch somewhere high up in your code then you probably have a bug somewher. If you get an uncatched throw, then you know you haven't implement the necessary code to handle the exception.


More information about the erlang-questions mailing list