Code Refactoring in JavaScript - Methods

An overview on How JS Devs can refactor their JavaScript Code.

Code Refactoring in JavaScript - Methods

Photo by Luca Bravo on Unsplash

Starting this series to review Refactoring Techniques or Code Refactoring from Refactoring Guru, from JavaScript Perspective.

What is Refactoring?

As per Refactoring Guru,

Refactoring is a systematic process of improving code without creating new functionality that can transform a mess into clean code and simple design.

First Refactoring Technique is all about Methods and Functions. There is a saying, that if your function or method is more than 10-15 lines, you should split it. Long functions or methods are root of all evil, it makes the methods hard to understand and sometimes even harder to extend or change.

Let's discuss some refactoring techniques for methods.

1. Extract Method

Let's take a look at the code sample below

function printStudentInfo() {
  printName();

  // Printing Details
  console.log("Name: " + name);
  console.log("Grades: " + getGrades());
}

The above code is trying to do many things. First, it is trying to get name printName(), then it is trying to print the details, which again is trying to get grades getGrades()

If this method had more lines, it would have become difficult to figure out what this method does. This is the main reason why we need refactoring.

Let's try to refactor the above code snippet into clean code.

function printStudentInfo() {
    printName();
    printGrades(getGrades());
}

function printGrades(grades) {
    console.log("Name: " + name);
    console.log("Grades: " + grades);
}

As you can see, we have extracted the printing statements into new separate method and the replaced the old code with a call to this new method

Benefits of Extract Method Technique

  • We get clean or more readable code.
  • Less duplication of code, extracted code or the newly created method can be reused in other part of code.
  • Loose coupling or isolation of code.

Thanks

Next we will discuss Refactoring Technique for Inline Methods