Clean Code - Part-1: Naming

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
MainEntityare undefined, making it unclear what it represents.The
processmethod lacks description, leaving ambiguity about its functionality.The condition check for
loginis unclear, with no indication of its type or purpose.Ambiguity persists regarding whether
loginis 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
UserManagerclass effectively manages user-related functionality, including authentication and login status checks.Descriptive naming of classes and methods, such as
authenticateUserandisLoggedIn, enhances readability and understanding of their purpose.Each method within the
UserManagerclass has a clearly defined role, reducing ambiguity and improving maintainability.The
isLoggedInmethod 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 / 100Camel Case:-
Usages - Commonly used in Java and JavaScript for variables, functions, and methods.
Examples -
let userName = "John Doe"; function calculateDiscount(price, percentage) { // Function implementation }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. }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:
userMore details:
loggedInUser,updatedUser,customerNumber
Representing age
Variable:
ageMore details:
userAge,customerAge,employeeAgeString
Representing a name
Variable:
nameMore details:
userName,productName,customerNameBoolean
Representing whether a user is active
Variable:
isActiveMore details:
isLoggedInUserActive,isCustomerActiveContext oriented
User to Customer
Poor examples:
u,c,lIU,uRImproved examples:
customer,client,loggedInCustomer,registeredCustomerConstants
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:
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.
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 theemployeeobject 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 thedepartmentobject. 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:
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:
Describe the object:
ProductThis class represents a product in a system. It follows the convention of using a noun (
Product) to clearly describe the object it represents.
Provide more details without introducing redundancy:
CourseThis 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.
Avoid redundant suffixes:
DatabaseManagerThis 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.
Custom examples:
Describe the object:
CustomerThis 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:
StudentProfileThis 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:
FileHandlerThis class handles file-related operations. It avoids redundant suffixes and focuses on describing its primary responsibility, which is handling files.
Bad names (to contrast):
UserObjThis name is considered bad because it lacks specificity and does not provide clear information about the purpose or nature of the object it represents.
ObjectAThis 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.
DataThis 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:
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 itcustomer. 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
userWithEscalatedPrivilegesinstead of an unclear abbreviation likeuwepensures 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
allCustomerswhen it actually contains filtered customers can mislead other developers. Choosing names likefilteredCustomerswould 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
doSomethingorprocessStuffcan be vague and unhelpful. Instead, opt for names that succinctly describe the action performed, such asresizeImage,applyFilter, orconvertFormat. 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(), orretrieveCustomers(), 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.




