[erlang-questions] Why doesn't Erlang has return statement?
Viktor Söderqvist
viktor@REDACTED
Tue Dec 16 23:58:58 CET 2014
On 2014-12-16 09.05, aman mangal wrote:
> Moreover, is there a good alternate to avoid nested case statements?
One way is to avoid them is actually not to write them. Especially if
the cases are error handling, handle only the expected case and let
everything else crash.
When I'm parsing some input or structure and want to return {ok, Value}
or 'error' instead of crashing, I often wrap that code in a try-catch.
This is only when dealing with untrusted input and similar situations.
parse_foo_url(URL) ->
case http_uri:parse(URL) of
{ok, {_, _, _, _, Path, _}} ->
case re:split(Path, "/", [{return, list}]) of
["", "foo", Foo] ->
try list_to_integer(Foo) of
FooInt -> {ok, FooInt}
catch error:_ ->
error
end;
_BadPath ->
error
end;
_BadUri ->
error;
end.
---->
parse_foo_url(URL) ->
try
{ok, {_, _, _, _, Path, _}} = http_uri:parse(URL),
["", "foo", Foo] = re:split(Path, "/", [{return, list}]),
FooInt = list_to_integer(Foo),
{ok, FooInt}
catch error:_ ->
error
end.
> Using /catch /statement seems another good alternate but my intuition
> is that it is not good practice, is it?
In the above example I dare to say it's not bad practice. Just don't
overuse try-catch so that it becomes defensive programming and make sure
you don't put any other code inside the try-catch so that you
accidentally catch totally unrelated errors.
Viktor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20141216/71d617a1/attachment.htm>
More information about the erlang-questions
mailing list