Posts Tagged

Clean code

Write cleaner Javascript code with Eslint

Javascript has a bad reputation, and this is mainly due to the fact that it is too flexible to use. Many users would abuse this great feature of this language writing code that is very inconsistent and hard to follow. For example, simple inconsistency like single or double quote around strings, can make project seem quite unclear and messy.

In recent years, after I have been exposed to different languages that follow a more rigid approach to coding standards, I have started to focus to write cleaner Javascript, and I would like to share some of these experiences.

JavaScript, is especially prone to developer error due to its lack of a compilation process. Linting tools allow developers to discover problems with their JavaScript code without the need of executing it. In this article I will be going into details on how you can  use and configure a lint utility to support you.

What is Eslint

Eslint is a pluggable linting utility created by Nicholas Zokas in June 2013, that can be used to analyse our Javascript code to highlight errors on the fly, supporting a quick and clean development.

There are many linters around, but I am listing below some of the reasons that have supported my decision to choose Eslint:

  • It is open source.
  • Great documentation.
  • Huge number of configurations
  • Good examples
  • Works with all major IDE and Code editors.
  • Can be used from the Command Line
  • Works on Build Server

Getting started with Eslint

Eslint requires Node,js to be installed on your machine, so if you do not have it, please download the latest stable release from the main website.

Install

After Node.js is up and running, we can move to the next step by opening a Command Prompt and installing the Eslint package from NPM (visit the NPM website for more information regarding its usage).

Install eslint package globally
 
  1. npm i -g eslint

Configure

Following the installation above, we now have to define a configuration file called .eslintrc.json. Eslint comes with an handy feature to support you in creating this file. To trigger it, access the root location of your site and type the following command

Create eslint config file
 
  1. eslint --init

This command will return three options:

  1. Ask a couple of questions to define the configuration required
  2. Use a popular styleguide ( this will require an existing NPM package)
  3. Inspect your Javascript Files (not suggested if your coding style is inconsistent)

The above will be displayed in the command prompt like shown by the image below:

eslint --init options

For the purpose of this blog post, I am going to provide my own configuration file that need to be extracted in the root of your site. The file can be downloaded by clicking the following link:

Eslint Configuration File

Run the linter

After successfully complete the above steps, you will now be able to use Eslint by using its extensive CLI (command line interface) commands or within most of the major IDE (mode details to follow). The most basic command would just include the file or path to test, for example the following two example will respectively test file.js and all files within the “site” folder

eslint run
 
  1. eslint "c:/site/file.js"
  2. eslint "c:/site"

Configuration File explained

Now that we have Eslint fully configured, it is time to dive into the configuration file to see how a configuration file is structured, and what configurations are set in our setup. As mentioned above, there are hundreds of configurations, all well documented on the Eslint website.

Root & Environments

Section one
 
"root": true, //this will set this file and folder as the root directoty
    "env": {//load common environment/plugin configuration
        "browser": true,
        "commonjs": true,
        "es6": true,
        "node": true,
        "jquery": true
    }

The first section of our configuration file includes the root setting. This is an optional setting that define the root of your project. Projects can have more than one Eslint configuration file, and when running it, it will search in the current folder and all its ancestors until it finds the root value.

The next setting used is the env (environment). Using this setting will load specific environment setting. For example in the case above we are allowing the use of ES6 notation, therefore we would not have any error triggered if using the arrow notation =>.

Globals

Globals eslint
 
"globals": {
        "exampleGlobalVariableName": true
    }

The global configuration accept a object that will determine global variables that we can use within our JS files, without the need to be declared. Failing to do so, will trigger a no-undef error.

For example, when we added jQuery in the env setting above, has indirectly set a global for $ and jQuery variables. This setting is really useful to support the user to understand unexpected dependencies that you may have, that will result in hard unit testing.

Rules

Most of the configuration have three simple settings.

  • off – This configuration is self explanatory. It will switch the error off.
  • warn – This setting will trigger a Warning error. In many IDE warning are displayed with a Yellow underline.
  • error – This setting will return an error. A file could have some warning, but you should always aim for “error free” files.

Some specific rules have more arguments that can be used, but I will be wasting time trying to explain them, as the Eslint documentation is really complete.

Using Code Editors

Eslint CLI is fantastic, but I do not expect you to run it every single time you modify a file, and even if the linter gives you the line number for it, it would still be hard to use on a daily basis.

Luckily for us, Eslint is very easy to set up in most of the major code editors. In this section of the article, I am going to show how you install the linted on Visual Studio Code, that is my editor of choice.

Visual Studio Code

To use Eslint in the editor, we need to first install the official extension called ESlint. To access the extension page click the Extension button on the left menu or click Ctrl+ Shift + X (on windows).

After installing the above extension, you will be required to restart the editor for the effect to take place.

On restart, assuming your Eslint configuration file is in the correct folder, you will be able to immediately see errors highlighted in real time.

The screen shots below show some of the feature available when enabling the extension.

 

Conclusion

I have personally doubt the need for a tool like this, but now after using it, I cannot live without. The configuration that I have shared is a personal choice and I am more than happy for you to use it if you wish to, but at the same time, you should also dive into the available rules and see if there is anything that fit your guidelines.

