Tag: naming

Throughout our programming education, we are typically taught how to communicate with the computer. We master the art of bending the black box to our will! But how many teachers actually emphasize the other use of code? Yes each piece of code you write communicates not only with the machine but even more importantly with another human. Possibly the rest of your team or the open source community or maybe even the future you.

While there is a lot to be said on making your code communicate better, the best place to start is how you name entities in your code. The information you pack into each name will be seen everywhere the entity is used. This makes a good naming structure a valuable investment in your code.

Think of each name as an expressive albeit tiny comment on what is currently going on in your mind. By looking at the name, the reader should be able to get context of what is happening.

With that said, let us look into some ways of improving the naming convention of your code.

The curse of the generic name

Bill gates is famously quoted to have said

"I choose a lazy person to do a hard job. Because a lazy person will find an easy way to do it."

Unfortunately too many of us only read the lazy person bit and take that to heart. Using variable names such as id, retval say nothing about the code. But say a lot about the lethargy of the developer who wrote it.

The only instance which you are allowed to use generic names is when you are using iterators

for($x = 0;$x <= 10;$x++) {
//Do something well named
}

Be explicit

In applying the principle dictated above, we may miss the entire point by giving names based not on what the code does but in our understanding of it. This insidious action can render our code even less comprehensible than before. Take a look at the example below.

$cleanStr=runCleanUp($str);

Did you understand how the $str is getting cleaned up?

$cleanStr=removeUnprintable($inputStr);

What about now?

Crucial information

In some cases you might find yourself in a situation where the variable represents some special information. This can be:

Unit of measurement

Data type

Security issue

Regulatory issue

etc

In such cases find a way to include that info

$cost = $vol * 95;

Contrast that with

$totalSale = $vol_litres * PUMP_PRICE;

Naming scheme

Most languages have a naming scheme, in PHP we has PSR-4 Python has PEP 8 and so on. It’s important to chose your favorite and stick with that.

Thankfully most editors ship with a style checker that can help enforce this displine.

Above are just a few of the naming rules you can use to make your code that much better.

What conventions do you use in your own projects? Tell us in the comment section below.