Sitemap

32 Golden Rules for Meaningful Naming in Code

9 min readDec 28, 2023

--

“Extracting the Naming Conventions from well renowned “Clean Code” book by Uncle Bob to Improve Your Programming”

Press enter or click to view image in full size

Rule 1: Intention-Revealing Names

Principle: Choose names that clearly indicate their purpose, functionality, and usage.

Wrong Approach ❌:

int d; // elapsed time in days

Here, ‘d’ does not clearly indicate what it measures or that it’s in days.

  • Right Approach ✅:
int elapsedTimeInDays;
int daysSinceCreation;

These names clearly represent what the variables are for.

Rule 2: Avoid Disinformation

Principle: Name things in a way that does not create misunderstanding and their context is clear.

Example: Confusing Code:

public List<int[]> getThem() {
List<int[]> list1 = new ArrayList<int[]>();
for (int[] x : theList)
if (x[0] == 4) list1.add(x);
return list1;
}

This code does not clarify what ‘theList’ contains or the significance of ‘4’.

Improved Code:

public List<int[]> getFlaggedCells() {
List<int[]> flaggedCells = new ArrayList<int[]>();
for (int[] cell : gameBoard)
if (cell[STATUS_VALUE] == FLAGGED) flaggedCells.add(cell);
return flaggedCells;
}

Here, ‘flaggedCells’ and ‘gameBoard’ make it clear what the code is doing.

Rule 3: Make the Code Explicit

Principle: Make the code so explicit that it doesn’t require extra context to understand.

Example:

public List<Cell> getFlaggedCells() {
List<Cell> flaggedCells = new ArrayList<Cell>();
for (Cell cell : gameBoard)
if (cell.isFlagged()) flaggedCells.add(cell);
return flaggedCells;
}

Here, the ‘Cell’ class and ‘isFlagged()’ method make the code much clearer.

Rule 4: Avoid Misleading Names

Principle: Avoid names that can create confusion or obscure the code’s actual meaning.

Example:
Wrong Approach ❌:

int hp; // Hypotenuse ke liye, lekin Unix platform ke naam se confuse ho sakta hai.

Here, ‘hp’ resembles Unix platforms’ names, which can be confusing.

Right Approach ✅:

int hypotenuseLength; // Ziyada clear hai.

Rule 5: Use the Correct Data Structure

Principle: If your variable does not represent a specific data structure (like List), do not use that type-specific name.

Example: Confusing Naming ❌:

Set<String> accountList; // Yeh List nahi hai, Set hai.

The name ‘accountList’ suggests it’s a List, while it’s actually a Set.

Better Naming ✅:

Set<String> accounts; // Yeh clear karta hai ke yeh ek collection hai, but specific type nahi batata.

Rule 6: Consistent Naming for Similar Concepts

Principle: Use similar and consistent naming for similar concepts.

Example: Inconsistent Naming ❌:

class ControllerForHandlingStrings {...}
class ControllerForStorageOfStrings {...}

These two classes perform similar tasks but have very different names.

Consistent Naming ✅:

class StringHandlingController {...}
class StringStorageController {...}

Here, both class names have a similar structure.

Rule 7: Avoid Arbitrary Distinctions

Principle: Do not make arbitrary changes in names without any meaningful difference.

Example: Wrong Approach ❌:

public static void copyChars(char a1[], char a2[]) {
// Copy characters from a1 to a2
}

There is no meaningful distinction between ‘a1’ and ‘a2’.

Right Approach ✅:

public static void copyChars(char source[], char destination[]) {
// Copy characters from source to destination
}

‘Source’ and ‘destination’ provide clear and meaningful distinctions.

Rule 8: Avoid Number Series and Noise Words

Principle: Do not use number series (like a1, a2) or noise words (like data, info) in names.

Example: Avoid Number Series:

class Employee1 { /* ... */ }
class Employee2 { /* ... */ }

This naming convention does not provide meaningful information.

Avoid Noise Words:

class ProductInfo { /* ... */ }
class ProductData { /* ... */ }

‘Info’ and ‘Data’ are noise words that don’t add much value.

Rule 9: Meaningful and Pronounceable Names

Principle: Choose names that are pronounceable and easily understandable.

Example:

class Customer { /* ... */ }
class CustomerRecord { /* ... */ }

Both ‘Customer’ and ‘CustomerRecord’ are pronounceable and their meaning is clear.

What to Do When Avoiding Number Series and Noise Words?

Use Specific Descriptions

  • Do: Use names that describe the unique and specific role of each variable or object.
  • Example: Wrong Approach ❌:
// Number series ka istemal
String name1, name2, name3;
  • Sahi Tarika ✅:
// Specific description
String customerName, supplierName, employeeName;

Here, each variable has a unique purpose.

Context-Based Naming

Do: Name according to the context that clearly defines their use case.

  • Example: Wrong Approach ❌:
// Noise word ka istemal
ProductData, UserInfo;
  • Sahi Tarika ✅:
// Context-based naming
ProductDetails, UserCredentials;

‘Details’ and ‘Credentials’ provide more specific context.

