A complete guide for choosing the right names

devsmanship
Javarevisited
Published in
11 min readMay 17, 2021

In this article, we will talk about how to pick the right names for classes, methods, and variables. We will see how a bad name can lead to code that is hard to understand and how to fix that. Let’s begin.

This article is part of a clean code in-depth course called “Software Practices And Writing Clean Code” you can check it out. It’s currently available at an 87% off discount.

General rules

We certainly don’t want names like:

  • var number = 5;
  • var a = 42;
  • var abc = “John”;
  • etc

These names are meaningless, they don’t bring us any value. Look at this code:

actvUsr(String text) {
User usr = rpstry.find(text);
usr.actv();
}

We have a method called actvUsr that expects String text as a parameter. Then we are calling rpstry.find and we are finding a user by “text”. Then we are calling usr.actv() method.

Pheww. What a mess. The names are even hard to pronounce. If you see this code for the first time, I bet it will be hard for you to understand. Even if you are not seeing this for the first time it will be hard. It’s awful. And this snippet is only 2 lines of code. Imagine it was 20.

If I want to understand what this method does I will need to go and see what “rpstry” is. Then I need to go in the find method and see what is the parameter called “text”. Then I need to go to actv() method and see what it does. There is so much work I need to do so I can understand 2 lines of code, that’s madness. Okay, you won’t probably see that kind of a mess, but I wanted to make my point. If your names are crappy, your code will be hard to read.

Let’s refactor it.

“actv” means activate, so just call it that. You don’t need to make abbreviations like that, frequently there are not understandable. This abbreviation style comes from the old days where we had very small memories(in the size of kilobytes), so every bit mattered. But now it’s not that time, memory is cheap and developers’ time is expensive. So you need to make it easier as possible for developers to understand your code.

Next is the other meaningless abbreviation “usr”. This doesn’t even cut the word much, it just makes it hard to read. So we will rename it to user.

text is the id for the user.

rpstry is repository. You can rename it a repository or repo, both are fine and understandable.

Find method is named okay, but we still don’t know by what we are finding. In this case, it is by id. So let’s rename it to suit that — findById.

And this is the final result:

activateUser(String id) {
User user = repo.findById(id)
user.activate();
}

That’s way better.

Okay, let’s say that I’m seeing this method for the first time. I will need less than 5 seconds to understand exactly what it does without going to the inner methods. Of course, if I want to know exactly how the user activation works I need to go to the activate method, but that’s something normal. We have the abstract code on the top and if we want to see details we go into inner methods.

You also need to pay attention to the context. See the following example:

class UserService {
public User getUserById(String id) {
// TODO: implement
}
}

We have a class UserService. Within we have getUserById method. Let’s see how we are going to call this method outside:

UserService userService = new UserService();
userService.getUserById("USER_ID");

Notice the calling line: userService.getUserById. It’s a little bit redundant, right? If we are calling the userService we know the context and we know that we are going to work with users. So, it’s perfectly fine to call the method just getById:

class UserService {
public User getById(String id) {
// getting the user
}
}
UserService userService = new UserService();
userService.getById("USER_ID");

That’s better. It’s not that much, but reduces the redundancy and makes the code cleaner.

How to write better class names

The class name should be a noun. Examples for that are:

  • Bike
  • Person
  • Scheduler
  • UserService

…and of course:

  • HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(this one is from a real project, you can google it)

You don’t want to make the class name that long, but don’t worry if your class name is big. Historically, class, variable, and method names were very short to save memory. But now we don’t need to do that. We understood that the maintenance is more valuable than the extra bytes that the longer name is going to take. Which translates to — better to have more descriptive names instead of saving memory. Nowadays we have plenty of memory and also our compilers are optimizing the names by replacing them with smaller ones when compiling. So don’t worry about that.

Avoid noise words like:

  • Processor
  • Data
  • Info
  • Utils
  • etc.

