Mastering the Art of Identifier Naming: Enhancing Readability and Maintainability
https://pixabay.com/users/boskampi-3788146/

Mastering the Art of Identifier Naming: Enhancing Readability and Maintainability

In the world of software development, the art of naming plays a crucial role. We assign names to variables, functions, classes, and various other elements in our codebase. From the smallest detail to the largest structure, naming is pervasive in our work.

Given the abundance of naming in coding, it becomes essential for us to do it well. While it may require some extra effort and time, the benefits it brings far outweigh the investment. So, here we are going to discuss a few important points which, if applied well, can significantly improve the readability and maintainability of our code.

  • Use Intention-Revealing Names:

The names that we choose for our variables, functions, classes, etc., should provide clear answers to questions like why something exists, what it does, and how it is used. By using intention-revealing names, we can enhance the understandability and maintainability of our code.

As developers, we read the code more than we write the code. If we give sensible names to our identifiers, then the reading part becomes easy. The developer need not have to refer to different sections and files of the workspace to understand the context of the code. This saves a lot of effort and time for every individual and, thus, results in increased productivity for the entire team.


int cal(int a, int b)
{ 
  int res = a * b; 
  return res; 
}         

Can we figure out what this simple code is doing just by reading it? The answer is "NO" because we do not know what variables a, b, and res stand for, or what the function cal is supposed to do. Is it the multiplication of two integers, or calculation of the total price of a list of items based on the quantity and price of an individual item, or something else? Now let's rewrite this code with better identifier names:


int calculateAreaOfRectangle(int length, int base)
{ 
  int areaOfRectangle = length * base; 
  return areaOfRectangle; 
}         

Now we can easily figure out what this code is doing without even referring to other parts of the code, despite the fact that this code also uses the same number of operations and the same number of variables in the same order. Only the naming has changed.

It's important to understand that good naming goes beyond simplicity. It involves making the context explicit within the code itself. By using descriptive names, we reduce the cognitive load on developers and enable them to grasp the code's functionality and behavior more easily.

  • Eliminate Misleading Names :

Disinformation refers to names that can mislead or create confusion for developers trying to understand the code.

Avoid using platform-specific abbreviations. Variables like hp may seem appropriate for abbreviating terms related to the Unix platform. However, in a different context, they can be misleading and create confusion (e.g., hypotenuse or HP - a tech company). It's best to use more descriptive and meaningful names that align with the purpose of the variable.

Variables like accountList should not be used unless it's actually a List. If the container holding the data is not actually a List but a different collection or grouping, using "List" in the variable name can lead to false assumptions. Instead, opt for names like accountGroup, bunchOfAccounts, or simply accounts to accurately represent the nature of the collection.

Beware of using variable names that vary in small ways. It takes time to spot the difference between nameOfStudentWithHighestMarksInClassA and nameOfStudentWithHighestMarksInClassB.

  • Create clear distinctions :

When it comes to naming elements in code, it's crucial to make meaningful distinctions. Sometimes, programmers resort to misspelling, using noise words, or adding number series to differentiate variable names without considering their significance. However, if names need to be different, they should carry distinct meanings.

Using names like item1, item2 (appending number series to a variable), and so on may seem convenient, but they lack intention and clarity. These variables do not provide any information about their use and, hence, are non-informative variables.

Noise words, such as "info", "data", or "details", can make names less informative. For example, using names like productInfo and productData doesn't provide clear distinctions (which variable actually represents the Customer object?). Choose names that precisely describe the purpose or specific attributes of the variable.

Certain words should be avoided in variable names because they are redundant or misleading. For instance, including the term "variable" in a variable name, such as nameVariable, is unnecessary. Similarly, using terms like "table" in a table name, like customerTable, adds no extra value and can be omitted.

Variables like studentNameString should be avoided. How can studentNameString be better than studentName? studentName should be a string only, and if this is not the case, then studentNameString is a disinformative variable.

  • Use Pronounceable Names:

One important aspect of naming in code is using pronounceable names. As humans, we are inherently skilled at processing and pronouncing words. Our brains are wired to recognize and understand spoken language, and this extends to the names we encounter in code.

When code is written using pronounceable names, it becomes easier to read and comprehend. As developers, we often need to discuss and collaborate on code, and having names that can be pronounced facilitates effective communication. If a name is difficult to pronounce, it can create confusion and hinder discussions.

int numberOfStudentsEnrolled = 50; 
or
int numStdntsEnrld = 50;         

