sexta-feira, 26 de junho de 2015

Choosing good names

When we talk about clean code, the first thing that comes to my mind is to give the intent of the code we're writing. When we write some piece of code we want to make it clean, it also means we want to clarify the intent of that unit. Choosing good names for classes, methods, attributes, etc is one way to achieve this. Here is a citation from Robert Martin on Clean Code book:

"Choosing good names takes time but saves more than it takes."

It seems to be something very basic, but many times we're writing code, thinking the names we're giving the Classes/Methods/Attributes are clear enough, and actually it's not that clear. At that moment it seemed that name was the best, the clearer, but if you read that piece of code two or three hours later, you'll probably notice that the name you choose was not transmitting your intent, or at least you will find a better name.

Where there is a comment near a method name for example, It means the author could not reveal the intent of that method. Meaningful names dispense comments.

A classic example is the variables named "a", "b", "c", etc. Here is an example of a method for calculating taxes over a banking transfer:

Once someone who's gonna consume this method looks at its signature, this doubt will appear. What the hell is "a"? What about "b"? Here the developer could have chosen better names for the parameters and even for the method name. Let's express the method intent with well written names:

Now looking at the method signature, it's way clearer. Now the consumer will understand the intent of the method and the meaning of the attributes.

Still there are a lot of other techniques to write clean code and avoid other programmers's suicide when trying to understand what's been written and how to use it.