views:

159

answers:

2

When I'm programming in Erlang should I be validating all return values from function calls for success via pattern matching even if i don't intend to use the return value? Most Erlang APIs I've seen so far don't throw exceptions on error (but return something like {error, Error}) so I must need to validate the return value yes? Any exceptions to this where I don't really need to worry about it?

+11  A: 

It's good programming style to crash as early as possible when something has gone wrong. Anything you execute after that will be done with the system in an unknown state.

Unless you intend to handle the error value and do something on it, you write your code for the successful case. As in the following little sad loop:

life() ->
  ok = work(),
  ok = rest(),
  life().
Christian
Christian said it all...+1.
jldupont
Yea, this is what I figured. The problem is one of the 3rd party APIs I'm using doesn't nicely return ok on success. After saving a document it returns the saved document itself. I get back SomeComplexDoc rather than {ok, SomeComplexDoc}.
Jeremy Raymond
@Jeremy, You can just save the document, and then match on it in the next line. `Doc = my_api_call()`, `ok = is_valid_doc(Doc)`.
Zed
Yes that's a good idea. I was doing something similar. SomeComplexDoc was either coming back as some big structure or an atom to indicate error. I could do something like `false = is_atom(Doc)` and this should fail if the save failed.
Jeremy Raymond