ForgeCredoChecks.MapNewFromReduce (forge_credo_checks v0.3.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 high and works with any version of Elixir.

Explanation

Replace Enum.reduce(_, %{}, fn _, acc -> Map.put(acc, k, v) end) with Map.new/2 and a key-value tuple.

Why

The reduce form obscures intent: it spells out an accumulator pattern when "build a map" is the actual operation. Map.new/2 says it directly.

How to fix

# BEFORE
Enum.reduce(things, %{}, fn x, acc ->
  Map.put(acc, x.id, transform(x))
end)

# AFTER
Map.new(things, fn x -> {x.id, transform(x)} end)

The fn drops the acc argument and returns a {key, value} tuple instead of calling Map.put.

What NOT to do

Do not "fix" this by leaving the reduce shape and renaming Map.put to something else. The whole reduce expression is the smell - replace it with Map.new/2.

This check only fires when the fn body is exactly Map.put(acc, _, _) - more complex reduce bodies (conditional inserts, multi-key updates, etc.) are left alone because they may not have a Map.new/2 equivalent.

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.