Killer Sheep: Better naming for multiples
I was reading this sensible set of naming guidelines kettanaito/naming-cheatsheet: Comprehensive language-agnostic guidelines on variables naming. (github.com) when I got to the last one Singulars and Plurals.
Like a prefix, variable names can be made singular or plural depending on whether they hold a single value or multiple values.
The example then use friend and friends.
const friend = {};
const friends = [];
I maintain that the intention is good but the execution is poor.
- English words are inconsistent in their naming conventions
- The use of s on its own is very subtle and can easily be missed
- Its not explicit there are multiple types of plural object
English words are inconsistent in their naming conventions
Lets look at some:
- Friend -> Friends
- Box -> Boxes
- Knife -> Knives
- Party -> Parties
- Potato -> Potatoes
- Woman -> Women
- Sheep -> Sheep
So to understand our code you have to understand English and the killer is sheep. Or killers are sheep? It’s unclear.
const sheep = {};
const sheep = [];
The use of s on its own is very subtle and can easily be missed
When scanning code the difference of one character especially in long variable names is easy to miss.
const variableWithLongExplicitName = "";
const variableWithLongExplicitNames = [];
Its not explicit there are multiple types of plural object
This is not a plea for Hungarian notation but its not clear from a single s how the object is ‘plural’. In fact it may not even be plural.
const physics = new Array();
const physics = new Map();
const physics = new WeakMap();
const physics = new Set();
const physics = new WeakSet();
const physics = new Object();
Yes even an object is a type of plural, especially if your using the member’s names as an index:
const courses = {
biology: {},
chemistry: {},
physics: {}
};const course = courses.physics;
Proposal for Plural Object naming Convention
Append the word collection to the core object name
This is clear and explicit and looks good, to avoid it being Hungarian notation in disguise the type of collection is not specified (intellisense will help us with that these days).
let course = ""
const courseCollection = {
biology: {},
chemistry: {},
physics: {}
};const courseCollection = ["biology", "chemistry", "physics"];const courseCollection = new Set(["biology", "chemistry", "physics"])
Consistent
- Friend -> FriendCollection
- Box -> BoxCollection
- Knife -> KnifeCollection
- Party -> PartyCollection
- Potato -> PotatoCollection
- Woman -> WomanCollection
- Sheep -> SheepCollection
Obvious
const variableWithLongExplicitName = "";
const variableWithLongExplicitNameCollection = [];
Explicit
const myCourse = courseCollection.find((c) => c.Name === "Physics")
const yourCourse = courseCollection.get("English")