Rbtz.CredoChecks.Refactor.PreferWithOverCase (rbtz_credo_checks v0.8.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

Flags a two-clause case whose only non-happy-path clause re-returns an error it matched, unchanged. A with expresses this more directly: its implicit else returns the non-matching value as-is, so the pass-through clause disappears.

Bad

case File.read(path) do
  {:ok, contents} -> {:ok, String.trim(contents)}
  {:error, reason} -> {:error, reason}
end

Good

with {:ok, contents} <- File.read(path) do
  {:ok, String.trim(contents)}
end

The pass-through clause must re-return an error shape — an {:error, ...} tuple or the bare :error atom — whose body is structurally identical to the pattern it matched ({:error, reason} -> {:error, reason}, :error -> :error).

To keep rewrites safe, only this shape is flagged. These are not flagged:

  • case with one clause, or three or more clauses.
  • Both clauses doing real work (no pass-through clause).
  • Both clauses being pass-through clauses (an identity case).
  • A pass-through clause that isn't an error shape (e.g. nil -> nil, other -> other).
  • A clause head with a when guard.
  • A catch-all happy path (_ / a bare variable) paired with the error pass-through — the rewrite would depend on clause order.

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.