<html>
<head>
<meta content="text/html; charset=windows-1252"
http-equiv="Content-Type">
</head>
<body bgcolor="#FFFFFF" text="#000000">
On 2014-12-16 09.05, aman mangal wrote:<br>
<blockquote
cite="mid:CAL6Z3hzj+UW3HCKzz5Jb9Zq_DwW7Xbk=MCk-g7BjL3BDAowm_Q@mail.gmail.com"
type="cite">Moreover, is there a good alternate to avoid nested
case statements?</blockquote>
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.<br>
<br>
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.<br>
<br>
<tt>parse_foo_url(URL) -></tt><tt><br>
</tt><tt> case http_uri:parse(URL) of</tt><tt><br>
</tt><tt> {ok, {_, _, _, _, Path, _}} -></tt><tt><br>
</tt><tt> case re:split(Path, "/", [{return, list}]) of</tt><tt><br>
</tt><tt> ["", "foo", Foo] -></tt><tt><br>
</tt><tt> try list_to_integer(Foo) of</tt><tt><br>
</tt><tt> FooInt -> {ok, FooInt}</tt><tt><br>
</tt><tt> catch error:_ -></tt><tt><br>
</tt><tt> error</tt><tt><br>
</tt><tt> end</tt><tt>;</tt><tt><br>
</tt><tt> _BadPath -></tt><tt><br>
</tt><tt> error</tt><tt><br>
</tt><tt> end;</tt><tt><br>
</tt><tt> _BadUri -></tt><tt><br>
</tt><tt> error;</tt><tt><br>
</tt><tt> end.</tt><tt><br>
</tt><br>
----><br>
<br>
<tt>parse_foo_url(URL) -></tt><tt><br>
</tt><tt> try</tt><tt><br>
</tt><tt> {ok, {_, _, _, _, Path, _}} = http_uri:parse(URL),</tt><tt><br>
</tt><tt> ["", "foo", Foo] = re:split(Path, "/", [{return,
list}]),</tt><tt><br>
</tt><tt> FooInt = list_to_integer(Foo),</tt><tt><br>
</tt><tt> {ok, FooInt}</tt><tt><br>
</tt><tt> catch error:_ -></tt><tt><br>
</tt><tt> error</tt><tt><br>
</tt><tt> end.</tt><tt><br>
</tt><br>
<blockquote
cite="mid:CAL6Z3hzj+UW3HCKzz5Jb9Zq_DwW7Xbk=MCk-g7BjL3BDAowm_Q@mail.gmail.com"
type="cite">Using <i>catch </i>statement seems another good
alternate but my intuition is that it is not good practice, is it?</blockquote>
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.<br>
<br>
Viktor<br>
</body>
</html>