Naming Things#
There are only 2 hard problems in computer science: cache invalidation, naming things, and off-by-1 errors.
—Leon Bambrick
So what’s in a name? A lot, actually. Naming things is one of the most important aspects of programming. It’s the first thing you do when you create a new variable, function, or class. It’s the first thing you see when you read someone else’s code. It’s the first thing you need to understand when you’re trying to figure out what a piece of code does.
In this chapter, we’ll talk about the importance of naming things, and we’ll go over some best practices for naming variables, functions, classes, and other things.
// Check to see if the employee is eligible for full benefits
if ((employee.flags & FULL_TIME) && (employee.age >= 68))
//Or this?
if (employee.isEligibleForFullBenefits())
Why Naming Things Is Important#
Take a look at the image below.
Say the words out loud as they are written
Say the colours of the words out loud
I bet that even of you succeeded in step 2 you probably had to put in a lot more effort than in step 1. This is because the brain is wired to read words and not colours.
Any compiler can translate code written in a programming language into machine code that a computer can execute. But only a human can read and understand code written in a programming language. And the better the code is named, the easier it is for a human to read and understand it. So you are not really writing code for the compiler/interpreter but for other developers (including your future self). So it is not a trivial matter to name things well.
It is therefore also very important to review the names of things in your code. If you find a variable, function, or class that is not named well, you should refactor it.
Best Practices for Naming Things#
Good names should adhere to the following rules. Names should be:
Informative
Consistent
Concise
Searchable
One should of course take the naming convention of the specific programming language into account. If CamelCasing is the convention (e.g. Java), then one should use that. If snake_case is the convention (e.g. Python), then one should use that.
Informative#
Names should be informative. They should describe what the variable, function, or class represents. They should be descriptive enough to give other developers (and your future self) a good idea of what the code does.
For example, instead of naming a variable x, you should name it number_of_items. Instead of naming a function f, you should name it calculate_total. Instead of naming a class C, you should name it ShoppingCart.
Consistent#
Names should be consistent. They should follow the same naming conventions throughout your codebase. This makes your code more readable and maintainable.
Concise#
Names should be concise. They should be short enough to be easy to read and type, but long enough to be descriptive. If a name is too long, it can be hard to read and type. If a name is too short, it can be hard to understand.
Searchable#
Names should be searchable. They should be easy to find in your codebase. If you’re looking for a variable, function, or class, you should be able to search for it by name and find it quickly.
Naming functions / methods#
Function names should be verbs or verb phrases that describe what the function does. They should be descriptive enough to give other developers (and your future self) a good idea of what the function does. A function should do one thing and one thing only and the name should reflect that. If it uses parameters they should be named in a way that makes it clear what they are used for.
Prefix suggestions:#
Action |
Prefixes |
Description |
Examples |
|---|---|---|---|
Retrieve data |
get, find, show, list |
Used when you need to retrieve data |
get_users, retrieve_users |
Insert data |
insert, add |
Used when you intend to add new information |
add_user, insert_user |
Update data |
update, change |
Used when you want to update information |
update_user, change_username |
Update or insert |
set |
Used when you wish to update or create a new record if it doesn’t exist |
set_days_off |
Retrieve from 3rd party |
fetch, retrieve |
Used when you wish to fetch data from a third-party resource, like over HTTP request for example |
fetch_users, retrieve_comments |
These are just suggestions and you should use what makes sense in your context.
Naming Classes:#
Class names should be nouns or noun phrases that describe what the class represents. They should be descriptive enough to give other developers (and your future self) a good idea of what the class does.
Keep it simple and descriptive
Use nouns or noun phrases
Use CamelCase (or your preferred language convention)
Use whole words and avoid acronyms and abbreviations
Avoiding Bad Names#
There are several types of bad names that you should avoid:
Single-letter names (e.g.
x,y,z)Abbreviations (e.g.
numinstead ofnumber) unless universally understood likeXMLorHTML. Abbreviations may be very company specific and not very intuitive for the person writing it but not for the person reading it.Names that are too long (e.g.
thisIsAVeryLongVariableNameThatSaysNothingSpecial) but there is a balance to be found between being too long and too short. The name should be descriptive and if that results in a somewhat longer name that is fine. Less is more, but don’t be cryptic.generic names (e.g.
data,value,temp)misleading names (e.g.
listwhen it is actually a dictionary ortotalwhen it is actually a subtotal). These names usually happen when the code is refactored and the name is not updated to reflect the new content.
Set<Address> addressList = person.getAddresses(); // This is a set of Address objects, not a list
Funny names, slang or the like. It may be funny the first time you see it but it will get old very quickly and it will make the code harder to read and understand. So don’t be a comedian in your code. Don’t do
shoutItOfTheRoofTops(), just go withsentNotifications().Names should not need comments to explain what they are for. If you need a comment to explain what a variable is for, then the name is not descriptive enough. The name should be self-explanatory. e.g.
int timeout = 10; // Timeout in seconds.This should be namedint timeoutInSeconds = 10;Names that are too similar to other names in the same scope. This can lead to confusion and bugs. e.g.
int total = 0;andint subtotal = 0;Try to be more specific.avoid encodings in names. e.g.
String strName = "Sarah";andint intAge = 25;". Just go with ``String name = "Sarah";andint age = 25;Vague naming like
DataHandlerorManagerorprocess. These names are too generic and don’t give any indication of what the class does. Be more specific. e.g.UserRepositoryorPaymentProcessororInvoiceGeneratororcalculateTotalPriceOfShoppingCard.Util classes. These classes are usually a dumping ground for methods that don’t fit anywhere else. This is a code smell and should be avoided. If you have a util class, it is a sign that your code is not well structured. Try to refactor the code so that the methods in the util class are moved to the classes where they belong. So if you want to create a class that will have something like Util or Utility in the name, think again.
Speak the Developers lingo. Use
Singletonand notOneInstanceand the like.Speak the Business lingo. Use
calculateBMIand notcalcXand the like. Note that an abbreviation is used here but it is universally (enough) understood. If you doubt if it is universally understood within the company, then don’t use it. UsecalculateBodyMassIndexinstead.Try to avoid negative naming. e.g.
isNotValid. It is better to useisValid. It is more positive and easier to understand.
Style Guides#
Every language has its own style guide. It is important to follow the style guide of the language you are using. Here are some examples:
PEP 8 (Python)
Google Java Style Guide (Java)
Examples#
public boolean process(Event e) {
if (e.d == 6 || e.d == 0) {
return false;
} else {
return (e.t.h >= 8 && e.t.h < 18);
}
}
public boolean isDuringWorkingHours(Event event) {
if (event.dayOfWeek == DayOfWeek.SATURDAY || event.dayOfWeek == DayOfWeek.SUNDAY) {
return false;
}
return (event.time.hour >= WORKING_DAY_START && event.time.hour < WORKING_DAY_END);
}
It might be more code but it is oh so much more readable and understandable. In the good example lots of pitfalls have been avoided. The function name is descriptive, the parameter name is descriptive, the variable names are descriptive and the constants are descriptive. Numbers with meaning have been given a name avoiding magic numbers. The code is now self-explanatory and does not need comments to explain what it does.