credo icon indicating copy to clipboard operation
credo copied to clipboard

add `Credo.Check.Readability.NoCaptureOperator`

Open markmark206 opened this issue 6 months ago • 2 comments

(Thank you for this super-neat tool!;)

Please add a check (off by default, low priority) that would generate a warning on capture operator.

Reasoning:

Some teams might prefer explicit anonymous functions for ease of "at a glance" readability.

While the capture operator allows for shorter code, it adds cognitive overhead (and possibility of mis-reading) for the person quickly reading the code.

Code Examples:

  1. the "capture operator" version
current_execution.values
|> Enum.map(& &1.node_name)

(this code would be flagged by Credo.Check.Readability.NoCaptureOperator)

  1. the "anonymous function" version
current_execution.values
|> Enum.map(fn value -> value.node_name end)

Option 2 is obviously more verbose and not as clever, but it is also more explicit, and easier to correctly understand at a glance by developers even relatively new to Elixir, which is important for some teams.

markmark206 avatar Aug 26 '25 03:08 markmark206

I am not against this per se, but I have a feeling that we want to be able to allow your example:

Enum.map(values, & &1.node_name)

or

Enum.map(values, &MyModule.fun/1)

but disallow more complex cases like

Enum.map(values, & [&1, Math.sqrt(&1)])

or

Enum.map(values, &Mod.puts(:stderr, &1))

WDYT?

rrrene avatar Oct 16 '25 19:10 rrrene

I think we may want this rule to only allow the following forms:

Enum.map(values, &FunctionModule.increase/1)

Enum.map(values, &FunctionModule.increase(&1, 2))

Enum.map(values, my_func)

My argument is that you force that the explicit behavior is declared and enclosed in its own function block, hence making it easier for you to make sense of what the code is doing. It also helps readability because you are not making inline business logic, which could happen if you allow anonymous functions or standalone capture operations.

Would it make sense?

jmalovera10 avatar Oct 19 '25 15:10 jmalovera10