Idiomatic guard clause for checking not nil

What is the idiomatic way of matching for not nil in Elixir?

E.g.,

First way:
defp halt_if_not_signed_in(conn, signed_in_account) when signed_in_account != nil do

Second way:
defp halt_if_not_signed_in(conn, signed_in_account) when not is_nil(signed_in_account) do

If there is a preferred way does anybody know the reason?

Personally I prefer the first way because it reads more naturally and takes less horizontal space but examples I’ve seen have used not is_nil(...) and I am wondering why.

2 Likes

Personally I do:

defp halt_if_not_signed_in(conn, nil), do: :whatever
defp halt_if_not_signed_in(conn, signed_in_account) do
  ...
end

Unless you just want nil to error out, in which case I’d optimally do a precise match:

defp halt_if_not_signed_in(conn, signed_in_account) when is_binary(signed_in_account)

Or so.

8 Likes

agreed. I find using pattern matching to handle this is very readable.

I’ve helped introduce two Java engineers to Elixir and they both found this a really useful language feature, especially as they discovered some of the powerful variations of pattern matching.

As for other uses of not is_nil(val) vs val != nil I’d say just pick one and be consistent within your project. Personally not is_nil(val) is not my favorite. :slight_smile:

1 Like

I’m personally a fan of val != nil because nil is just an atom, so I don’t even know why it has a specialized function like is_nil/1 anyway, especially since the empty list [] is the nil value on the system, those confused me for a bit when I started Elixir (nil should have been [] as the empty list is named nil standardly, not :nil, blah).

2 Likes