Rbtz.CredoChecks.Readability.PreferNilEquality (rbtz_credo_checks v0.4.0)

Copy Markdown View Source

Basics

This check is disabled by default.

Learn how to enable it via .credo.exs.

This check has a base priority of normal and works with any version of Elixir.

Explanation

Prefers x == nil and x != nil over is_nil(x) and not is_nil(x) in conditional and assertion positions, for consistency with other equality checks at the same call site.

The check fires only inside the boolean expression of if, unless, cond clause heads, the case scrutinee, and the first argument of assert / refute. It descends through boolean operators (and, or, &&, ||, not, !) but does not descend into arbitrary function arguments — foo(is_nil(x)) is not flagged because the condition being tested is foo(...), not is_nil/1 itself.

is_nil/1 remains the right (and required) choice in when guards and in Ecto query DSL, so those uses are unaffected.

Bad

if is_nil(user), do: redirect()
unless not is_nil(token), do: raise "no token"
cond do
  is_nil(x) -> :missing
  true -> x
end
assert is_nil(result)
refute not is_nil(result)

Good

if user == nil, do: redirect()
unless token != nil, do: raise "no token"
cond do
  x == nil -> :missing
  true -> x
end
assert result == nil
refute result != nil

# Guards: keep is_nil
def fetch(x) when is_nil(x), do: :missing

# Ecto: keep is_nil
from u in User, where: is_nil(u.deleted_at)

Check-Specific Parameters

There are no specific parameters for this check.

General Parameters

Like with all checks, general params can be applied.

Parameters can be configured via the .credo.exs config file.