3 ms·
I've read this before and I agree with it. As an elixir programmer, it frustrates me to be reminded of this article because it reminds me of the only thing I fi
by latch 6y ago
I've read this before and I agree with it. As an elixir programmer, it frustrates me to be reminded of this article because it reminds me of the only thing I find torturous about programming in elixir.
Without a way to exit a function early, you either end up with deep nesting (which becomes hard to read/follow after 2-3 levels), or a lot of small function calls to continue/break. In many cases, you can use a `with <-` but if the statement only returns a variable, you need to wrap it into a function (are have a hard-to-read guard clause, which will only work in some cases) to support matching:
Say `User.load` is out of your control and it returns nil | user. I'd love to do:
user = User.load(id)
if user == nil do
return :not_found
end
But I have to either introduce nesting, or decrease the readability with either a guard or a function.
Guard:
# if we just let `nil` flow through to the `else` we won't be able to tell this `nil` from another
with user when user != :not_found <- User.load(id) || :not_found
Function:
with {:ok, user} <- get_user(id)
...
defp get_user(id) do
case User.load(id) do
nil -> :not_found
user -> {:ok, user}
end
end