Code Smell 233 - Collections Count

Maxi Contieri - Dec 1 '23 - - Dev Community

You count collections or collections.count?

TL;DR: Chose narrow names

Problems

  • Bad Naming

Solutions

  1. Accurately describe your collections

Context

Names are significant and should not deceive the reader.

You name things and lose the scope of the name.

It is important to be accurate of the expected reference on the names.

Sample Code

Wrong

const standardModelParticles = {
  quarks: [
    {
      name: "Up",
      charge: "2/3",
      type: "Quark",
    },
    {
      name: "Down",
      charge: "-1/3",
      type: "Quark",
    },
    // ...
  ],
  leptons: [
    {
      name: "Electron",
      charge: "-1",
      type: "Lepton",
    },
    {
      name: "Muon",
      charge: "-1",
      type: "Lepton",
    },
    // ...
  ],
  gaugeBosons: [
    {
      name: "Photon",
      charge: "0",
      type: "Boson",
    },
    {
      name: "W Boson",
      charge: "±1",
      type: "Boson",
    },
    // ...
  ],
  higgsBoson: [
    {
      name: "Higgs Boson",
      charge: "0",
      type: "Scalar Boson",
    },
  ],
};

const quarks = standardModelParticles.quarks.length; 
// Bad name. It does not represent a count
// But a Collection of things
Enter fullscreen mode Exit fullscreen mode

Right

const standardModelParticles = {
}; // Same as the "Wrong" example

const quarksCount = standardModelParticles.quarks.length; 
Enter fullscreen mode Exit fullscreen mode

Detection

[X] SemiAutomatic

Some linters can check the types and names and infer a mistake

Tags

  • Namings

Conclusion

Take care of your names.

Use automatic refactor tools whenever you come across a bad name.

Relations

Disclaimer

Code Smells are my opinion.

Credits

Photo by Sandy Millar on Unsplash


Some people are good programmers because they can handle many more details than most people. But there are a lot of disadvantages in selecting programmers for that reason — it can result in programs that no one else can maintain.

Butler Lampson


This article is part of the CodeSmell Series.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .