Skip to main content

Command Palette

Search for a command to run...

Clean Code - Part-1: Naming

Updated
9 min read
Clean Code - Part-1: Naming
S

Greetings! 🚀 I'm a dynamic Fullstack Software Engineer, driving advancements in technology to empower organizations globally. Proficient in a diverse tech stack, I contribute to the architecture and development of high-performance applications. Beyond coding, I thrive on creating empowering and collaborative environments, championing technological innovation, and fostering connections to push the boundaries of excellence. As a Gamer🎮, and a Footballer⚽️, I bring passion to both my professional and personal pursuits. A Wanderlust🛣️ enthusiast and Orophile⛰️, I thrive on exploring diverse landscapes. A Melomane🎵 and avid TV😍 enthusiast, I find joy in the finer aspects of life. Also, a proud enthusiast of Tea☕️ who appreciates bike rides, beaches, and mountains alike. Always eager to connect with like-minded professionals and individuals who share a zest for technology, innovation, and life's adventures. Let's push boundaries together! 🌐

Assigning Names to Variables, Functions, Classes & More


Names should be meaningful

const us = new MainEntity();
us.process();
if (login) {
    // Some code related to login
}

Consider the above example:-

  • Lack of clarity on the overall purpose or functionality of the code snippet.

  • The purpose and role of MainEntity are undefined, making it unclear what it represents.

  • The process method lacks description, leaving ambiguity about its functionality.

  • The condition check for login is unclear, with no indication of its type or purpose.

  • Ambiguity persists regarding whether login is a boolean flag, variable, or function.

  • The absence of context, descriptive naming, and documentation makes the code difficult to understand and maintain.


class UserSession {
    constructor() {
        // Initialize user session
    }

    authenticate(credentials) {
        // Authenticate user with provided credentials
        // Return true if authentication successful, false otherwise
    }

    isLoggedIn() {
        // Check if user is currently logged in
        // Return true if logged in, false otherwise
    }
}

class UserManager {
    constructor() {
        this.userSession = new UserSession();
    }

    authenticateUser(credentials) {
        const isAuthenticated = this.userSession.authenticate(credentials);
        if (isAuthenticated) {
            // Proceed with authenticated user logic
        } else {
            // Handle authentication failure
        }
    }

    isLoggedIn() {
        return this.userSession.isLoggedIn();
    }
}
  • The UserManager class effectively manages user-related functionality, including authentication and login status checks.

  • Descriptive naming of classes and methods, such as authenticateUser and isLoggedIn, enhances readability and understanding of their purpose.

  • Each method within the UserManager class has a clearly defined role, reducing ambiguity and improving maintainability.

  • The isLoggedIn method returns a boolean value, providing clarity on the user's login status.

  • Well-structured code and meaningful names offer context and understanding of the implemented functionality.

  • While not explicitly shown, adding comments or documentation would further enhance comprehension and maintainability.

Meaningful names in code are paramount as they significantly enhance the readability, maintainability, and scalability of software projects. Clear and descriptive names for variables, functions, and classes facilitate easier comprehension for developers, reducing the cognitive load and enabling efficient collaboration. Additionally, meaningful names serve as a form of self-documentation, conveying the purpose and functionality of code elements without the need for extensive comments or documentation. This aids in debugging and troubleshooting processes, as well as in the ongoing maintenance and evolution of the codebase. Ultimately, investing time and effort into choosing meaningful names pays dividends in terms of code quality, developer productivity, and the long-term sustainability of software projects.


Name Casing

Name casing is paramount in clean code as it enhances readability, maintainability, and collaboration among developers. By adhering to consistent naming conventions throughout the code base, developers can quickly understand the purpose and type of each identifier, facilitating easier navigation and modification of code. Clear and intuitive naming conventions also promote effective collaboration, as standardized naming styles reduce misunderstandings and promote cohesive coding standards. Additionally, name casing contributes to code consistency, ensuring that all elements of the code base follow the same conventions, thus enhancing overall code quality.

