gshaw
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.
Most Liked
OvermindDL1
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.
OvermindDL1
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).
fmcgeough
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. ![]()
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









