[erlang-questions] Erlang style question - input handling
Richard A. O'Keefe
ok@REDACTED
Thu Sep 28 06:47:17 CEST 2006
Nohl Attila Rajmund <attila.rajmund.nohl@REDACTED> wrote:
I have a couple of functions which follow this pattern:
f(X, Y) ->
% collect some data
% do something with the collected data
.
In C/C++/Java I'd insert a code like this
between the collecting part and the "do something" part:
if (!check1(data1)) return ERROR_CODE1;
if (!check2(data2)) return ERROR_CODE2;
if (!check3(data3)) return ERROR_CODE3;
and then the rest of the function would be not touched. However, there
is no return in Erlang so I can't do this.
As a matter of fact, there IS something very similar, and someone who
knows C++ and Java should be familiar with it:
f(X, Y) ->
try
... collect some data ...
check1(data1),
check2(data2),
check3(data3),
... do something with the collected data
catch
check1 -> ERROR_CODE1;
check2 -> ERROR_CODE2;
check3 -> ERROR_CODE3
end.
check1(Data) ->
... if all is well, answer true ...
... if something is wrong, throw(check1) ...
similar for check2, check3.
By the way, I have very serious doubts about the interface of this
function. Why should the caller have to work so hard to figure out
whether they got a good result or a bad one? The natural thing to do
in C++ or Java is *NOT* to return an error code but to throw an
error term, so the expected structure for f/2 would be
f(X, Y) ->
... collect some data ...
check1(data1),
check2(data2),
check3(data3),
... do something with the collected data ...
and the way the caller finds out about a problem is by using
a try/catch.
More information about the erlang-questions
mailing list