A guide to naming identifiers in a programming language
Learn how to effectively name identifiers in a language with these 8 practical guidelines.
Naming variables, functions, and properties — collectively referred to as identifiers — is an important activity in every major programming language.
In this article, I want to give you some handy and practically applicable tips to naming identifiers effectively in any language. Good naming is paramount to making code self-explanatory and easy to read through.
Rules for naming identifiers
Almost all programming languages enforce certain rules on the programmer when naming identifiers. This is done to prevent one from creating names that could introduce ambiguity into the respective program.
The general rules are pretty much the same across all languages:
- Names can only contain alphanumeric characters (
a-z,A-Z,0-9) and the_character (or even$in some cases, for example, in JavaScript). Hence,first-nameis invalid since it contains a hyphen (-) which is illegal to put in a variable name. - Names can't begin with a digit. Hence,
2ndis invalid. - Names can't contain spaces. Hence,
first wordis invalid. - Names can't be reserved keywords. For example,
letis invalid in JavaScript becauseletis a reserved keyword in the language (used to declare a variable).
Alright, with these rules in mind, let's now get to the guide for naming identifiers.
1. Be descriptive
An identifier's name shall clearly describe what it's meant to hold. You shouldn't need a huge amount of context to be able to extract its meaning.
For instance, suppose that you have to store a user's name in a variable. It would be really bad if you name the variable u for "user" (or some other single-letter name).
u // What does this mean?The name u doesn't tell much about what's stored in the variable. A much better name would be username.
usernameBut, of course, if u models a variable in the underlying logic being implemented, then it's a good choice. For example, u in kinematics (physics) is conventionally called the "initial velocity." In this case, you could well use it.
2. Don't be overly descriptive
Coming up with descriptive identifier names is desirable, but you have to make sure that you remain within the bounds of description. Even too much description can be problematic.
Suppose you want to create a variable that stores the first name of a user. Being exceptionally descriptive, you could name it:
thefirstnameofuser // Too descriptivealthough this would be more than the desired amount of description. A better name would be:
firstnameIn short, you need to try to strike the perfect balance between brevity and descriptiveness.
3. Abbreviate long words if possible
Sometimes, it's really helpful to abbreviate long words in a given name to short and simple words, given that the abbreviation seems sensible and is well-understood.
For example, instead of
databasename // Can be shortenedyou can abbreviate the word "database" down to "db" since it's a pretty familiar abbreviation known throughout the programmer community:
dbnameHowever, bear in mind that abbreviations don't always work well.
For instance, naming a variable that holds the name of an object's property as pname would be a complete mess. pname could mean "property name" or "panel name" or "previous name" and whatnot. A much better name would be propname — with the word "property" abbreviated down to "prop."
4. Use a casing convention to separate words
When an identifier's name contains more than one word, it's desirable to use some kind of a casing convention to be able to distinguish between the words easily.
Let's say you have the following variable that holds the number of questions asked in a quiz program.
questionsasked // What is this?Seeing this name doesn't immediately tell you about the individual words in it. Does it? You probabaly have to gaze at the name for a while before you finally realize that it reads as "questions asked."
Worse yet, in some words the name could even be misinterpreted by the reader of the code. For example, what do you think I meant when creating the variable idenum? Is it "ide num" or "id enum"? Well, I meant "id enum" for "ID enumeration" but the name failed to describe this.
To solve such ambiguities and make long identifier names readable, you must use a casing convention that pairs well with the underlying language. Some common casing conventions are as follows:
camelCasing: every word's first letter is uppercased except for that of the first word, for e.g.indexOf,getElementById.PascalCasing: every word's first character is uppercased. C# uses Pascal casing for almost all identifiers. Some examples from C# are as follows:WriteLine,ReadLine,GetType.snake_casing: every word is lowercased and separated from the other using the_(underscore) character. PHP uses snake casing for most of its predefined functions. Some examples from PHP are as follows:array_push,mysqli_connect,str_split.SCREAMING_SNAKE_CASING: same assnake_casingexcept that all letters are uppercased. This casing is commonly used to denote constants in many programming languages. For example, here are some predefined constants in JavaScript:MAX_VALUE,MAX_SAFE_INTEGER.
Coming back to the example presented above, the variable questionsasked could be renamed to one of the following:
questionsAsked // Camel casing
QuestionsAsked // Pascal casing
questions_asked // Snake casing
QUESTIONS_ASKED // Screaming snake casingAs you can see, now it doesn't require much effort on you side to distinguish between the different words used in the variable's name.
So which convention should I follow?
you ask. Good question. The next snippet expands upon it.
Which casing convention to use?
The two most common conventions used for naming variables in most of the programming languages out there are camelCasing and snake_casing. Of course, this is not to say that all languages use either of these two but they are surely the most common ones.
The question of which convention to use comes down to what the language goes well with.
For example, Java and JavaScript have their standard library built around camelCasing likewise that's the recommendation if you're programming in Java or JavaScript.
Similarly, C and Python have their standard libraries in snake_casing so that makes the most sense to use if you're programming in C or Python.
5. Use questions for Booleans
Booleans — that is, true or false values, are second nature to all programming languages. Naming identifiers representing Booleans, therefore, is a common thing. In this respect, try to ensure that the name you come up with poses a question.
For example, consider the following identifier that states whether the current user under question is an admin:
admin // A "yes or no" or an "admin user"admin could be read in two disparate ways: "admin?" or "admin." The first one asks a question and likely expects a yes or no answer. The second one probably refers to the admin user (like maybe an object). You can make this name better simply by making the question more explicit:
isAdminIt's clear now that isAdmin is certainly not referring in any way to the admin user but rather stating whether the user is an admin or not.
On the same lines, try names like shouldEdit, canInvoke, hasElected instead of edit, invoke, elected. And so on and so forth.
6. Use verbs for functions
Functions are a familiar abstraction available in all modern programming languages. They represent an action such as adding two numbers together, hashing a password, sending an HTTP request, etc.
Notably, since a function represents an action, it's ideal to name it after a verb in English — for example, "run", "eat", "sleep", "drive" — which is also used to represent an action.
Let's say that you have a function that submits some form data (in the browser) to a given URL endpoint. It's named as follows:
formDataSubmission() // A bit awkward nameEven though the name somehow does indicate what it's meant to do, it's a bit awkward. A better name would be to turn this into an active verb like:
submitFormData()7. Use appropriate prefixes or suffixes
Sometimes, it makes perfect sense to name a given entity based on the concept it represents but that might blur the line between it and another entity. What do I mean by this?
For example, in C#, you might have an interface, which is certainly a different entity compared to a class. (You're not required to understand what an interface or class really is; just that they are different concepts.) Let's say that the interface represents an HTTP request. So you might name the interface as:
HttpRequest // Interface or class?Now, just by reading this name, it isn't clear that whether HttpRequest is an interface or a class. In large-scale software development, it's often handy to be able to distinguish between different software components just by their names, or else it would be untenable to work with the codebase.
Coming back to the C# interface's name, as per the convention set forth by C#, you should prefix interface names with "I." Therefore, the name should rather be:
IHttpRequestAs soon as you read IHttpRequest, there's no second-guessing involved in determining that it represents an interface. Problem solved!
Let's consider yet another example, this time of a suffix.
In (client-side) JavaScript, interfacing with the HTML DOM API is second nature. I've actually seen many code snippets that name HTML DOM elements by the element they represent. For example, one might call the element returned by selecting a <button> element as follows:
button // What is this button?Is this a bad name? Yes and no.
"No" because it does convey what the identifier actually represents — a button. "Yes" because it isn't clear that whether button is an HTML DOM element or an instance of some other type. A better name would include a suffix like "el" or "element" at the end to convey that it represents an element, as follows:
buttonEl
buttonElement8. Stay consistent
Before rounding up this discussion, let me present perhaps the most important rule to abide by when naming identifiers in your programs — in fact, when writing code itself. It is consistency.
If you name an interface as IHttpRequest stick to it; don't ever name an interface without the "I" prefix. Similarly, if you name functions based on verbs (e.g. editForm), don't transition to a noun (formEditing).
Consistency is easier said than done. A huge part of software design principles has its roots in the ever-green rule of consistency; henceforth, consistency in naming should actually train you towards that larger goal.