Hi.
I’m always looking for ways to make code more manageable, readable, and nice to look at. To this end, matching and the case-do
statement have become my favorite tools in doing so.
I often found myself writing code like this:
case condition1 do
match1 -> case condition2 do
match2 -> ...
I tried pulling out the inner case-do
into a function but that wasn’t “pretty” by any standard in a lot of cases. (In some cases it was definitely needed - one size doesn’t fit all.)
What I do these days looks more like this:
case {condition1, condition2} do
{match1, match2} -> ...
{match1, _} -> ...
{_, match2} -> ...
_ -> ...
end
The only thing I don’t like about this is that you have to repeat sometimes the result of one case in another. Just putting it in front of the case statement makes you compute something that might not be needed. You also cannot emulate this:
case condition1 do
match1 -> common = ...
case condition2 do
match2 -> <do something with common>
match3 -> <do something with common>
So, combining a case-do
with tuples is no panacea. But it can clean up some code considerably.
Though you could do this…
common = fn -> <something common> end
case {condition1, condition2} do
{match1, match2} -> common.() ...
{match1, match3} -> common.() ...
{match1, _} -> ...
{_, match2} -> ...
_ -> ...
end
Hmmm…
Any additional ideas are very welcome!