Rbtz.CredoChecks.Warning.SortKeywordValidateResult (rbtz_credo_checks v0.2.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

Requires Enum.sort/1 between Keyword.validate!/2 and any binding that pattern-matches the result.

Keyword.validate!/2 returns the keys in the order they appear in the input keyword list, not in the order of the defaults. That means [a: a, b: b] = Keyword.validate!(opts, a: 1, b: 2) only matches when the caller happens to pass [a: ..., b: ...] — flip the call site to [b: ..., a: ...] and the pattern crashes at runtime. Sorting the result first makes the pattern deterministic regardless of caller ordering.

Bare calls without binding (e.g. Keyword.validate!(opts, [:foo]) used purely for its raise-on-unknown-key side effect) are fine and not flagged.

Bad

[foo: foo, bar: bar] = Keyword.validate!(opts, foo: 1, bar: 2)

Good

[bar: bar, foo: foo] = opts |> Keyword.validate!(foo: 1, bar: 2) |> Enum.sort()

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.