DEV Community

Anton for This is Angular

Posted on • Originally published at Medium

Code quality: pre-commit linting

In 2012 I started my attempts to develop web applications. As the first project, I chose to build a website constructor. This kind of software requires a ton of client interactions. Since then I knew only one library able to assist me with that mission. It was the legendary jQuery. I put all my efforts to achieve the interactivity goals. And the end result was pretty good. Even now I am still proud of it. It was my first real project. Though since then I knew nothing about the code quality and architecture patterns.

“The code works, don’t touch it”

When I finished building the initial phase including backend and frontend parts started to mention that I am not feeling so comfortable with the code I built.

jQuery gave me a lot of freedom to structure the files and folders. And I have to say it was bad freedom. So my code looked like you were leaving your dog alone at home. All the items were in total disorder and everything upside down. It wasn’t a total disorder, but just a brand new order for each component of the application.

Initially, all was smooth and clear. I was holding all the code base in my mind. After a while, it grew larger and that’s when the problems started. Each time I needed some component I had to dig up all the code to find the component. Though it’s another topic.

The main issue with the code was the fact I was writing the code in different code styles. One time I used tabs, the next time I used spaces. Variables, methods, and constants were written in different cases without obeying any code style.

From one side it was my problem not knowing coding best practices. On the other hand, junior developers cannot know all these nuances.

The problem

Every programmer may have his preferences on how to write code. The code style may differ between coders. Nothing bad in that fact. We are all humans and have our perceptions. However, usually, software engineers are working in teams. That’s the point where problems are starting.

Imagine you’ve been given a task to do a code review. You are trying to read the code, but after a while realize you can understand nothing and the main issue in the code style. Variables are written in unusual cases, as well as functions. Lines are too long and go out of the screen borders. Indents not aligned. Once there is a line of space, another time no lines at all.

The code style is not the only and the biggest problem. The right usage in code itself means a lot for performance as well as readability.

What do I mean? For instance, let was used for a variable that has a single value assignment. If it’s not going to change why aren’t you using const? Or another case. You’ve imported some libraries to a file but afterward decided not to use them. It should be removed from the file if it’s not used otherwise the application will have a larger size than it requires.

Example

Let’s compare linted and prettified code against the same code lacking linting. For that purpose, we will take Angular code.

Non-linted and non-formatted:

    import { CrudService } from 'src/app/services/crud.service';
    import { Component, OnInit } from '@angular/core';

    @Component({
      selector: 'app-example',
      templateUrl: './example.component.html',
      styleUrls: ['./example.component.scss']
    })
    export class ExampleComponent implements OnInit {

    constructor( ) { }

    ngOnInit(): void {
      }

    public someMethod() {
        let rabbitName = 'Walter'; return rabbitName;
      }

    public anotherMethod(){
        let one = 1;
     let two = 2;

    return one+two;
      }
    }
Enter fullscreen mode Exit fullscreen mode

Linted and formatted:

    import { Component} from '@angular/core';

    @Component({
      selector: 'app-example',
      templateUrl: './example.component.html',
      styleUrls: ['./example.component.scss']
    })
    export class ExampleComponent{

        constructor( ) { }

        public someMethod() {
            return 'Walter';
        }

        public anotherMethod() {
            const one = 1;
            const two = 2;

            return one+two;
        }

    }
Enter fullscreen mode Exit fullscreen mode

As you can see the second example has nothing unnecessary inside and is more readable. This is only a tiny demonstration. Imagine having an app containing dozens of files and thousands of lines of code.

Linter is the solution

It’s good to keep all the best practices in your head. However, even senior developers may miss something unintentionally. There are a couple of tools able to assist developers to keep their code clean and structured.

Eslint

Image description

Linter is the main instrument to assist with code style and syntax issues. You may want to use the **eslint **extension if you’re working with vs code. It analyzes the code in a live mode and proposes improvements.

Prettier

Image description

There is another useful tool for developers called Prettier. It also can be used as a vscode extension. The main purpose of the instrument is to format the code in a visually nice manner. It aligns all spaces and indents providing developers with beautiful code formatting.

Only having those extensions within the IDE doesn’t guarantee all the developers on the team are responsible enough and going to be using the tools.

How do we ensure no unlinted or unformatted code will appear on the git repository? Unfortunately, none of the large frontend libraries/frameworks are supporting forceful code linting. Most of them have lint cmd commands which are running linter and verifying the code following standards.

Anyways there are npm packages able to assist with this mission.

Husky

There is an npm package coming up to help us to secure none of the unclean commits will drop into our git tree. It’s called Husky. The main purpose of the package is to create hooks for git operations. That way it’s possible to bind Eslint and Prettier actions on the pre-commit hook.

Please refer to this StackOverflow question. Where there is a basic setup for Husky. In addition, it explains how to use the pre-commit hook.

Recap

The current article discusses the necessity of code formatting and linting. Keeping eye on code quality is essential especially in large projects when it’s easy to mess up.

Lint — script responsible for alarming developers when the code violates standards.

Code formatting/prettification — an operation that makes the code more human-readable.

Top comments (0)