Role-Based Naming

  • Do: Name based on the role of the object or variable.
  • Example: Wrong Approach ❌:
// Confusing naming
String data;
  • Sahi Tarika ✅:
// Role-based naming
String userEmailAddress;

It’s clear that this variable stores the user’s email address.

Rule 10: Use Pronounceable Names

Principle: Choose names that can be easily spoken. This makes programming a social activity where you can easily talk about your code.

Example: Wrong Approach ❌:

// Mushkil pronounce karne wala naam
class DtaRcrd102 {
private Date genymdhms; // Generation timestamp
// Other variables...
}

‘genymdhms’ is hard to pronounce.

Sahi Tarika ✅:

// Asani se pronounce karne wale naam
class CustomerRecord {
private Date generationTimestamp;
// Other variables...
}

‘generationTimestamp’ is easy to pronounce and its meaning is clear.

Rule 11: Avoid Complex Abbreviations

Principle: Try to avoid complex and confusing abbreviations.

Example: Avoid Complex Abbreviations:

String psqzint; // Kya hai ye?

Abbreviations like ‘psqzint’ can cause confusion.

Use Full Words:

String accountStatus; // Clear hai

Using full words like ‘accountStatus’ makes names clear and pronounceable.

Rule 12: Use Search-Friendly Names

Principle: Choose names that are easy to search for in the code. Avoid sinle-letter names and numeric constants as they can be hard to locate.

Example:Wrong Approach ❌:

for (int i = 0; i < 7; i++) {
// Code...
}

Here, ‘7’ is a magic number that can be hard to search for.

Get Ateeb Taseer’s stories in your inbox

Join Medium for free to get updates from this writer.

Right Approach ✅:

int MAX_CLASSES_PER_STUDENT = 7;
for (int i = 0; i < MAX_CLASSES_PER_STUDENT; i++) {
// Code...
}

MAX_CLASSES_PER_STUDENT’ is search-friendly and its intent is clear.

Rule 13: Avoid Short Names Where Necessary

Principle: Use short names only for small and local scopes. Use longer, more descriptive names for variables with a widespread scope.

Avoid Short Names in Large Scope:

int e; // Kya hai ye? Kahan use hota hai?

Short names like ‘e’ can be confusing in a large scope.

Use Descriptive Names in Large Scope:

int elapsedTimeInDays;

Descriptive names like ‘elapsedTimeInDays’ are easy to search for and understand in a large scope.

Rule 14: Avoid Type Encodings:

Principle: Avoid encoding types (like int, String) in names.
Deep Analysis: Modern programming languages provide type information, and IDEs detect type errors at compile time. Therefore, encoding types in names is unnecessary.

Example: Wrong Approach ❌:

int iDays; // 'i' for integer
String strName; // 'str' for String
  • Right Approach ✅:
int days;
String name;

Rule 15: Avoid Hungarian Notation:

Principle: Avoid using Hungarian Notation, where a variable’s type is encoded in its name.

Example: Avoid Hungarian Notation:

int iCount; // 'i' for integer

Rule 16: Avoid Member Prefixes:

Principle: Avoid using prefixes like ‘m_’ for class member variables.
Deep Analysis: In small classes and functions, there’s no need for special prefixes for members. Modern IDEs distinctively highlight members.

Example: Wrong Approach ❌:

private String m_description; // 'm_' for member
  • Sahi Tarika ✅:
private String description;

Rule 17: Interfaces Naming Without Prefixes

Principle: Avoid using prefixes like ‘I’ in interface names.
Deep Analysis: Interface naming with prefixes like ‘I’ can be traditional but distracts in modern programming practices and provides unnecessary information.

Example: Wrong Approach ❌:

interface IShapeFactory { /* ... */ }

Sahi Tarika ✅:

interface ShapeFactory { /* ... */ }

Rule 18: Implementations Naming Principle

Principle: If encoding is necessary, do it in the implementation class, not the interface.
Deep Analysis: Users should not need to know they are dealing with an interface; they should just know the type of factory they are dealing with.

Example: Implementation Encoding:

class ShapeFactoryImp implements ShapeFactory { /* ... */ }

Here, ‘Imp’ in ‘ShapeFactoryImp’ is used to denote implementation.

Rule 19: Avoid Mental Mapping Principle:

Principle: Avoid names in code that force readers to mentally map them.
Deep Analysis: Code should be such that the used terms are directly related to either the problem domain or solution domain, so readers don’t need extra mental effort.

Example: Wrong Approach ❌:

int r; // days since last modification

Here, understanding the actual meaning of ‘r’ requires mental mapping.

Right Approach ✅:

int daysSinceLastModification;

In this example, ‘daysSinceLastModification’ is directly understandable without extra effort.

Rule 20: Use Noun or Noun Phrase Principle:

Principle: Name classes with a noun or noun phrase, like ‘Customer’, ‘Account’.
Avoid: Avoid vague or non-descriptive words like ‘Manager’, ‘Processor’, ‘Data’, ‘Info’.

Example: Right Approach ✅:

