Credence.Rule.PreferMapFetchOverHasKey (credence v0.3.2)

Copy Markdown

Detects Map.has_key?/2 used in if/cond conditions, which typically leads to a double map lookup — once to check existence, again to get the value.

This is a Python idiom (if key in dict: val = dict[key]) that LLMs carry over. In Elixir, Map.fetch/2 or Map.get/3 combines the check and retrieval in a single lookup.

Bad

if Map.has_key?(map, key) do
  map[key] + 1
else
  0
end

if Map.has_key?(seen, char) and seen[char] >= start do
  seen[char] + 1
else
  start
end

Good

case Map.fetch(map, key) do
  {:ok, value} -> value + 1
  :error -> 0
end

case Map.get(seen, char) do
  idx when is_integer(idx) and idx >= start -> idx + 1
  _ -> start
end

Auto-fix

Not auto-fixable — the replacement depends on how the value is used in the body (simple access, comparison, transformation).