---
description: >-
  Names are everywhere in software. We name our variables, our functions, our
  arguments, classes,  packages, source files, directories, ... What follows are
  some simple rules for creating good names.
---

# Meaningful Names

## Use intention-revealing names

The name of a variable, function, or class, should answer all the big questions. It should tell you why it exists, what it does, and how it is used. If a name requires a comment, then the name does not reveal its intent.

What does the list represent?

{% hint style="danger" %}
```java
List<User> theList; // The list of users
```
{% endhint %}

{% hint style="success" %}
```java
List<User> users;
```
{% endhint %}

## Avoid disinformation

Programmers must avoid leaving false clues that obscure the meaning of code. We should avoid words whose entrenched meanings vary from our intended meaning.

Of what type is the account list? String? Array of strings? Array of objects?

{% hint style="danger" %}
accountList
{% endhint %}

{% hint style="success" %}
accounts
{% endhint %}

The lower-case `L` or uppercase `O` ? or they look almost entirely like the constants one and zero, respectively.

{% hint style="danger" %}


```java
int a = l;
if ( O == l ) {    
  a = O1;
} else {    
  l = 01;
}
```
{% endhint %}

## Avoid similar shapes

How long does it take to spot the subtle difference?

{% hint style="danger" %}
class ControllerForEfficientHandlingOfStrings\
class ControllerForEfficientStorageOfStrings
{% endhint %}

## Make meaningful distinctions

How do these different names convey different meanings?

{% hint style="danger" %}
class Product\
class ProductInfo\
class ProductData
{% endhint %}

## Use pronounceable names

How can you discuss it without sounding like an idiot?

{% hint style="danger" %}
class CstmrRcrd
{% endhint %}

{% hint style="success" %}
class CustomerRecord
{% endhint %}

## Use Searchable Names

Single-letter names and numeric constants have a particular problem in that they are not easy to locate across a body of text.

What is the number `34` , `4` or `5`?

{% hint style="danger" %}


```java
for (int j = 0; j < 34; j++) {    
  s += (t[j] * 4) / 5;
}
```
{% endhint %}

{% hint style="success" %}


```java
private static final int REAL_DAYS_PER_IDEAL_DAY = 4;
private static final int WORK_DAYS_PER_WEEK = 5;
private static final int NUMBER_OF_TASKS = 34;

public static int sumOfRealTaskWeeks(int[] taskEstimates) {    
  int sum = 0;    
  for (int j = 0; j < NUMBER_OF_TASKS; j++) {        
    int realTaskDays = taskEstimates[j] * REAL_DAYS_PER_IDEAL_DAY;        
    int realTaskWeeks = (realTaskDays / WORK_DAYS_PER_WEEK);        
    sum += realTaskWeeks;    
  }    
  return sum;
}
```
{% endhint %}

## Avoid Encodings

It hardly seems reasonable to require each new employee to learn yet another encoding “language” in addition to learning the (usually considerable) body of code that they’ll be working in.

{% hint style="danger" %}
void tạoNgườiDùng()
{% endhint %}

{% hint style="success" %}
void createUser()
{% endhint %}

## Member Prefixes

Don’t need to prefix member variables with m\_ anymore. Your classes and functions should be small enough that you don’t need them.

{% hint style="danger" %}


```java
class Part {    
  private String m_dsc; // The textual description
      
  void setName(String name) {        
    m_dsc = name;    
  }
}
```
{% endhint %}

{% hint style="success" %}


```java
class Part {    
  private String description;    
  
  void setDescription(String description) {        
    this.description = description;    
  }
}
```
{% endhint %}

## Interfaces and Implementations

{% hint style="danger" %}
interface IShapeFactory {}

class ShapeFactory implements IShapeFactory {}
{% endhint %}

{% hint style="success" %}
interface ShapeFactory {}

class ShapeFactorImpl implements ShapeFactory {}
{% endhint %}

or

{% hint style="success" %}
interface ShapeFactory {}

class CShapeFactor implements ShapeFactory {}
{% endhint %}

{% hint style="info" %}
I don’t want my users knowing that I’m handing them an interface. I just want them to know that it’s a ShapeFactory. So if I must encode either the interface or the implementation, I choose the implementation.
{% endhint %}

## Avoid Mental Mapping

This is a problem with single-letter variable names. Certainly, a loop counter may be named `i` or `j` or `k` (though never `l`!) if its scope is very small and no other names can conflict with it. This is because those single-letter names for loop counters are traditional. However, in most other contexts a single-letter name is a poor choice.

{% hint style="danger" %}


```java
List<Student> l = getStudents();
for (Student i : l) {    
  i.doSomething();
}
```
{% endhint %}

{% hint style="success" %}
```java
List<Student> students = getStudents();
for (Student student : students) {    
  student.doSomething();
}
```
{% endhint %}



## **Class Names** <a href="#ch2lev1sec9" id="ch2lev1sec9"></a>

Classes and objects should have noun or noun phrase names.

{% hint style="success" %}
class Customer\
class WikiPage\
class Account
{% endhint %}

## Avoid words (in the name of a class)

{% hint style="danger" %}
Manager\
Processor\
Data\
Info

Core

Helper

Common

Utilities
{% endhint %}

{% hint style="success" %}
JwtHelper



MediaType {

&#x20; public static final String APPLICATION\_PDF\_VALUE = "application/pdf";

&#x20; public static final String IMAGE\_JPEG\_VALUE = "image/jpeg";

&#x20; public static final String APPLICATION\_JSON\_VALUE = "application/json";

}