Start to use a linter is just the first step to write cleaner code. No matter if you are a single developer or work in a big team. Introducing this tool will increase the quality and readability of your code. We have all been guilty of being sometimes lazy to keep our project consistent and lacking structure, but now the tools are available and we have no excuse but to start and write cleaner Javascript.

 

Javascript String: ECMAScript standards

This is the second article highlighting some of the latest improvement issued in the most recent released of the ECMAscript for javascript string.

The first article covered classes and is named:  Javascript Class: ECMAScript standards.

Javascript String

String is one of the most primitive object and most used in any programming language. It the most recent ECMAscript releases (starting from the 2015), javascript string have received some updated and improvement that will support developers in their usage.

This article will cover changes like templates literals, replacements, concatenation and tagged templates literals by offering brief descriptions and code snippets where appropriate.

Template literals

Template literals also known as “template strings”, can be accessed by the use of the back-tick (`) characters, differently from the basic strings that are initialised with single or double quotes.

This are very powerful as they enable string manipulation without the overhead that that we have had to use until now. The first feature of template literals that we are going to cover is the ability to specify multi-line strings.

Multi-line String

Javascript multi-line string have until recent being defined by ending the string with “/n” and a “+” sign, Like the example below.

old multi-line
 
console.log('This is my first line 1\n' +
'and this is my second');

This code, even if probably quite easy to write, it is not easy to maintain and not nice to read (breaking one of the rule of clear code).

If declaring a string with template literals notation, you will actually be able to define multi line string without the need of any additional character. The example below will actually output the same as the one previously shown.

Template literals multi-string
 
  1. console.log(`This is my first line 1
  2. and this is my second`);

String replacement “embedding”

String embedding or replacement occurs when we try to dynamically create a string by adding an expression or a variable within it. This is personally one of the feature that I really hate in Javascript. Most of the common languages had string manipulations methods and finally, this feature are also available to the Javascript developers.

Prior to the template literals you may have use the following to create a dynamic javascript string.

expression interpolation
 
var a = "Fifteen";
var b = 5;
console.log(a + 'is ' + (b * 3) + ' and\nnot ' + (b * 2) + '.');
// "Fifteen is 15 and
// not 10."

The above is not only quite tricky to write as it require lots of parenthesis and quotes, but it is also very hard to read compared to the following, that as with all the other examples, will output perfectly the same.

template literals: expression interpolation
 
var a = 'Fifteen';
var b = 5;
console.log(`${a} is ${b *3} and
not ${b * 2}.`);
// "Fifteen is 15 and
// not 10."

 Tagged template literals

This is an advanced for of template literals. It will enable you to create a function that can be used to parse you template literals.

The return value of this function does not have to be a string, but in the following example we show the “basic” feature.

tagged template literals
 
function tagExample(strings, valueOne, valueTwo){
    //the strings is the array of strings, each item separated by one of the value
    let firstPart = strings[0];
    let secondPart = strings[1];
    let thirdPart = "";
    if(valueOne >= valueTwo){
        thirdPart = "therefore younger than me."
    }else{
        thirdPart = "therefore older than me."
    }
    return `${firstPart} ${valueOne}
    ${secondPart} ${valueTwo}
    ${thirdPart}`;
}
tagExample`I am ${myAge}while my brother is ${myBrotherAge}`
//OUTPUT
"I am  15
while my brother is  30
therefore older than me."

String prototype methods

The following paragraphs are going to cover useful methods that have been released since the ECMAscript 2015.

javascript string includes

This new method is surely going to put a smile on your face. As a developer, I have used the following OLD method many times, and every time I had to go through over at least twice to make sure that it was returning the correct behaviour.

The include method will allow you to search for a specific string and will return the position. This was previously done using the indexOf() method like the example below.

indexOf
 
var stringToSearch = "This is a very long string";
stringToSearch.indexOf("string") !== -1;
//true

We are now able to easily obtain the same result using the includes() method. This method also allows us to pass a second paramether that specifies where the string starts.

string.includes()
 
var stringToSearch = "This is a very long string";
stringToSearch.includes("string");
//true

javascript string repeat

The name of this method is self explanatory. It allows you to repeat a specific string for a X number of times

string.repeat
 
let var1 = "etc ";
var1.repeat(3);
//etc etc etc

javascript string startsWith and endsWith

This helpers return a Boolean value and also support a second parameter that is the position to where the string check starts.

string.startWith
 
var string1 = "Start with a simple word and finish with another.";
string1.startsWith("simple ", 13);
//true
string1.endsWith("Start");
//false

Browser support

At time of writing, the features covered in this article are largely supported in all the main used browsers ( includes mobiles browsers), with the only exception of IE11 and is still not supporting this features as showed by the graph below or as it can be found in by following this link to caniuse.com website.

teamplate literals
teamplate literals

Conclusion

Even if the above feature may not be the most exiting introduced by the ECMAscript standards, they are surely going to make your day to day life a lot easier. Productivity can surely increase and this small methods will not only make you develop faster, but will also make your code more readable that is what most of us hope to achieve.

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.

 

"