TOUSEEF
Clean Code Guide (1) - Effective Way Of Naming Variables, Functions, Classes, etc.

Clean Code Guide (1) - Effective Way Of Naming Variables, Functions, Classes, etc.

July 25, 2023
|
Clean Code

As a Developer, we used to name things a lot, either it is a file name or variable, function, class or package name. Here are some rules for writing meaningful names.

Use name that reveal intension

It simply means that the name of a variable, function, or class, should tell you why it exists, what it does, and how it is used. If the name requires a comment, then the it does not reveal its intent. - Clean Code

Example:

function rArea(int a, int b) {
	return a * b
}

In the above example, the function rArea is the name of function that calculates the area of rectangle and a and b are variables that accept the length and breadth. But the function name rArea and variable names a and b and are not descriptive, making the code harder to understand.

Lets Refactor it!

function rectangleArea(int length, int breadth) {
	return length * breadth
}

Now, the code becomes self-explanatory, and developers reading or working with the code can quickly understand its purpose without the need for additional comments or explanations.

😻 Important Tips:

  1. Do not give cute names to your variables, functions, or classes, etc. Example: using usrCfg for userConfiguration, tp for totalPrice, vCreds for validCredentials, etc.
  2. Be cautious of using names that are very much similar or vary in small ways. Example: It would be difficult to recognize OrderProcessorForFastOrderHandling and OrderProcessorForEfficientOrderStorage if they are used within same file or somewhat closely within a module.

Names should be Pronounceable

Try to avoid short forms for words or i would say don't use whatsApp language in naming things.

Example: Use productQuantity instead of prdQty, totalSkuCount instead of tSkuCnt, transmitRequest instead of tnsmtReq, updateUserProfile instead of updUsrProf.

Do not use shakespearian english in code!

A proper format of naming Constants

Constants should be named using all uppercase letters with words separated by underscores(_). This convention is known as "SCREAMING_SNAKE_CASE" and is commonly used to distinguish constants from variables and make them easily recognizable. Example: TARGET, DESTINATION, MAX_PRICE, MAX_STUDENTS_IN_CLASS, MIN_WEIGHT, etc.

Have meaningful distinctions

Lets see this example to understand distinction. Here is a function that copies characters from one array and stores it to another.

function copyCharacters(char a1[], char a2[]) {
	for (int i = 0; i < a1.length; i++) {
		a2[i] = a1[i];
	}
}

The problem is the a1 and a2 variables have different names but are meaningless. Yes, we can understand after reading the code that characters are copied from a1 to a2, but here is a problem.

Problem : By only seeing the function signature copyCharacters(char a1[], char a2[]), we can't tell in which order we have to send arguments. Should we send empty array as first parameter or as second.

Lets refactor it:

function copyCharacters(char source[], char destination[]) {
	for (int i = 0; i < source.length; i++) {
		destination[i] = source[i];
	}
}

Here, we can understand that the source which is an array of characters will be sent first and empty array will be sent afterward. We don't need to go through the code within function to figure this out.

😻 Important Tips:

  1. Avoid using vague or indistinct noise words like StudentInfo and StudentData together in a place. Even the names are different but there is no distinction.
  2. Don't use names that are hard to distinguish. Can you tell which function will be called at which situation?
getActiveUser();
getActiveUsers();
getActiveUserInfo();

Avoid Single Character Names

This is mostly seen in beginner level programming books. Certainly a loop counter are named i or j or k, and one needs to remember that i represents the outer loop, j is the inner loop counter and k is some inner loop counter inside j.

This literally sucks! Avoid it for god's sake!

😻 Important Tips: Try to use names that are searchable.

Class and Object Names

Classes and objects should have noun or noun phrase names that represent the entities or concepts they model (as per the concept of OOPs). Example: Employee, Car, Book, Product, etc.

A noun or noun phrase name clearly tells us what the class represents or what real-world entity it models.

Words like Manager, Processor, Data, or Info can be vague and may not accurately convey the purpose of the class. For example, a class named Data doesn't tell us what type of data it deals with, making it unclear and potentially misleading.

Same way, Using verbs in class names might indicate that the class has behavior or actions. Try to avoid using verbs in class or object names. Example: Don't use ManageEmployee, CalculateValues, HandleEvents,RunTasks, etc as class or object names.

Method Names

Methods should have verb or verb phrase names that clearly indicate the action or operation they perform.

Additionally, accessors (methods that retrieve data) and mutators (methods that modify data) should be prefixed with "get" or "set" respectively. Example: getUserDetails(), setUserDetails().

Predicates (methods that return boolean values) should also have names that convey the question they answer. Example: isEven(), isPrimeAndPalindrome().

Use One Word Per Concept

Having multiple synonymous words for the same concept, like "fetch," "retrieve," and "get" can be confusing for developer to remember which word was used as prefix for which function. So try to use one word for a concept and maintain it in codebase.

Some other examples like: OrderController vs OrderManager, PaymentProcessor vs PaymentHandler, etc.

Use prefixes when necessary

Sometimes in functions, we used to give names like user_name, user_age, user_weight, user_address, user_state, in which a prefix user_ is common. Try to void this by minimizing the size of your function by breaking it into multiple functions or you can create a structure or class named as User that can contain name, age, weight, address and so on.

So this is it for now! Thank you for your time!

Next, I'll be discussing about functions!