inaka / elvis_core

The core of an Erlang linter
Other
61 stars 56 forks source link

New rule: Avoid duplicate keys in Maps #282

Open elbrujohalcon opened 1 year ago

elbrujohalcon commented 1 year ago

Avoid Duplicate Keys in Maps

Brief Description

The idea is to emit a warning in situations like the following ones (notice the duplication of keys everywhere):

Map = #{key1 => value1, key2 => value2, key1 => value3}.
OtherMap = Map#{key2 := new_value2, key3 => new_value3, key2 := new_value4, key3 => new_value5},
#{key1 := V1, key2 := V2, key1 := V3} = OtherMap.

Should be on by default?

YES

Reasoning

These are perfectly valid Erlang expressions but are often the result of a typo or some confusion from the developers and they can easily be simplified to produce exactly the same output.

Examples

-module bad.

-export [my_fun/0].

my_fun() ->
    Map = #{key1 => value1, key2 => value2, key1 => value3}.
    OtherMap = Map#{key2 := new_value2, key3 => new_value3, key2 := new_value4, key3 => new_value5},
    #{key1 := V1, key2 := V2, key1 := V3} = OtherMap,
    {V1, V2, V3}.
-module good.

-export [my_fun/0].

my_fun() ->
    Map = #{key2 => value2, key1 => value3}.
    OtherMap = Map#{key2 := new_value4, key3 => new_value5},
    #{key1 := V1 = V3, key2 := V2} = OtherMap,
    {V1, V2, V3}.

Origin (#281)

Inspired by the duplicate_key rule from https://coffeelint.github.io/

elbrujohalcon commented 1 year ago

You are probably thinking about the successive maps rule. It’s a similar one, but different to this one.

On Tue, 28 Feb 2023 at 22:03, Paulo F. Oliveira @.***> wrote:

I was sure to have seen this somewhere. Was it in the formatter's issues?

— Reply to this email directly, view it on GitHub https://github.com/inaka/elvis_core/issues/282#issuecomment-1448913313, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAAW3WLHEZC3TDN772DVNVDWZZR2RANCNFSM6AAAAAAVKYDDNI . You are receiving this because you authored the thread.Message ID: @.***>

-- Sent from Gmail Mobile by Brujo Benavides

paulo-ferraz-oliveira commented 1 year ago

Ah, you got it by email and replied 😄 My comment was "I'm sure there was something along the lines of this rule. Maybe I saw it in the formatter".

I was talking about (found it!) this: #156

paulo-ferraz-oliveira commented 1 year ago

(which is not the same, that one deals with assignment to different variables, from the same key)