There are 4 major types of name casing used:-

  1. Snake Case:-

    Usages - Typically used in Python for variables, functions, and methods.

    Examples -

     user_name = "John Doe"
     calculate_discount = lambda price, percentage: price * percentage / 100
    
  2. Camel Case:-

    Usages - Commonly used in Java and JavaScript for variables, functions, and methods.

    Examples -

     let userName = "John Doe";
     function calculateDiscount(price, percentage) {
         // Function implementation
     }
    
  3. Pascal Case:-

    Usages - Used in Python, Java, and JavaScript for naming classes.

    Examples -

     public class UserProfile {
         private String name;
         private int age;
    
         // Constructor, getters, setters, etc.
     }
    
  4. Kebab Case:-

    Usages - Often used in HTML for attributes like IDs and classes.

    Examples -

     <div id="user-profile" class="user-info"></div>
    

These naming conventions help maintain consistency and readability within code bases, aiding developers in understanding and navigating the code more efficiently.


How to name variables & constants?

The standard rules when we should follow naming variables and constants is - describe the value and provide more details about the value's context without introducing redundancy (if applicable).

  1. Object

    Representing a user

    Variable: user

    More details: loggedInUser, updatedUser, customer

  2. Number

    Representing age

    Variable: age

    More details: userAge, customerAge, employeeAge

  3. String

    Representing a name

    Variable: name

    More details: userName, productName, customerName

  4. Boolean

    Representing whether a user is active

    Variable: isActive

    More details: isLoggedInUserActive, isCustomerActive

  5. Context oriented

    User to Customer

    Poor examples: u, c, lIU, uR

    Improved examples: customer, client, loggedInCustomer, registeredCustomer

  6. Constants

    Representing the value of PI

    Variable: PI

These examples demonstrate the importance of using descriptive and contextually appropriate names for variables and constants, enhancing readability, clarity, and maintainability of code.


How to name Functions/Methods?

The standard rule we should follow when naming functions/methods is - use verbs or short phrases with descriptive adjectives.

We can categorize the naming for functions/methods in 3 types:-

  1. Performs an operation:

    • Performs an operation:

      • calculateArea()

        This method calculates the area of a shape, specifying clearly what it does without introducing redundancy. It follows the convention of using a verb (calculate) followed by a noun (Area) to describe the action performed.

    • Computes a boolean:

      • isValidEmail()

        This function computes a boolean value indicating whether an email address is valid or not. It follows the convention of using a verb (isValid) followed by a noun (Email) to describe the action and the context of the computation.

  2. Context-oriented names:

    • addEmployeeToDepartment()

      This method adds an employee to a specific department, clearly indicating the context and action being performed. It follows the convention of prioritizing clarity and specificity in naming methods related to specific contexts.

    • employee.addToDepartment()

      This syntax suggests that an action (addToDepartment) is performed by an instance of the employee object within its own context. It adheres to object-oriented principles by indicating the subject of the action directly.

    • department.addEmployee()

      This syntax suggests that an action (addEmployee) is performed on the department object. It follows a logical structure of subject-verb, making it clear what is being acted upon within the context of the department.

  3. Custom examples:

    • Performs an operation:

      • generateReportSummary()

        This method generates a summary report based on certain data or criteria. It follows the convention by using a verb (generate) followed by a noun (ReportSummary) to describe the action.

    • Computes a boolean:

      • isUserLoggedIn()

        This function computes a boolean value indicating whether a user is currently logged in or not. It follows the convention by using a verb (is) followed by a descriptive adjective and noun (UserLoggedIn) to describe the context and the result of the computation.

    • Context-oriented names:

      • checkoutCart()

        This method performs the action of checking out items in a shopping cart. It follows the convention by clearly indicating the context (cart) and the action (checkout) being performed.

These examples demonstrate how naming conventions can greatly enhance code readability and maintainability by providing clear indications of what each function/method does and within what context it operates.


How to name classes?

