Meaningful Names – Meaningful Distinctions

If we don’t give enough thought to the names we use, our code can become more difficult to understand because it’s unclear who does what.

Different variables that seem to be the same

In some cases, our code can be hard to understand because we don’t make meaningful distinctions when choosing names, take the following variables:

var customer;
var customerInfo;
var customerData;

It is unclear as to which data each variable holds. What’s the difference between them?

Unclear parameter names

Other times, the problem occurs when choosing the names for the parameters in our functions. Perhaps the clearest case for this would be simple mathematical operations.

int Multiply(int a, int b);
int Divide(int a, int b);

For multiplication this might not be a significant problem since the order of the factors doesn’t affect the product. For the division, however, the result (quotient) will be different depending on which number is the one being divided (dividend) and which one is the divisor. Using better names the functions would look like this:

int Multiply(int multiplicand, int multiplier);
int Divide(int dividend, int divisor);

While this might seem absurd (and maybe even confusing if you don’t remember the formal operand names) the code is very clear about the order in which it expects the parameters.

A “real world” example

Imagine a function in a financial system that takes funds from one account and deposits them in another. Which function prototype is clearer?

void TransferFunds(string a1, string a2, decimal d);
void TransferFunds(string originAccount, string destinationAccount, decimal amount);

Small improvements add up

Small details like this can make your code easier to understand. Code that is easy to understand is easier to modify, requires less comments and is less prone to have bugs. Any thing you can do to improve your code is worth doing.

 

Meaningful Names – Avoid Disinformation

Usually the main problem with code is that it can be hard to understand. Most of the time it’s hard to grasp what the code does because we don’t have enough information readily available. In other cases, the problem is that the code lies to us. It lies because it’s giving us information that simply isn’t true.

How code lies

People don’t usually set out to write code that is misleading. This usually happens because of small mistakes that add up over time. Have you ever seen one of the following:

Comments that don’t correctly describe what the code actually does

The comments were probably correct at some point but as the code changed, no one bothered to update them.

Functions that do more (or less) things than you would expect

The function initially only did what it said, but as a new feature was quickly developed, the extra business logic was never moved to a separate function.

Variables that don’t use the data structure their name implies

The first version of the code used a list to store the values, so of course the name ValueList was chosen. After some optimizations, the values are now stored in a hash table, but the name couldn’t be modified because changing it would cause other code to fail.

How to prevent this

As you may have guessed by now, the seemingly simple, even trivial task of deciding the names you are going to use, is far more important than it may seem. Take the time to really think about the names you will use. Make sure that they don’t imply things that aren’t true. When you change your code, check your comments (more on comments in future posts) and see if any of the names you were using have to be updated. Also try not to reveal implementation details in case they will change in the future.

 

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.

Meaningful Names – Introduction

Continuing our study of the Clean Code series, we will now talk about the importance of using the right names for our variables, functions, classes, etc.

Are the names we use really that important? In one word: Yes!

Why names are important

Over time I have come to appreciate just how important the names we give something is. The name we give something shows what we perceive that thing is and how we expect it to behave. If I tell you something is a vehicle you might think about a car, bus or motorcycle, buy just the name gives you a good idea about what it is and what it can or should do. Our code works the same way

I now prefer to take a few minutes (or longer) choosing the right names for my variables, classes, etc. because choosing the right name will make my coding a lot easier.

Let’s go back to the vehicle example, what do you expect a vehicle to have? What do you expect it to do?

Many people would expect a vehicle to have at the very least a steering wheel, engine, wheels and a seat. They would also expect the vehicle to somehow be able to turn on, move, honk and some other basic things a vehicle does. Likewise, they wouldn’t expect a vehicle to brew you a cup of coffee.

What about names in our code?

Our code works the same way. The name you use for something will direct your thoughts about what information it should have and the functionality that it’s responsible for.