If you use them, it means that you don’t know how to call the class. Make sure that every word you put in brights value, new information, and helps describe the class.

The Scope Rule

Scope means — how many times and how far you are using a function, variable, or class. For example, if we have a private method that is used only one time — this is a small scope. If you have a private method that is used 3 times — this is a bigger scope. If we have a public method that is used 10 times in different classes we have a big scope. And so on. You get the idea.

The rule is as follows: the name of a class should be long when its scope is small and should be short when its scope is large.

(Reread the above if you don’t fully understand it. It might be a bit overwhelming)

The reason for that is when we have a small scope we can afford to write a more descriptive name because it’s used less and you don’t have to remember and drag around a huge name. When the scope is big. we want to keep it clean, so we need to keep the name smaller and cleaner.

I don’t expect you to think of the perfect name for a class within 2 minutes. Thinking of the correct name is hard. You can always change it later if you feel like doing so. When you are working with a code, even if it’s not yours, and you think of a better name, don’t hesitate to change it.

How to write better method names

Method names should be verbs. Examples for method names are:

  • getName
  • fetchId
  • speedUp
  • break
  • вземиКолаПоМарка

A quick tip: names should be only in English. Even if you are writing an app for a specific non-speaking English country. Currently, almost everyone knows English and if you are writing an app and the names are in, let’s say, Italian — if you want to outsource in other countries that will be impossible.

If a method name returns a boolean — make it predicate. This is because it’s likely to be used in an if statement and it should read well. For example:

class Account {
public boolean isEmpty() {
// TODO: implement
}
}

We have a class Account with isEmpty method in it. When we use this method in an if statement it will look like this:

Account account = new Account();
if(accout.isEmpty()) {
throw new Exception();
}

Note how easy is to read the if statement:

If account is empty then throw new exception.

There is a famous quote from Grady Booch: “Clean code is simple and direct. Clean code reads like well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.”

In this case, you can see that this code reads like well-written prose. I know that’s a simple example, but it’s something to aim for.

The scope rule applies here as well: the name should be long when its scope is small and should be short when its scope is large. Again, when we have a small scope, we can write a more descriptive name because it’s used less and you don’t have to remember and drag around a very big name. When the scope is big we want to keep it clean, so we need to keep the name smaller and cleaner.

For example, the class File(this is from the standard Java library):

File has an open method. Imagine instead of open it was called openFileAndThrowIfNotFound:

Imagine calling this class all over your code. That’s awful. Because the scope of the open function in the File class is big, the name is small. It’s way simpler to just call File.open().

Remember if you need to go inside a class or a method to figure out what it does — it’s not named properly.

How to write better variable names

Often variable names hold objects, something that exists. That’s why they should be nouns. Examples for variable names are:

  • user
  • processor
  • isExecuted
  • commentList
  • etc.

boolean variables should be predicates. For example:

  • isPlayable
  • shouldBeDeleted
  • areLocked
  • etc.

They should read well when put in if statement. See the following example:

if(isEmpty) {
throw new Exception();
}

Have you heard of “Hungarian notations”? This is a naming convention of the 80s. This notation describes encoding prefixes for different variable types. For example:

  • b for boolean — bBusy
  • ch for char — chInitial
  • c for count of items — cApples
  • f for float — fBusy
  • fn for function name — fnSave
  • etc.

Don’t use encodings. Please. Nowadays we don’t need that. Our IDEs are perfectly capable of showing us what is the type of a variable. This is waste of time, makes the code harder to read and it’s useless.

Don’t use comments to replace good naming.

For example:

public void example() {
int m; // this is the month of the year
// implementation
// implementation
// implementation
// implementation
// implementation
// implementation
// implementation
// implementation
// implementation
[DO SOMETHING WITH m]
}

