Code Smell 233 - Collections Count
1 December, 2023
21
21
0
Contributors
You count collections or collections.count?
TL;DR: Chose narrow names
Problems
- Bad Naming
Solutions
- Accurately describe your collections
Context
Names are significant and should not deceive the reader. f 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
Right
const standardModelParticles = {
}; // Same as the "Wrong" example
const quarksCount = standardModelParticles.quarks.length;
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
Code Smell 163 - Collection in Name
Code Smell 134 - Specialized Business Collections
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
Software Engineering Great Quotes
This article is part of the CodeSmell Series.