How to go about filtering out invalid params like nil or empty list before proceed to process the params?
The case
use below seems to be common but it's not clear code -- I am pretty sure there is a simpler and idiomatic way to do this.
def load(token) do
case token do
nil -> nil
[] -> nil
token -> process(token)
end
end
If a function has several clauses, Elixir will try each clause until it finds one that matches. This allows you to "filter" on the basis of supplied arguments - particularly useful if the functions share no common logic.
def load([]), do: IO.puts("empty")
def load(token) when token == nil, do: IO.puts("nil") # Matching `nil' is OK too.
def load(token), do: process(token)
The second clause illustrates the use of guards which permit more general matches, there are a number of predicates that are valid as guards all of which can be attached to (almost) any expression which are used to switch upon function-arguments, recursively or otherwise.
This convention holds across all of the existing BEAM languages and is useful to keep in mind when reading OTP documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With