Credence.Pattern.NoLengthGuardToPattern (credence v0.4.0)

Copy Markdown

Refactoring rule: Detects guards that check list length with a literal comparison that can be replaced by a pattern match in the function head.

Covers two forms:

  • length(var) > 0 — non-empty check, replaceable with [_ | _]

  • length(var) == N for N in 1..5 — exact-size check, replaceable with [_, _, ...]

Pattern matching is O(1) and idiomatic, while length/1 traverses the entire list.

Bad

def process(list) when length(list) > 0 do
  Enum.sum(list)
end

defp triplet(list) when length(list) == 3 do
  List.to_tuple(list)
end

Good

def process([_ | _] = list) do
  Enum.sum(list)
end

defp triplet([_, _, _] = list) do
  List.to_tuple(list)
end