Think about how a developer will sound in a discussion where they have to pronounce the variable numStdntsEnrld (and similar variables) again and again.

  • Use Searchable Names :

Searchable names are those that are easily recognizable and can be quickly located within a codebase. This practice improves the efficiency of code maintenance, debugging, and collaboration among developers.

Single-letter names or numeric constants, while they may be concise, are not easily identifiable when scanning through a body of code. It can be challenging to understand their purpose or context without additional effort. On the other hand, using meaningful names like MAX_MARKS_IN_SUBJECT provides clarity and makes it easier to locate and understand the purpose of the variable or constant.

int calculatePercentageInSubject(int marksObtainedInSubject)
{
  return (marksObtainedInSubject/100 * 100);
}

//If maximum marks in the subject have to be changed then locating 100 in 
the entire codebase is not an easy task

//Below is the better option

final int MAX_MARKS_IN_SUBJECT = 100;
int calculatePercentageInSubject(int marksObtainedInSubject)
{
  return (marksObtainedInSubject/MAX_MARKS_IN_SUBJECT * 100);
}         

The length of a name should correspond to the scope of the entity it represents. Shorter names may be suitable for local variables or small, well-defined scopes, where their purpose is evident from the surrounding context. However, for larger scopes or variables with broader significance, it is recommended to use longer, descriptive names that provide clarity and improve searchability.

  • Be Consistent in Naming Throughout the Codebase :

When it comes to naming in code, consistency is key. One important guideline is to pick one word per concept and be consistent in its usage throughout the codebase. This helps improve code comprehension and makes the code easier to skim and understand.

When multiple words can describe a particular concept, choose one and stick with it. For example, if you have operations related to retrieving data, you can choose a single word like "fetch," "read," "get," or "retrieve" to represent that action. Using different words interchangeably for the same concept can create confusion and make the code harder to follow.

If you decide to use "fetch" to represent retrieving data from a database, use "fetch" consistently across all relevant code segments. Avoid mixing different words like "fetch" and "get" to represent the same concept, as it can introduce unnecessary complexity and cognitive load for developers.

In addition to using consistent words for concepts, it's important to avoid using the same word for multiple purposes. For example, if you use the word "add" for concatenating two words, it's better to choose a different word like "insert" or "append" when adding a letter to a collection. This ensures clarity and avoids confusion when reading and understanding the code.

  • Don't Add Unnecessary Context :

When naming classes, it's important to strike a balance between providing meaningful context and avoiding redundant information. Adding unnecessary context to class names, such as prefixing every class with generic terms, can create confusion and make the codebase harder to navigate.

For example, let's say you have a project related to managing different shapes, and you prefix every class with "Shape" in its name, such as ShapeRectangle, ShapeCircle, and so on. While it might seem logical to include "Shape" to indicate the nature of the class, it can lead to a cluttered codebase and hinder code comprehension.

By unnecessarily adding context that is already implied or can be inferred from the class's purpose, you create a situation where developers need to parse through redundant information. It adds visual noise and makes it harder to quickly identify and understand the purpose of each class.

Instead, aim for more concise and specific names that capture the essence of the class without relying on generic prefixes. For example, using just Rectangle and Circle as class names would be more appropriate. The context of these classes being related to shapes can be understood from their usage or the package structure.

By avoiding unnecessary context in class names, we create a cleaner and more focused codebase. It becomes easier to navigate, search, and understand the code, saving time and effort for developers.


Apart from the above practices, there are some standard naming conventions that should be followed to make code more readable and understandable.

Please refer to these conventions here.

Following these practices, standards, and conventions will make code more readable and understandable, ultimately increasing the overall quality of the codebase and reducing the time required to build any software application. Please remember that mastering these techniques requires consistent efforts and continuous refactoring of the existing codebase in order to achieve the desired quality.


References :

Martin, R. C. (2008). Clean Code: A Handbook of Agile Software Craftsmanship. Prentice Hall.


#CleanCode?#SoftwareDevelopment?#CodeQuality??#Productivity?#quality #VariableNaming #IdentifierNaming #NamingConvention #ProductiveProgramming #ReadableCode #NamingBestPractices #NamingSkills

AKHILESH JAISWAL

Electrical engineer with over 5 years experience and familiar with Project Execution and Project Coordination associated with the design, procurement and constructions of Electrical Substations.

1 年

Good information

要查看或添加评论,请登录

RANJAN CHAUBEY的更多文章

社区洞察

其他会员也浏览了