Skip to main content

Clean Code - Naming

 Introduction

If you are a ‘true’ developer than you heard about ‘Clean Code’ written by Robert C. Martin. In many companies this book become part of the developer bible. In combination with ‘Clean Coder’ I would say that this two books are mandatory for all developers.
I will start a series of article related to this topic. If you already read this book, than it is a good occasion to refresh your memories. For others, it is the perfect moment to discover how good code should look like. All the main ideas are from ‘Clean Code’. You can look at this series of articles as a summary of the book itself.

Why?

I decided to start to write about this topic because there are things that needs to be remembered and reviewed from time to time. ‘Clean Code’ is the kind of book that you don’t read once and throw it in a dark corner of your room.
This is the kind of book that you read it again and again. Every time you will discover new things that you missed or things that are reveling to you in different ways.

Naming

This is the first topic that we will cover in this article. A good name can replace one page documentation and can help another developer to understand the application and find an issues in a less period of time.
Everything in an application has a name, from a trivial field to a method or component name. A develop needs to handle the code through names. This is why it is important to give and use good naming.
How many times you look over the code that you written three months ago and you didn’t remembered what you done there. This is why good naming is irreplaceable.

Names have to reveal your Intention 

A good name can save you 10 minutes of debugging or 20 minutes of searching in documentation. When we look over the code, the code should reveal itself. Even the most complex algorithm should be easy to read if you have a good naming.
A name of the field, method, class, component should tell us why was created, what is his/her main scope ‘in life’.  Below we can find the classic example that is given when we talk about this topic.
DateTime d;
DateTime dn;
DateTime dlr;
If we look over this field definition of if we would see them somewhere in our code we would have no ideas what this fields represents and why were used (created).
DateTime creatingDate;
DateTime currentDate;
DateTime timeFromLastRun;
The above naming give us more information about our fields. It is clear for us what the purpose of each field is and what kind of information has.
We should never use a name that is mythical or hides the purpose of a specific resource. Don’t forget that a long name don’t affect application performance. Yes is true that in some languages can increase the size of the application, but nowadays, space is not a problem – more expensive is to have a support team that don’t understand a part of the application.

Avoid Disinformation

Finding a good name can take time, but this can save us time after it. Because finding good names is pretty hard, it is pretty easy to end up with names that are already consecrate. For example using names as ‘hp’, ‘cmd’ or ‘sco’ is bad. This are names that are already used as commands by operating system.
When you peek a name that is already used in another context you should take care to use it in the same context or with the same meaning. Never use consecrate names in other purposes.
carList
houseList
What do you see in the above examples? The ‘List’ suffix is telling us that the variable is a collection of cars or houses. If the variable represent only a car or a house, that the name is disinformative. Also there are times when ‘List’ is used even if use an array or other type of collections.
Another important thing is naming field similarly. For example in the below example we have two fields that are different only by one letter or another two fields that are very long and spotting the different is not easy.
cars
car
optimizelViewConfigurationUsingAVirtualProcess
optimizeIViewConfigurationUsingBVirtualProcess
In the example related to ‘car(s)’, finding a name like ‘currentCar’ and ‘carCollection’ could help us more to understand the purpose of them.
Avoid using characters that are similar like ‘L’ lower case (‘l’) and ‘I’ upper case or ‘0’ (Zero) and ‘O’ (‘o’ upper case). It is extremely hard to spot the different between them. In the above example, related to long naming, the first letter after ‘optimize’ is not the same.

Make Meaningful Distinctions


In an application you can easily end up with naming that is similar, even if we tried to make a clear distinction between them. Because of this we can end up misspelling a word or adding numbers at the end of the name.
For example in the below example we have a method that converts a string from one format to another.
void Convert(string s1, string s2)
The name of the input parameters don’t help us to understand the logic. Replacing ‘s1’ with ‘input’ or ‘inputInXYZFormat’ and ‘s2’ with ‘output’ or ‘converted’ or ‘outputInABCFormat’ would help us more.
When we don’t have ideas to name a class we can  easily end up with 3 classes with the following name
Car
CarData
CarInfo

The problem with this naming is that there is not clear distinction between ‘Data’ and ‘Info’. The reader will not know what kind of information has each class.
Using suffix or prefix that represent the type of the field don’t help us to make a more readable code. What is the different between ‘Name’ and ‘StringName’ or ‘NameString’. There is no different in the end. A name like ‘CarName’ would be more usefull. The same things applies to method, properties and class naming.

Use Pronounceable Names

Even if code is written for machines (010101001), it is pretty sure that you end up during debugging or refactoring to talk with another person about that code. It would sounds pretty silly to name a field in a way that you cannot read it or to use a naming that is coded.
‘carN4RegS1’ – ‘carNumberForRegistrationSection1’
 ‘dtoCRcrd100’ – ‘car’

