I am struggling to come up with a clean way to do input validation in Elixir.
In a OOP language i would do something like this:
def my_func(a, b):
if !validate_a(a):
raise ArgumentError
if !validate_b(b):
raise ArgumentError
return "something"
The best i could come up with in Elixir is this:
def my_func(a, b) do
cond do
not valid_a?(a) -> {:error, "a is invalid"}
not valid_b?(b) -> {:error, "b is invalid"}
:otherwise -> {:ok, "something"}
end
end
I know that i could also raise an exception in Elxir, but i like pattern-matching against the return type a lot better, since my code doesn't get cluttered with try/rescue blocks.
Is there a preferred pattern to do this in Elixir?
:otherwise ->
for the last case, I've seen most people usetrue ->
. – Dogbert:else
or:otherwise
for readability. – Luca Fülbier