LexCredo.Check.Warning.NoComplexWithElse (LexCredo v0.1.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

Avoid complex else blocks in with expressions.

When multiple clauses can fail and each needs different handling, normalise error return types in small private helper functions so the with expression focuses only on the happy path. If you genuinely need to distinguish error sources, use case instead.

# BAD — 2 else clauses, default max is 1
with {:ok, user} <- fetch_user(id),
     {:ok, post} <- fetch_post(user) do
  post
else
  {:error, :not_found} -> {:error, :user_not_found}
  {:error, :forbidden} -> {:error, :access_denied}
end

# GOOD — each function returns a normalised error atom,
# so a single catch-all clause in else is sufficient
with {:ok, user} <- fetch_user(id),
     {:ok, post} <- fetch_post(user) do
  post
else
  {:error, reason} -> {:error, reason}
end

Check-Specific Parameters

Use the following parameters to configure this check:

:max_else_clauses

Maximum number of else clauses allowed (default: 1).

This parameter defaults to 1.

:exclude_test_files

When true, skips test files. Default: false.

This parameter defaults to false.

General Parameters

Like with all checks, general params can be applied.

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