Use Searchable Names

Sounds stupid? No.
You need to search the code to see different fields were use. Yes it is true that the new IDE’s give can make the job for us, but we still to use names that can be easily searched.
For example how easy is to find where ‘i’ or ‘j’ was used. The same thing is happening with magic words that are used inline, without extracting them as constants.
For example searching and replacing a number value in an application can be a nightmare if the same value was used in line for different use cases.

Avoid Encoding

 Don’t try to reinvent the weal and define your own encoding for things that were already defined and standardized. The last thing that you want to have is your own custom language.
Because of this try to use prefix like ‘I’ for interfaces or ‘Base’ suffix for abstract classes. Don’t use ‘C’ prefix for class implementation or ‘m_’ for variables.
If you end up with a custom encoding, make a step back and try to see why you end up in this situation. Based on that response you should take a decision.

Avoid Mental Mapping

Let’s start with an example:
r
t
p
Even we are developers, we don’t want to learn and memorize that ‘r’ means full url of Dacia server from Romania, ‘t’ is the same url but without protocol information and ‘p’ represent the query parameters that we need to send to the server to be able to login.
Even if mental mapping is bad, there are some names that are standard in our days. For example when we see an ‘i’ or ‘j’ we know from the first moment that we are talking about an iteration.

Class and Method naming

There are two simple rules that can help us a lot when we need to find a good name to our class or methods:
A class name should have a noun or noun phrase
A method name should have a verb of a verb phrase
Try to avoid class named with prefix/suffix like ‘Service’, ‘Factory’, ‘Processor’, ‘Data’, ‘Info’. This class name are overused (especially when we don’t find better name).

Pick One Word per Concept

Different concept in your system should have the same name. Be consistent from this perspective. You don’t want to end up with two names of a class that express the same concept. For example ‘Processor’ and ‘Analyzer’ or ‘Controller’ and ‘Manager’.
Using same word per concept will developers to understand the code more easily.

Use names from Solution and Problem domain name

Don’t use names that are out of context and are not from that specific domain. It is more natural for someone that work in automotive industry to use ‘engine’ and not ‘power source’. You should use the specific domain names and not developers naming, that can be wrong.
This can be a cause of misunderstanding between clients and developers.

Don’t Add Gratuitous Context

It is pretty easy to add context to things that are already clear. For example in a class called ‘Car’ you don’t need to name the color field of the class ‘carColor’ or ‘colorCar’. You are already in the car class and all information from this class is related to ‘Car’.

Conclusion

Finding good names inside application can be a hard things and time consuming. It is not simple to find good names. Because of this you should invest time to find and use good names.

Final words

One difference between a smart programmer and a professional programmer is that the professional understands that clarity is king. Professionals use their powers for good and write code that others can understand.
Robert C. Martin (2008-07-31 21:00:00+00:00). Clean Code: A Handbook of Agile Software Craftsmanship (Kindle Locations 969-970). Pearson Education. Kindle Edition.  

Comments

Popular posts from this blog

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(

Azure AD and AWS Cognito side-by-side

In the last few weeks, I was involved in multiple opportunities on Microsoft Azure and Amazon, where we had to analyse AWS Cognito, Azure AD and other solutions that are available on the market. I decided to consolidate in one post all features and differences that I identified for both of them that we should need to take into account. Take into account that Azure AD is an identity and access management services well integrated with Microsoft stack. In comparison, AWS Cognito is just a user sign-up, sign-in and access control and nothing more. The focus is not on the main features, is more on small things that can make a difference when you want to decide where we want to store and manage our users.  This information might be useful in the future when we need to decide where we want to keep and manage our users.  Feature Azure AD (B2C, B2C) AWS Cognito Access token lifetime Default 1h – the value is configurable 1h – cannot be modified

What to do when you hit the throughput limits of Azure Storage (Blobs)

In this post we will talk about how we can detect when we hit a throughput limit of Azure Storage and what we can do in that moment. Context If we take a look on Scalability Targets of Azure Storage ( https://azure.microsoft.com/en-us/documentation/articles/storage-scalability-targets/ ) we will observe that the limits are prety high. But, based on our business logic we can end up at this limits. If you create a system that is hitted by a high number of device, you can hit easily the total number of requests rate that can be done on a Storage Account. This limits on Azure is 20.000 IOPS (entities or messages per second) where (and this is very important) the size of the request is 1KB. Normally, if you make a load tests where 20.000 clients will hit different blobs storages from the same Azure Storage Account, this limits can be reached. How we can detect this problem? From client, we can detect that this limits was reached based on the HTTP error code that is returned by HTTP