Look at the second line. This is not okay. Yep, if you are reading this line you will know what m is, because of the comment, but if you are looking at its usage at line 12 — you won’t know what it is. You should search for the declaration of m and see what it is. This is a simple example, but imagine having 5 variables like that in a method. This will make the code a lot harder to read. That’s why you should make the variable more descriptive:

public void example() {
int month;
// implementation
// implementation
// implementation
// implementation
// implementation
// implementation
// implementation
// implementation
// implementation
[DO SOMETHING WITH month]
}

In this case, we removed the comment and included the information from it into the variable name. That way we don’t have to support additional comments and our code is self-documented. Of course, comments are sometimes useful, but this is another topic.

And of course, we have a scope rule here as well:

The rule here is the opposite from methods and classes: variable name should be short when its scope is small and should be long and descriptive when the scope is large.

The rule here is different because the scope of a variable is, typically, small(within a method). If the scope is small there is no need for a descriptive name since it’s very easy to see what’s the variable means. Let’s see an example:

public FreelancePaidEmployer save() { 
FreelancePaidEmployer freelancePaidEmployer = getEmployer();
save(freelancePaidEmployer);
return freelancePaidEmployer;
}

In this case, the freelancePaidEmployer variable has a very small scope. And we don’t need a descriptive name for the variable since it’s very easy to see what the variable means and from where it comes. Let refactor it:

public FreelancePaidEmployer save() {
FreelancePaidEmployer e = getEmployer();
save(e);
return e;
}

That’s better. You can make them a little bit more descriptive if you what, but I don’t see the need for that.

On the opposite, if we have a big scope for a variable, which means that we will have a bigger method we need to make the variable more descriptive. The reason for that is that we don’t want to keep scrolling up and down all the time so we can recall what the variable does.

Let’s see a more abstract example:

public void method() {
int m; // this is the month of the year
[USING THE VARIABLE HERE]
// business logic
// business logic
// business logic
// business logic
[USING THE VARIABLE HERE]
// business logic
// business logic
// business logic
[USING THE VARIABLE HERE]
[USING THE VARIABLE HERE]
// business logic
// business logic
// business logic
// business logic
// business logic
[USING THE VARIABLE HERE]
}

We declare the variable at the top, then we have business logic and from time to time we are using the variable. If the name of it is not descriptive we will need to frequently scroll to the top of the method to see exactly what this variable is. That’s why when the scope is big we want to have a longer and more descriptive name. Let’s rename the variable:

public void method() {
int month;
[USING THE VARIABLE HERE]
// business logic
// business logic
// business logic
// business logic
[USING THE VARIABLE HERE]
// business logic
// business logic
// business logic
[USING THE VARIABLE HERE]
[USING THE VARIABLE HERE]
// business logic
// business logic
// business logic
// business logic
// business logic
[USING THE VARIABLE HERE]
}

That’s better. Now when we are using the variable we will know exactly what it is without needing to go to the variable declaration.

Another tip is to declare variables as closes as possible to the uses of the variable. Don’t do this:

public void method() {
var variable = new Variable();
// business logic
// business logic
// business logic
// business logic
// business logic
[USING THE VARIABLE HERE]
}

Here we are making the scope of the variable bigger and that’s not needed. Since the scope is bigger we need to write the longer and descriptive name. And it doesn’t make sense to do it. You can just declare the variable just above the usage of it. As so:

public void method() {
// business logic
// business logic
// business logic
// business logic
var variable = new Variable();
[USING THE VARIABLE HERE]
}

When you do that you are making the scope smaller and it’s perfectly fine to call the variable with a simpler name. Note that in JavaScript it’s a practice to declare variables at the top, but this is an exception to this rule, so keep this in mind.

Before You Go — Our Amazing Clean Code Course

If you loved this article, you will love our course:

  • 39 lectures
  • 1.5 hours of content
  • Working on a real-life project that will test your knowledge
  • 27 downloadable resources
  • 30-Day Money-Back Guarantee

You can sign up for the course here — Software Practices And Writing Clean Code

--

--