Assigning Names to Variables, Functions, Classes & More
Names should be meaningful
const us = new MainEntity();
us.process();
if (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() {
}
authenticate(credentials) {
}
isLoggedIn() {
}
}
class UserManager {
constructor() {
this.userSession = new UserSession();
}
authenticateUser(credentials) {
const isAuthenticated = this.userSession.authenticate(credentials);
if (isAuthenticated) {
} else {
}
}
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:-
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
Camel Case:-
Usages - Commonly used in Java and JavaScript for variables, functions, and methods.
Examples -
let userName = "John Doe";
function calculateDiscount(price, percentage) {
}
Pascal Case:-
Usages - Used in Python, Java, and JavaScript for naming classes.
Examples -
public class UserProfile {
private String name;
private int age;
}
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).
Object
Representing a user
Variable: user
More details: loggedInUser, updatedUser, customer
Number
Representing age
Variable: age
More details: userAge, customerAge, employeeAge
String
Representing a name
Variable: name
More details: userName, productName, customerName
Boolean
Representing whether a user is active
Variable: isActive
More details: isLoggedInUserActive, isCustomerActive
Context oriented
User to Customer
Poor examples: u, c, lIU, uR
Improved examples: customer, client, loggedInCustomer, registeredCustomer
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:-
Performs an operation:
Performs an operation:
Computes a boolean:
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.
Custom examples:
Performs an operation:
Computes a boolean:
Context-oriented names:
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:
Describe the object:
Provide more details without introducing redundancy:
Avoid redundant suffixes:
Custom examples:
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:
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.
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.
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.
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.
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.