If you have ever written a module or class that ended up more than one thing (hello god objects!) then you know why names are important. If you have a class called CurrencyConverter then you can be pretty sure that it’s job will be receiving a value representing one currency and it returning the converted value in a different currency. You would expect it to store the conversion rate for those currencies somewhere and so on. You probably wouldn’t expect that class to send emails.

 

Now that we’ve established the importance of using the right names in our code, lets look at some guidelines that will help you do a better job at picking them.

Don’t be afraid of asking questions at your next meetup

Whenever I go to a meetup, presentation, etc. there is one thing that has always surprised me. People are afraid of saying that they don’t know something.

What usually happens

Usually at the beginning of a presentation the speaker will ask the audience if they have any experience in the topic that he is about to present. I’ve never seen more than a few people raise their hands. Most of the time everyone will sit quietly for the duration. Once the floor is opened for questions there will be an awkward silence that lasts for a short time and the presentation will end.

Why don’t people ask questions?

I don’t think that anyone can give a presentation on a subject to a group of people and everyone will understand everything to the point that there are no questions. I find it specially hard to believe in a deep and complex field like software development.

People have questions, they’re just ashamed of asking them in front of others. This is why many times even though there were no questions you will see people approaching the speaker afterwards and talking to him for some time.

The lie we believe

We’re programmers. We’re smart people. Others come to us when they need difficult problems solved. We feel we shouldn’t let others know when we don’t understand something because it will make us look bad. We can always do some research online afterwards, and no one will know.

This is a very dangerous way of thinking.

Why you should ask questions

One of the main reasons I like going to all the events I can, is precisely so I can discover new things. Sometimes the presentation will be about a new framework or technology that I didn’t know existed. Other times someone will show a way of doing things that I had never thought of before. Many times I’ve had to accept the difficult truth that I’ve been doing things the wrong way. While I don’t like being reminded that I am not all knowing and can make mistakes, I’m always glad of being able to correct the mistakes I have made.

Never be afraid of asking questions. You might be surprised what you learn.

 

Do you like the ternary operator?

In case you don’t know what the ternary operator is and want a thorough explanation you can read this article.

If you want a quick refresher, the ternary operator (?) is a very compact way to do an assignment that depends on an if-else statement. For example

string result = "";
if (DoSomething()){
  result = "Do Something worked";
}
else {
  result = "Do Something didn't work";
}

Can be summarized using the ternary operator to

string result = DoSomething() ? "Do Something worked" : "Do Something didn't work";

The first time I saw this in my early programming days I honestly didn’t like it.  I would even admit that I thought other people used it in their code so they could feel “cool”.

As I’ve gotten more experienced in programming (and lazy) it has definitely won a place in my heart. You don’t have to type as much which makes code smaller and a lot easier to read.

 

What are your thoughts? Do you use this operator or would you rather just do a if-else?

 

Why does code have to be clean?

Have you ever tried to read someone else’s code? It can be quite an adventure. Weird variable names, functions that don’t explain what they do. Object names that don’t seem to be right. If you’ve ever had this happen to you then you know why code has to be clean. If this has ever happened while you are viewing your own code, after some time, then you definitely know why code has to be clean.

Who needs clean code

As long as you follow the rules of the language you’re using, the compiler doesn’t care if your code is clean or not. It’s just going to process it and make something the computer can work with. The computer doesn’t care about your variable names, all it wants is ones and zeroes.

Code has to be clean because it needs to be understood by humans. It needs to be understood while it’s being written. It most certainly needs to be understood when it’s being modified. Any piece of software that does it’s job well, will be modified because the users now want it to do more things. Don’t you want your code to be easy to modify?

Where can we learn?

If you want to learn how to write clean code then I suggest you start following Robert C. Martin or “Uncle Bob” as he refers to himself. You can find him at Clean Coders or buy his book Clean Code and start improving your skills. Rest assured that you will notice your code start to improve very quickly.

I will write down my thoughts in this blog as I study his book and videos. I will also try to share how my coding style has changed for the better.

Stay tuned!