For me, naming a variable is similar to giving a baby a name. It could tell us a bit about who they are or what they will become. I overthink about picking out the right one. It is not just variables. There are also functions, arguments, classes, packages, source files, and directories. Many programmers have acknowledged the difficulty in naming things, yet few use explicit guidelines. First, we will address the benefits of using a guideline, and then we will go over some naming guidelines, some borrowed from Clean Code. A solid foundation will help us get started.
The Benefits in Making Names Meaningful
How many of us have been stopped and surprised by finding a unique name for a certain variable or function? A famous engineer once said:
There are only two hard things in Computer Science: cache invalidation and naming things
But why is it so important to have things named properly?
Chances are you know the struggle when you have had thoughts like “What does this name even mean?”, “What’s the difference between this and that?”, or “What does this actually do?”. Few of us know the value of having intentional names. The weight of it carries over into the future. It can negatively affect you and your team. If not, the reverse effect will result in improvement in the following areas:
- Consistency
Familiarity with your code creates confidence. A naming guideline encourages that expectation. This is especially potent in a team environment. A standard is something we want to use, even as a general guideline. Otherwise, we’d be picking each other’s naming abilities and having the discussion during the code review or halfway through the development.
- Readability
You relieve yourself of cognitive load when you understand something. No one likes to get their head in a twisty. By having clarity, you are effectively communicating the purpose of your code and your teammate will thank you.
I was given a task to do some rework on an existing codebase when I found myself stuck and staring at a name. I didn’t understand there until I looked deeper into the code’s implementation. Why couldn’t it have been self-explanatory in the first place?
- Productivity
No prior guidelines or thought put into naming will hold you back from finishing the project or task.
You reread the code implementation to figure out what's going on. More time passes than is required. It turns out that failing to take the time to properly name your software will double in the long run.
Don’t underestimate the impact of good titles or names. Having good names increases code integration and removes misunderstandings, which in turn improves other areas, such as code maintainability and code reuse!
Starter Kit for Naming Guidelines (and Best Practices)
To model a naming guideline we need to know how names are designed. This require heaps of experience in programming, _especially _with a team.
Fortunately, there are already few great models out there we can get some exposure in order to build our foundation upon.
Naming guidelines are meant to be shared and used upon in the codebase. They are an agreement on what to use and not use.
Here are my takeaways with Clean Code and other articles which provides some excellent points to go follow.
Use Intention-Revealing Names
Think big questions for variable, function or class. Answer the following questions: “why it exists”, “what it does”, and “how it is used”.
Change Names Again When you Found its Real Purpose
We’re not done when we have chosen our name and written the code. Look back and see if yesterday’s code make sense today. With new information and features coming, the purpose of the code in examination may change.
Avoid Disinformation and Noninformation
Information has consistency in naming and often uses existing knowledge to aid its naming. We don’t want to always pull out a dictionary or look up the term in our browser. Disinformation is not directly answering what the code is intended to do. Hence, it lacks meaning and transparency. Meanwhile, noninformation does not have a meaning or clue.
- Abbreviation can be disinformative.
In general abbreviation is discouraged.
e.g. c
can stand for "Carbon", "Celsius" or "Century"
Names that intertwine with existing programming concepts is confusing.
e.g. str
can mean "strength" or, in programming terms, "string". It will vary in different project scope, but when you are making an RPG game you may have this conflict.
However, I would make an exception for a list being looped.
e.g. cards
is an array and I only expect an item.
cards.map((c) => c);
c
could be rewritten as card but it is already implied.
- zero
0
, lowercaseo
, uppercaseO
, and lowercase l are truly horrible variable names.
It's difficult to tell the difference between the number zero, the letter "o", uppercase and lowercase. It's the same with the lowercase letter "l" and the number 1
. More so when combined!
e.g.
let a = l;
if ( O == l ) {
a = O1;
} else {
l = 01;
}
- Number series naming is noninformative.
They might as well be written in hieroglyphs.
e.g.
Array.prototype.swap = function (x1, x2) {
var b = this[x1];
this[x1] = this[x2];
this[x2] = b;
return this;
}
x1
could have been source
and x2
could have been target
.
Make Meaningful Distinction
When met with similar concepts, which are frequently given a very general name, you may be tempted to use it everywhere else with a slightly tweaked version. But you can’t (and that’s just lazy naming).
Make further distinctions when you come across the following:
- Plural ending with “s”
e.g. The plural of apple
is only one letter different from apples
. With the untrained eyes, programmers can miss this marginal detail. They can be solved by making them into Collective Nouns. Think of something like basketOfApples
or bunchOfApples
.
- Noise Words — Same Meaning, Different Spelling
Don’t even use the same term for two different purposes.
e.g. What is the difference between totalOfCash
and amountOfIncome
? They both mean the same thing. Figure out the specificity and differentiate.
Indistinct Noise Words
e.g. Attaching words like these articles like a
, an
, or the
don't mean anything more different when you are simply writing the name of it. There's nothing wrong with using them. It is just useless in a case like thePerson
or aPerson
. Make names differ by more than one or two letters.
Similarly with member prefixes you don't need them when your class and functions are small. As developers spend more time reading the code they ignore the prefix or suffix to see the meaningful part of the name.
e.g.
function sendEmail(input) {
const a_txt;
setMessage(a_txt + input)
}
_________________________________________________
function sendEmail(input) {
const text;
setMessage(text + input)
}
A more cut out version of noise words is when there is no other words attach to further describe what is they are. Like total
and amount
are still similar and share the same meaning except on their own it doesn't say much. "Total" of what? "Amount" of what?
Use Pronounceable Names
When you enter the tech field, you’d be surprise that programming is a social activity. So if you can’t pronounce the variable you are referring to, you will not be able to have a discussion without sounding silly!
Use Searchable Names
The search bar in your code editor can narrow down results when names become more unique. This is essential when tasked in refactoring the codebase.
Here’s how we can make names more searchable:
Use longer names over shorter names
Single-letter names results in maximum ambiguity. Longer names acts as a better identifier and gives enough context.
There is an exception: single-letter names are okay in local variables inside short methods. See example in Avoid Disinformation and Noninformation in point “Abbreviation can be disinformative”, where an array is mapped and what items are already implied.
Use constant naming convention over raw values
e.g. MAX_PASSENGER_ON_BOARD tells you more than the number 9.
Class Names
Here are some classic guidelines used to assist in naming classes that exist within object-oriented languages.
- Noun or noun phrase names
By using a noun you make sense of the new
keyword which initialise it.
e.g.
const apple = new Fruit("sweet", "crunchy");
It makes less sense with a verb attached to it or as a verb. e.g. new createFruit()
, new Swim()
.
Think concrete words, something that has a single clear meaning.
- Open to different states
Avoid class names that would be inconsistent with the state when calling a method that changes the state.
Make the name less specific.
e.g. new FelineDomesticAnimal
is too closed off from what it can or cannot be (it says only cats allowed). Something like new Animal
allows more diversity.
Cover all expected values. Don’t write the means to an end. Avoid contradiction. Write the field. Use a name that applies to values the state may hold.
e.g. A class with method start
and end
may have a name like Race
, not FinalRace
. "Final" suggest it is sided with the method end
.
Make it inclusive.
Method Names
Method names should be a verb or a verb phrase name.
e.g. saveDocument
, playMusic
or delete
.
For accessors, mutators, and predicates, the JavaBeans Naming Convention says they should be named for their value and prefixed with get
and set
. Therefore, only use these for field access.
e.g.
const grade = student.grade();
teacher.setGrade(80);
For methods with side-effects, do not use get
, is
, or has
prefixes.
Use Solution Domain Names
Don’t be afraid to use Computer Science terms, algorithm names, pattern names, math terms and so forth. The people who are reading your code are programmers.
Whereas, if there is no programmers, use problem domain names. Code that has to do with problem domain concepts should have names that derive from it. Even though we may not know what it means, we can at least ask the domain expert what it means. It saves the hassle of writing up your own castle of names and referring back and forth to the blueprint domain names given.
Add Meaningful Context
Names can be meaningful by themselves, but when they are not, you need to place them in context for your reader. Enclose them in well-named classes, functions or namespaces. If fail, prefix the name to add the necessary context.
Concluding Remarks
Clarity is king. We write code for humans, not just to satisfy the compiler of our computer. We want to skim over our code and produce as fast as possible. We don’t want to spend an hour deciphering a code name. I don’t blame others, it is hard naming things. An established naming guidelines helps elevate the difficulties we share on deciding a name, one which we can all agree on and feel at ease understanding. Once you are a more seasoned developer you can customize or improve the standard!
References
Robert Cecil Martin. “Clean Code: A Handbook of Agile Software Craftsmanship". Courier in Stoughton, Massachusetts, USA: Pearson Education, Inc, 2009 (book)
Jolas. “Meaningful Names — A Dimension of writing Clean Code”. 2017 (article)
Peter Hilton and Felienne Hermans. “Naming guidelines for professional programmers” 2017 (article)
Top comments (0)