Hi there,
recently I’ve seen an article about the with
statement, just another one that describes how it can improve code readability. Ironically, the article ends with a long code snippet, neither concise nor readable, even though the author says some aspects were omitted ‘in favour of simplicity’. The snippet shows that the problem from this posts title can be solved like this:
with {:label1, result1} <- {:label1, expr1()},
{:label2, result2} <- {:label2, expr2()} do
do_something(result1, result2)
else
{:label1, error} -> handle_error1(error)
{:label2, error} -> handle_error2(error)
end
Since I once created a macro that helps do this in (I believe) a more pleasant way, I thought I’ll share it and maybe you like it. So it’s called withl
and can be used as follows:
with label1: result1 <- expr1(),
label2: result2 <- expr2() do
do_something(result1, result2)
else
label1: error -> handle_error1(error)
label2: error -> handle_error2(error) # note that result1 is accessible here in case you need it
end
Our team uses this here and there for almost two years, so one day we put in into our bunch library. In the docs you can find a detailed description and more real-life examples. Let me know what you think