Coding standards: Meaningful Names in Javascript

Intro

This post, is part of a series aimed at creating some basic coding standards for the javascript language.

Even if Javascript is well known for being “flexible”, giving the developers too much freedom when using it, it does not mean that there could not be a standard.

My personal speciality is Javascript, and like many developers, I started to use it adopting my code structure and implementation, depending to the project I was running, the pressure and sometime due to the weather ( I live in Wales, so the weather need to be mentioned!). But recently there have been two main event that have helped me to understand the importance of structure. Firstly  I have started to move toward a Full Stack position, starting to learn new languages and learning different techniques and then I was introduce to Clean Code: A Handbook of Agile Software Craftsmanship, one of the best book on the market for coding standards.

Even if I strongly suggest to read the book as it was very inspiring for me, I am still going to dedicate some of my blog post to analyse and migrate part of the book into the Javascript world, highlighting starting from the use of names.

Note: All the “Bad” examples below, comes from real life experience.

Summary from the book

I have extracted part of the book by quoting the most important sentence of the paragraph accompanied by a real life example. Some section have been omitted as not fully relevant with Javascript.

Use Intention revealing Names

The name of a variable, function, or class, should answer all the big questions. It should tell you WHY it exist, WHAT it does, and HOW it is used.Use Intention-Revealing Names

example 1
 
//Bad
var time;
var diff;
//Good
var todaysTimeInMilliseconds;
var ageDifferenceBetweenUsers;

Use pronounceable names

If you can’t pronounce it, you can’t discuss it without sounding like and idiot.Use pronounceable names

example 2
 
//Bad
var btn;
var usrAdd;
var psw;
//Good
var actionButton;
var userAddress;
var password;

Use searchable Names

If a variable or constant might be seen or used in multiple places in a body of code, it is imperative to give it a search-friendly name.Use searchable names

example 3
 
//Bad
var dd;
var max;
//Good
var directDebit;
var maxAjaxAttempt;

Avoid Mental Mapping

Readers shouldn’t have to mentally translate your names into other names they already know.Avoid Mental Mapping

example 4
 
//bad
var fn;
var ln;
//good
var firstName;
var lastName

Note: If a loop is bigger than 10 lines, this should have meaningful names too instead than a 1 letter variable.

Don’t be cute

Choose clarity over entertainment value.Don’t be cute

example 5
 
//Bad
var theOnlyButton;
var killSwitch;
//Good
var submitForm;
var closeWindow;

Pick one work per concept

Pick one word for one abstract concept and stick with it.Pick one word

example 6
 
//bad
var fetch;
var retrieve;
var get;
//Good
//use just one across all the project.

Use solution domain name

Remember that people who read your code will be programmers.Use solution domain name

 

example 7
 
//Use technical terms:
var queue
var absolute
var length

Do it for your future self

It is always easy to quote a great artist, or to create a couple of examples, but the hardest part is to actually merge this small little tips in your everyday life.

I have seen an amazing improvement in my code quality and sharability ( ability to share my code with other developers without the need to add comment or explanation). I wanted to start and write this post to make people realise the importance of this small little changes.

Sometime we think that by using a very short variable we have saved ourselves time, but it is completely the opposite. The code that we have just written now, will be read many times, not only by yourself while developing but also down the line when the next update will be required in the future ( prob still you in 6 month time) or by a developer that will have no business knowledge, and that extra second that you have saved in naming a variable with a short name will be lost over and over again overtime.

Spending some extra time on deciding the correct name for a variable is worth every penny, sometime the best thing when in doubt is to ask a colleague, there is no one, better that someone that doesn’t know anything to support you in this hard task.

From practice to real life

I have written the following code to show a real life example and show how a few little variables can really change the speed with which we can read and understand the code. This is not to say that the code is actually perfect, but it is surely an improvement.

The following 11 lines of code, have nothing wrong. It is a normal function with a couple of “For loop”.

Lets read it:

Real Example 1
 
var updateObj = function(obj){
    for(var i = 0; i <= obj.length; i++){
        var sum = 0;
        for(var a = 0; a <= obj[i].marks.length; a++){
            sum += obj[i].marks[a];
        }
        var avg = sum / obj[i].mark.length;
        obj[i].exc = (avg >= 70) ? 'Yes' : 'No';
    }
}

Was it easy to read, does it explain what it does since the start?

Well, this is what most people code will probably look like. I have probably created an extreme case, but many of the pattern in the above code can be found everywhere ( the user of updateObj as variable name, or name a variable sum because is s sum of number).

The same code, with a little clean up on around names will look something like:

real example 2
 
var addExcellenceFieldToStudentsObj = function(obj){
    var students = obj;
    for(var i = 0; i <= students.length; i++){
        var student = students[i];
        var sumOfCurrentYearMarks = 0;
        var numberOfMarks = student.marks.length;
        for(var a = 0; a <= numberOfMarks; a++){
            var mark = student.marks[a];
            sumOfCurrentYearMarks += mark;
        }
        var finalMarkAverage = sumOfCurrentYearMarks / numberOfMarks;
        student.excellence = (avg >= 70) ? 'Yes' : 'No';
    }
}

The function main login is still the same, and the two For Loop are still there, but not there is a different flow when reading the code.

You don’t need to arrive at the end of the function to know that we are working on the studentObject ( the function name is now easily searchable), and you don’t need to reach the tenth line to understand that by sum we mean sum of mark.

Conclusion

This is just a small example of the power of naming. If used properly it can really change the way we develop and the way people see our code. It increase quality, readability and remove the need of comments (that are not needed if a code is well written).

I am astonished by the amount of time I have spent time reading a code over and over to understand what i really does before being able to change it, and even more surprised when that code was written by myself. I have since when making sure every file I create or update will have the same kind of “naming refactoring” showing above, as the effort is minimal ( it doesn’t change logic and if the test is covered by automatic test is quite a log risk change), but the improvement is enormous.

I hope you too share the same feeling and will help me create this standard across the industry to make Javascript a cleaner and more consistent language.

 

1 Comment

  1. Pingback: Javascript Class: ECMAScript standards - Zelig880

Leave a comment

Your email address will not be published. Required fields are marked *

"