Meaningful Names – Intention Revealing Names

In your code, the names you choose should tell anyone reading it what you intend to do with that class, function or variable. You shouldn’t rely on comments (more about this in a future post) to explain what your code does.

The importance of declaring your intention

Code should be easy to read. Good code is easy to understand, even by “normal” programmers. If you write code that is very clear about what it intends to do, then it will probably be very easy to understand.

A very simple example

Take the following variable declarations:

int d;
List<int> dl;

What does d do? Just by seeing the name do we have any idea what d is for? No, we do not. The same goes for dl. You might be tempted to fix this by doing the following:

int d; //day
List<int> dl; //list of days

or a slightly better version:

int day;
List<int> listOfDays;

This isn’t much of an improvement. Now we know that the variable is supposed to store a value that represents a day, but what day? The day of the month? The day of the week? The day of the year? What days does the list of days store? Why?

A better name for the variables would be:

int todaysDate;
List<int> holidaysOfTheMonth;

I’m pretty sure that these new names give you a better idea of what we intend to do with those variables.

Now look at this function. What do you think it does?

bool FunctionX(List<int> holidaysOfTheMonth, int date){
return holidaysOfTheMonth.Contains(date);
}

It’s fairly obvious that it checks if the date we send it is a holiday. Now look at this program:

class Program
    {
        static void Main(string[] args)
        {
            int todaysDate = DateTime.Today.Day;
            List<int> holidaysOfTheMonth = new List<int>() {15, 30};
 
            if (IsDateAHoliday(holidaysOfTheMonth, todaysDate))
                Console.WriteLine("What are you doing here? Go home!");
            else
                Console.WriteLine("Get back to work!");
        }
 
        private static bool IsDateAHoliday(List<int> holidaysOfTheMonth, int date)
        {
            return holidaysOfTheMonth.Contains(date);
        }
    }

Even though there isn’t a single comment, most people would be able to read the code and quickly see that the program checks if today is a holiday.

Try it yourself

Really think about the names you use from now on. Try making your code’s intention so clear that you don’t feel the need to write comments about what it does. Other programmers who read your code (and your future self) will be glad you did.

Leave a Reply