The standard rule we should follow when naming classes is - use nouns or short phrases with nouns

Sure, here are detailed examples of naming classes using the provided guidelines along with custom examples:

  1. Describe the object:

    • Product

      This class represents a product in a system. It follows the convention of using a noun (Product) to clearly describe the object it represents.

  2. Provide more details without introducing redundancy:

    • Course

      This class represents a course, providing additional details without redundancy. It's concise and descriptive, making it clear what kind of object it represents without unnecessary repetition.

  3. Avoid redundant suffixes:

    • DatabaseManager

      This class manages interactions with a database. It avoids redundant suffixes like "Obj" or "Entity" and instead focuses on describing the primary responsibility of the class.

  4. Custom examples:

    • Describe the object:

      • Customer

        This class represents a customer entity within a system. It follows the convention by using a noun (Customer) to clearly describe the object it represents.

    • Provide more details without introducing redundancy:

      • StudentProfile

        This class represents the profile of a student. It provides additional details (Profile) without introducing redundancy, making it clear what kind of object it represents.

    • Avoid redundant suffixes:

      • FileHandler

        This class handles file-related operations. It avoids redundant suffixes and focuses on describing its primary responsibility, which is handling files.

    • Bad names (to contrast):

      • UserObj

        This name is considered bad because it lacks specificity and does not provide clear information about the purpose or nature of the object it represents.

      • ObjectA

        This name is vague and does not convey any meaningful information about the object it represents, making it difficult to understand its purpose or use in the codebase.

      • Data

        This name is too generic and lacks specificity. It does not explain what kind of data the class represents or what its purpose is within the system, making it ambiguous and potentially confusing to other developers.


Common pitfalls when naming

In the context of writing clean code, naming conventions and consistency are crucial aspects that can greatly affect the readability, maintainability, and overall quality of your code base. Let's break down the common pitfalls that can occur when naming variables, functions, classes & more:

  1. Avoid unnecessary details in variable names:-

    When naming variables, it's essential to strike a balance between being descriptive and concise. Variables should convey their purpose without including redundant information. For instance, instead of naming a variable customerWithNameAndAge, which explicitly states both the customer's name and age, you could simply name it customer. The context or usage of the variable should provide clarity on what data it holds.

  2. Avoid slang or unclear abbreviations:-

    Using clear and understandable names helps other developers (including your future self) comprehend the code more easily. Avoid using obscure abbreviations or slang that might not be immediately apparent to others. For example, using userWithEscalatedPrivileges instead of an unclear abbreviation like uwep ensures that the purpose of the variable is clear at a glance.

  3. Avoid disinformation:-

    Naming variables or functions in a way that misleads or provides incorrect information can lead to confusion and errors in the code. For instance, naming a variable allCustomers when it actually contains filtered customers can mislead other developers. Choosing names like filteredCustomers would accurately convey the contents of the variable, promoting clarity and reducing the chances of misunderstanding.

  4. Choose distinctive and explanatory names:-

    Functions and methods should have names that clearly describe their purpose and functionality. Ambiguous names like doSomething or processStuff can be vague and unhelpful. Instead, opt for names that succinctly describe the action performed, such as resizeImage, applyFilter, or convertFormat. These names provide clear indications of what the function does, making the code easier to understand and maintain.

  5. Be consistent:-

    Consistency in naming conventions across your codebase is essential for readability and maintainability. Choose a naming style for functions, variables, and classes and stick to it throughout your application. Whether you prefer getCustomers(), fetchCustomers(), or retrieveCustomers(), ensure that the chosen style is consistently applied. Inconsistent naming conventions can confuse developers and make it harder to understand the codebase as a whole.

In summary, adhering to these principles of clean code—using descriptive yet concise names, avoiding ambiguous or misleading terminology, and maintaining consistency—can significantly improve the quality and readability of your code, making it easier to understand, debug, and maintain over time.

More from this blog

S

Saurabh Mahajan

12 posts

Living, Learning and Leveling up, one day at a time