HttpMethod {GET, POST, PUT}

HttpStatus {CREATED, ACCEPTED, NO\_CONTENT}



StringUtils

RandomUtils

TagUtils
{% endhint %}

{% hint style="info" %}
The class name means the class does more than one thing. It doesn't say anything specific
{% endhint %}

## **Method Names** <a href="#ch2lev1sec10" id="ch2lev1sec10"></a>

Methods should have verb or verb phrase names like `postPayment`, `deletePage`, or `save`. Accessors, mutators, and predicates should be named for their value and prefixed with `get`, `set`, and `is` according to the **J**avaBean standard.

{% hint style="success" %}
void postPayment()\
void deletePage()\
void save()
{% endhint %}

## Prefer methods to constructors overloaded

When constructors are overloaded, use static factory methods or builders with names that describe the arguments.&#x20;

{% hint style="danger" %}
```java
class User {    
  private String firstname;    
  private String lastName;    
  private int age;    
  
  public User() {
  }    
  
  public User(String firstname) {        
    this.firstname = firstname;    
  }    
  
  public User(String firstname, String lastName) {        
    this.firstname = firstname;        
    this.lastName = lastName;    
  }    
  
  public User(String firstname, String lastName, int age) {        
    this.firstname = firstname;        
    this.lastName = lastName;        
    this.age = age;    
  }
}

User user1 = new User("GP");
User user2 = new User("GP", "Coder");
User user3 = new User("GP", "Coder", 32);
```


{% endhint %}

{% hint style="success" %}


```java
class User {    
  private String firstname;    
  private String lastName;    
  private int age;    
  
  public static class UserBuilder {        
    private User user;                
    
    public UserBuilder withFirstName(String firstName) {            
      user.firstname = firstName;            
      return this;        
    }        
    
    public UserBuilder withLastName(String lastName) {            
      user.lastName = lastName;            
      return this;        
    }       
    
    public UserBuilder withAge(int age) {            
      user.age = age;            
      return this;        
    }                
    
    public User build() {            
      return user;        
    }    
  }
}

User user1 = new User.UserBuilder()
                .withFirstName("GP")
                .withLastName("Coder")
                .withAge(32)
                .build();
```
{% endhint %}

## Adjust the length of a name to the size of its scope

Is it obvious outside the class body that WD is an acronym for work days per week?

{% hint style="danger" %}
public static final int WD
{% endhint %}

{% hint style="success" %}
public static final int WORK\_DAYS\_PER\_WEEK
{% endhint %}

{% hint style="info" %}
If a variable or constant might be seen or used in multiple places in a body of code, it is imperative to give it a search-friendly and meaningful name.
{% endhint %}

## Avoid using the same name for different purposes

What does add mean? Concate strings? Insert a record in a table? Append a value to the end of an array?

{% hint style="danger" %}
function add(value)
{% endhint %}

{% hint style="success" %}
function concate(value)\
function insert(value)\
function append(value)
{% endhint %}

## Use Solution Domain Names

Remember that the people who read your code will be programmers. So go ahead and use computer science (CS) terms, algorithm names, pattern names, math terms, and so forth.

The name `AccountVisitor` means a great deal to a programmer who is familiar with the Visitor Pattern.

## Use problem domain names

What does the term "document" mean in the archives domain? Are photos considered documents?

{% hint style="danger" %}
document
{% endhint %}

{% hint style="success" %}
record
{% endhint %}

## Add Meaningful Context

There are a few names which are meaningful in and of themselves—most are not. Instead, you need to place names in context for your reader by enclosing them in well-named classes, functions, or namespaces. When all else fails, then prefixing the name may be necessary as a last resort.

What does a comma `,` mean? How to change all of them for a specific context?

{% hint style="danger" %}


```java
public static final String COMMA = ",";
String extractCountry(String address) {    
  final int COUNTRY_INDEX = 0;
  return address.split(COMMA)[COUNTRY_INDEX];
}

void parseCsv(String csvLine) {    
  String[] parts = csvLine.split(COMMA);
}
```
{% endhint %}

{% hint style="success" %}


```java
public static final String ADDRESS_SEPARATOR = ","
String extractCountry(String address) {  
  final int COUNTRY_INDEX = 0;  
  return address.split(ADDRESS_SEPARATOR)[COUNTRY_INDEX];
}

public static final String CSV_SEPARATOR = ",";
void parseCsv(String csvLine) {    
  String[] parts = csvLine.split(CSV_SEPARATOR);
}
```
{% endhint %}

## Don’t Add Gratuitous Context

{% hint style="danger" %}
package com.gpcoder.entity.obnk;

class ObnkConsentEntity {};

class ObnkAdrEntity {};
{% endhint %}

{% hint style="success" %}
package com.gpcoder.entity.obnk;

class ConsentEntity {};

class AdrEntity {};
{% endhint %}

{% hint style="info" %}
Shorter names are generally better than longer ones, so long as they are clear. Add no more context to a name than is necessary.
{% endhint %}

## Add context by using prefixes

What does the state represent? Condition or country?

{% hint style="danger" %}
state
{% endhint %}

{% hint style="success" %}
addressState
{% endhint %}

{% hint style="info" %}
The names `accountAddress` and `customerAddress` are fine names for instances of the class `Address`, but could be poor names for classes.

If you need to differentiate between MAC addresses, port addresses, and Web addresses, consider PostalAddress, MAC, and URI.
{% endhint %}



