Code4IT

The place for .NET enthusiasts, Azure lovers, and backend developers

Clean Code Tip: Avoid mental mappings

2022-01-25 2 min read Clean Code Tips
Just a second!
If you are here, it means that you are a software developer. So, you know that storage, networking, and domain management have a cost .

If you want to support this blog, please ensure that you have disabled the adblocker for this site. I configured Google AdSense to show as few ADS as possible - I don't want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.

Thank you for your understanding.
- Davide

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()

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()

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()

or variables used, for instance, in a loop:

for (int i = 0; i <; 100; i++){}

or in lambdas:

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

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?

This article first appeared on Code4IT

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!

🐧