Credence.Pattern.PreferGuardOverIf (credence v0.7.1)

Copy Markdown

Detects function clauses whose body is a single if/else with a guard-eligible condition. In idiomatic Elixir, prefer multi-clause functions with guards over wrapping the entire body in if/else.

Bad

defp accumulate_run(last_val, [head | tail] = list, current_run) do
  if head > last_val do
    accumulate_run(head, tail, [head | current_run])
  else
    {Enum.reverse(current_run), list}
  end
end

Good

defp accumulate_run(last_val, [head | tail], current_run)
     when head > last_val do
  accumulate_run(head, tail, [head | current_run])
end

defp accumulate_run(_last_val, list, current_run) do
  {Enum.reverse(current_run), list}
end

Auto-fix

Splits the if/else body into two function clauses: the first clause gets the condition as a when guard with the do branch as body; the second clause keeps the original head (with any existing guard preserved) and uses the else branch as its body.