DEV Community

Cover image for A Guide to Clean Code: The Power of Good Names
Gervais Yao Amoah
Gervais Yao Amoah

Posted on

A Guide to Clean Code: The Power of Good Names

Introduction

In the world of software development, clean code is a goal that all developers should aspire to achieve. Writing clean code means producing software that is not only functional but also easily readable, maintainable, and understandable. One of the foundational elements of clean code is the use of good names. In this article, we'll explore why good names are vital for clean code, delve into naming conventions for various code elements, discuss the scope length rule, and conclude with a reminder of the importance of this fundamental coding practice.

Why Good Names Are Important

Before we dive into the specifics of naming conventions and guidelines, it's essential to understand why good names are indispensable in clean code. The primary reasons are:

  • Readability and Understanding: Good names make your code more readable and understandable, reducing the cognitive load on developers. When you encounter a well-named variable or function, you instantly grasp its purpose.

"Clean code is simple and direct. Clean code reads like well-written prose." - Grady Booch

  • Maintainability: Clean code is easy to maintain. When names are descriptive and intuitive, you spend less time deciphering code and more time making improvements if there is a need for any.

"You know you are working on clean code when each routine you read turns out to be pretty much what you expected." - Ward Cunningham

  • Collaboration: When working in a team, good names foster effective collaboration. Team members can quickly comprehend each other's code, leading to better productivity.

"Clean code always looks like it was written by someone who cares." - Michael Feathers

Armed with an understanding of why good names are a fundamental part of clean code, let's now delve into the practical guidelines that make your code readable, maintainable, and clean!

Principles of Naming in Clean Code

One of the fundamental tenets of writing clean code is adhering to meaningful and consistent naming conventions. The names you choose for your different code elements (variables, classes, and methods/functions) should act as a form of self-documentation, conveying the purpose and usage of each code element. The following principles should guide your naming choices:
1. Names Should Communicate Intent
The essence of a good name is its ability to communicate intent. When you name a variable or function, it should immediately tell you, and any future reader or contributor, what its role is within the code. An expressive name reduces the need for additional comments to explain the purpose, making your code more self-contained and comprehensible.
2. Names Should Be Descriptive
Descriptive names are the cornerstone of clean code. A variable, class, or method should be named in a way that provides enough context to understand its role without needing to delve into the implementation details. In essence, your names should eliminate the need for comments to clarify their purpose.
3. Avoid Disinformation
A good name should accurately reflect what it represents, and it should avoid any disinformation. Misleading or overly generic names can lead to confusion and errors. Names should not trick the reader into making incorrect assumptions about the code's behavior.
4. Names Must Be Pronounceable
Readable code is often code that can be spoken aloud. When naming elements, ensure that the names are pronounceable and sound natural. Avoid cryptic or abbreviated names like DEWC_A or methods with names that are difficult to say. This enhances the code's clarity and promotes better communication among team members.
5. Avoid Encoding in Names
Modern integrated development environments (IDEs) are powerful tools that can help developers understand the roles of code elements. Avoid adding prefixes like I for interfaces or m_ for member elements in your names. Instead, rely on your IDE's features for quick, accurate insights into your code's structure.

Naming Conventions: Variables, Classes, Functions/Methods

Naming conventions are the unspoken language of clean and maintainable code. They serve as guidelines for choosing meaningful names for variables, classes, and methods/functions. The way you name your code elements can profoundly impact the comprehensibility and maintainability of your software.
Let’s explore the principles and best practices of naming conventions that apply to variables, classes, methods, and functions.

Variables

Well-chosen variable names can significantly enhance the readability and maintainability of your code. Here are some fundamental principles and examples for naming variables effectively:
Nouns and Noun Phrases
Variables should typically be named using nouns or noun phrases that convey the purpose and content of the variable. These names should be clear and descriptive, making it easy for other developers (including your future self) to understand the variable's role in the code:

  • account - This variable name clearly indicates that it represents an account object. It's concise and meaningful.
  • customerList - In this case, the variable name is a noun phrase that describes the contents of the variable. It's more explicit than simply using "list."
  • totalAmount - When you see this variable name, it's evident that it holds the total amount of something in the context of the code.

Boolean Variables and Predicates
Boolean variables are often used in conditional statements, where their names should be structured as predicates. This naming convention makes the code more natural to read and understand:

  • isEmpty - When you encounter a variable named isEmpty, it's intuitive to use it in a conditional statement, such as if (isEmpty) {...}. This makes the code more human-readable.
  • isValid - The name isValid conveys that this variable determines the validity of something, which is especially useful in validation scenarios.

Enums and Adjectives
For enum types, which represent a set of constant values, it's a common convention to use adjectives in the enum values. This helps to add context and meaning to the code:

enum Status {
    PENDING,
    CLOSED,
    CANCELED
}
Enter fullscreen mode Exit fullscreen mode

Naming Conventions: Functions/Methods

In the world of clean code, functions and methods are the doers, the agents of action that bring your software to life. How you name these functions and methods can significantly impact the code's readability and understandability. To make your code expressive and coherent, here are some essential naming conventions for functions and methods:
1. Use Verbs
Function and method names should be action-oriented, using verbs to describe what they do. A verb in the name provides an instant clue about the operation being performed. For instance:

  • getPrice: The name clearly suggests that this function retrieves the price of something.
  • postPayment: The name signifies that this method is responsible for posting payments.