class Customer { /* ... */ }
class WikiPage { /* ... */ }
class AddressParser { /* ... */ }
  • Galat Tarika ❌:
class DataManager { /* ... */ }
class InfoProcessor { /* ... */ }

Rule 21: Use Verb or Verb Phrase Principle:

Principle: Name methods with a verb or verb phrase, like ‘postPayment’, ‘deletePage’.
Accessors, Mutators, Predicates:
Name them for their value and prefix with ‘get’, ‘set’, ‘is’.

Example: Right Approach ✅:

void postPayment() { /* ... */ }
boolean isPosted() { /* ... */ }
void setName(String name) { /* ... */ }
String getName() { /* ... */ }

Rule 22: Use Factory Methods for Overloaded Constructors:

Principle: For overloaded constructors, use static factory methods that describe the arguments.

Example: Factory Method Use ✅:

Complex fulcrumPoint = Complex.fromRealNumber(23.0);

Here, the ‘fromRealNumber’ method describes the constructor’s arguments.

Rule 23: Avoid Cleverness in Naming Principle:

Principle: Avoid cleverness or humor in naming.
Deep Analysis: If names are too clever or humorous, they will only be memorable to those who understand the humor. This can reduce code clarity.

Example: Avoid Clever Names ❌:

void HolyHandGrenade() { /* ... */ } // What does this do?

Use Clear Names ✅:

void deleteItems() { /* ... */ } // Clear and descriptive

Rule 24: Avoid Colloquialisms and Slang Principle:

Principle: Do not use colloquial language or slang.

Example: Avoid Slang ❌:

void whack() { /* ... */ } // Does it mean kill?
  • Use Proper Terms ✅:
void terminateProcess() { /* ... */ } // Clear and professional

Rule 25: Consistency in Naming for Similar Concepts Principle:

Principle: Use the same word for one abstract concept in different classes or methods.
Deep Analysis: Using different terms creates confusion. For example, do not use ‘fetch’, ‘retrieve’, and ‘get’ interchangeably in different places for the same meaning.

Example: Inconsistent Naming ❌:

class User {
void fetchDetails() { /* ... */ }
}
class Customer {
void retrieveData() { /* ... */ }
}

Consistent Naming ✅:

class User {
void getDetails() { /* ... */ }
}
class Customer {
void getDetails() { /* ... */ }
}

Rule 26: Avoid Multiple Terms for Similar Roles Principle:

Principle: Avoid using different terms for similar roles (like manager, controller, driver).

Example: Confusing Role Terms ❌:

DeviceManager, ProtocolController; // Kya farq hai inme?

Unified Role Terms ✅:

DeviceController, ProtocolController; // Dono 'Controller' term use karte hain.

Rule 27: Avoid Using the Same Word for Multiple Purposes :

Principle: Do not use the same word for two different purposes or ideas.
Deep Analysis: Using the same term for different contexts or meanings creates confusion in code.

Example: Avoid Puns ❌:

class Calculator {
int add(int a, int b) { /* ... */ }
}
class Collection {
void add(Object item) { /* ... */ } // Yaha 'add' ka meaning alag hai
}

Use Different Words for Different Contexts ✅:

class Collection {
void insert(Object item) { /* ... */ } // 'insert' ya 'append' ka use

Rule 28: Consistent Meaning for Same Terms Principle:

Principle: Only use the same term when its meaning and use case are consistent across different classes or methods.
Deep Analysis: If you use a term like ‘add’, ensure its use is semantically equivalent everywhere.

Example: Consistent Use of ‘add’ ✅:

class MathOperations {
int add(int a, int b) { /* ... */ }
}
class StringConcatenator {
String add(String a, String b) { /* ... */ } // Yaha bhi 'add' ka sense same hai

Rule 29: Use Solution Domain Names:

Principle: Use technical or computer science terms where necessary.
Deep Analysis: These terms are often easier for programmers to understand and often describe specific concepts or operations clearly.

Example: Right Approach ✅:

class QueueProcessor { /* ... */ }

Rule 30: Use Problem Domain Names:

Principle:If there is no appropriate term in the solution domain, use terms from the problem domain.
Deep Analysis: This allows programmers maintaining the code to easily seek help from domain experts.

Example: Right Approach ✅:

class InvoiceCalculator { /* ... */ }

Rule 31: Add Meaningful Context:

Principle: Provide meaningful context to names, especially when they are used alone.
Deep Analysis: Through context, the purpose and use case of a variable or method can be easily understood.

Example: Without Context ❌:

private void printStatistics(char candidate, int count) { /* ... */ }

With Context ✅:

public class GuessStatisticsMessage {
private void printStatistics(char candidate, int count) { /* ... */ }
}

Rule 32: Don’t Add Gratuitous Context:

Principle: Do not add more context to each class or variable than necessary.
Deep Analysis: Unnecessary context can make the code cluttered and less readable.

Example: Avoid Unnecessary Context ❌:

class GSDAccountAddress { /* ... */ } // GSD prefix not needed

Sahi Tarika ✅:

class AccountAddress { /* ... */ }

--

--