Meaningful Names
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.
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?
List<User> theList; // The list of users
List<User> users;
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?
accountList
accounts
The lower-case
L
or uppercase O
? or they look almost entirely like the constants one and zero, respectively.
int a = l;
if ( O == l ) {
a = O1;
} else {
l = 01;
}
How long does it take to spot the subtle difference?
class ControllerForEfficientHandlingOfStrings
class ControllerForEfficientStorageOfStrings
How do these different names convey different meanings?
class Product
class ProductInfo
class ProductData
How can you discuss it without sounding like an idiot?
class CstmrRcrd
class CustomerRecord
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
?
for (int j = 0; j < 34; j++) {
s += (t[j] * 4) / 5;
}
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;
}
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.
void tạoNgườiDùng()
void createUser()
Don’t need to prefix member variables with m_ anymore. Your classes and functions should be small enough that you don’t need them.
class Part {
private String m_dsc; // The textual description
void setName(String name) {
m_dsc = name;
}
}
class Part {
private String description;
void setDescription(String description) {
this.description = description;
}
}
interface IShapeFactory {}
class ShapeFactory implements IShapeFactory {}
interface ShapeFactory {}
class ShapeFactorImpl implements ShapeFactory {}
or
interface ShapeFactory {}
class CShapeFactor implements ShapeFactory {}
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.
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.
List<Student> l = getStudents();
for (Student i : l) {
i.doSomething();
}
List<Student> students = getStudents();
for (Student student : students) {
student.doSomething();
}
Classes and objects should have noun or noun phrase names.
class Customer
class WikiPage
class Account
Manager
Processor
Data
Info
Core
Helper
Common
Utilities
JwtHelper
MediaType {
public static final String APPLICATION_PDF_VALUE = "application/pdf";
public static final String IMAGE_JPEG_VALUE = "image/jpeg";
public static final String APPLICATION_JSON_VALUE = "application/json";
}
HttpMethod {GET, POST, PUT}
HttpStatus {CREATED, ACCEPTED, NO_CONTENT}
StringUtils
RandomUtils
TagUtils
The class name means the class does more than one thing. It doesn't say anything specific
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 JavaBean standard.void postPayment()
void deletePage()
void save()
When constructors are overloaded, use static factory methods or builders with names that describe the arguments.
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);
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();
Is it obvious outside the class body that WD is an acronym for work days per week?
public static final int WD
public static final int WORK_DAYS_PER_WEEK
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.
What does add mean? Concate strings? Insert a record in a table? Append a value to the end of an array?
function add(value)
function concate(value)
function insert(value)
function append(value)
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.What does the term "document" mean in the archives domain? Are photos considered documents?
document
record
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?
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);
}
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);
}
package com.gpcoder.entity.obnk;
class ObnkConsentEntity {};
class ObnkAdrEntity {};
package com.gpcoder.entity.obnk;
class ConsentEntity {};
class AdrEntity {};
Shorter names are generally better than longer ones, so long as they are clear. Add no more context to a name than is necessary.
What does the state represent? Condition or country?
state
addressState
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.
Last modified 8mo ago