2. Predicate Names for Boolean Functions
When a function returns a boolean value, it's advisable to name it like a predicate, which makes it more natural to use in conditional statements. Consider this example:

  • user.isAuthorized(): The name is not just a label but reads like a question and enhances the code's readability when used in conditions. For instance, you can write if (user.isAuthorized()) { /* ... */ }

3. Use "get" for Accessors
Accessors, which are methods used to retrieve the value of an attribute, should follow a consistent naming convention. Using the prefix "get" before the attribute's name helps identify their role. For example:

  • getName: This method gets the name of an entity.
  • getAccountBalance: The name suggests that this method retrieves an account's balance.

Classes

Classes are the building blocks of object-oriented programming, defining the blueprints for objects and their behaviors. Naming classes appropriately is paramount to ensure that your code is well-organized and easy to understand. Let's explore some fundamental principles and best practices for naming classes effectively:
1. Noun Usage
In the world of clean code, class names should be nouns. A class represents a real-world entity or concept, and its name should reflect this. When another developer or team member encounters the class, its name should immediately convey what it represents. For instance:

  • Customer: This class represents a customer entity.
  • Product: A class with this name is assumed to define product-related attributes and behaviors.

2. Singular and Concise
Class names should be singular, representing a single entity or concept. Keep class names concise and focused on their core responsibility. Avoid making class names overly complex or multi-faceted.

3. Avoid Acronyms and Abbreviations
While shortening names might seem like a space-saving idea, it often sacrifices clarity. Avoid using excessive acronyms and abbreviations in class names. The goal is to make your code easily understandable to all team members, even those who may not be familiar with industry-specific terms or abbreviations.

By following these naming conventions, you can make your code more self-explanatory and user-friendly. We can go from

class AB {
  private double b;
 // Initialization
  AB(double init) {
    b = init;
  }
 // Get the account’s balance
  double balance() {
    return b;
  }
 // Deposit amount
  void deposit(double a) {
    if (a > 0) {
    b += a;
    }
  }
 // Withdraw amount
  void withdraw(double a) {
    if (a > 0 && a <= b) {
    b -= a;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

to

class AccountBalance {
  private double balance;

  AccountBalance(double initialBalance) {
    balance = initialBalance;
  }

  double getBalance() {
    return balance;
  }

  void deposit(double amount) {
    if (amount > 0) {
    balance += amount;
    }
  }

  void withdraw(double amount) {
    if (amount > 0 && amount <= balance) {
    balance -= amount;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

When you or your colleagues revisit the code in the future, meaningful names can save time and reduce cognitive load, leading to a more efficient and enjoyable coding experience. This clarity helps your code speak for itself.

Scope Length Rule

The scope length rule is a crucial concept in clean code that emphasizes the relationship between the scope of a code element and the length of its name. It guides us on how to choose names based on the visibility and duration of a code element. Let's explore how the scope length rule applies to variables, functions, and classes.

Variables: Short Scope, Short Names

In scenarios where a variable's scope is limited to a small portion of your code and its usage is immediately evident, concise names are acceptable. Consider a function with a short parameter name used immediately within its block:

void calculateTotalPrice(double p) {
  double tax = p * 0.08;
  double total = p + tax;
  // ...
}
Enter fullscreen mode Exit fullscreen mode

In this example, the variable p represents the price, and its short name is appropriate because it is used within a short scope, and its purpose is evident from the context.

Functions and Classes: Long Scope, Short Names

Conversely, when it comes to functions and classes with longer lifespans and wider scopes, concise and meaningful names become more important. Public functions, for instance, are used in various parts of your codebase, so a short, descriptive name is beneficial. On the other hand, private classes can afford longer, more descriptive names.
Consider these examples:

public double calculateTotal(double price) {
  // Public function with a short, concise name
  // ...
}
Enter fullscreen mode Exit fullscreen mode

and

private class CustomerInformationManager {
  // Private class with a longer, descriptive name
  // ...
}
Enter fullscreen mode Exit fullscreen mode

In the first example, the public function has a concise name, which is suitable for a wide scope. In the second example, the private class has a more descriptive name to clarify its purpose, which is acceptable within its limited scope.
The scope length rule reminds us to strike a balance between brevity and descriptiveness based on the visibility and longevity of code elements. This balance enhances the readability and maintainability of your code, making it more accessible to both current and future developers.

Conclusion

Clean code is not just a choice but a necessity in software development. It's about writing code that's not only functional but also comprehensible to humans, as Martin Fowler wisely pointed out: "Any fool can write code that a computer can understand. Good programmers write code that humans can understand."
Throughout this article, we've explored the power of good names and the scope length rule. These principles, grounded in clean code practices, enhance clarity, readability, and maintainability.
In your coding journey, prioritize clarity, choose meaningful names, and adhere to clean code conventions. Your code will not only work well but also be easily understood and maintained by your fellow developers.
Be a good programmer—write code that humans can understand.👊😎

Top comments (0)