DEV Community

Cover image for Clean Code Tip: Avoid mental mappings
Davide Bellone
Davide Bellone

Posted on • Originally published at code4it.dev on

7 1

Clean Code Tip: Avoid mental mappings

Every name must be meaningful and clear. If names are not obvious, other developers (or your future self) may misinterpret what you were meaning.

Avoid using mental mapping to abbreviate names, unless the abbreviation is obvious or common.

Names should not be based on mental mapping, even worse without context.

Bad mental mappings

Take this bad example:

public void RenderWOSpace()
Enter fullscreen mode Exit fullscreen mode

What is a WOSpace? Without context, readers won't understand its meaning. Ok, some people use WO as an abbreviation of without.

So, a better name is, of course:

public void RenderWithoutSpace()
Enter fullscreen mode Exit fullscreen mode

Acceptable mappings

Some abbreviations are quite obvious and are totally fine to be used.

For instance, standard abbreviations, like km for kilometer.

public int DistanceInKm()
Enter fullscreen mode Exit fullscreen mode

or variables used, for instance, in a loop:

for (int i = 0; i <; 100; i++){}
Enter fullscreen mode Exit fullscreen mode

or in lambdas:

int[] collection = new int[] { 2, 3, 5, 8 };
collection.Where(c => c < 5);
Enter fullscreen mode Exit fullscreen mode

It all depends on the scope: the narrower the scope, the meaningless (don't get me wrong!) can be the variable.

An edge case

Sometimes, a common (almost obvious) abbreviation can have multiple meanings. What does DB mean? Database? Decibel? It all depends on the context!

So, a _dbConnection obviously refers to the database. But a defaultDb, is the default decibel value or the default database?

Conclusion

As usual, clarity is the key for good code: a name, may it be for classes, modules, or variables, should be explicit and obvious to everyone.

So, always use meaningful names!

Happy coding!

🐧

This article comes from Code4IT

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more