Home  >  Article  >  Web Front-end  >  JavaScript Refactoring Tips

JavaScript Refactoring Tips

hzc
hzcforward
2020-06-23 09:35:582072browse
John Au-Yeung
Source: medium
Translator: Xiaozhi at the front end
Like and read again to develop a habit

This articleGitHub https://github.com/qq44924588... has been included. More categories of past highly praised articles have also been compiled, and many of my documents and tutorial materials have been compiled. Welcome to Star and Perfect. You can refer to the test points for review during the interview. I hope we can learn something together.

JavaScript is an easy-to-learn programming language, and it’s easy to write programs that run and perform certain actions. However, writing clean JavaScript code is difficult.

In this article, we will introduce some reconstruction ideas related to optimizing conditional expressions.

Decompose conditional expressions

We can decompose long conditional expressions into short and named conditional expressions, which is beneficial to reading. For example, we may write code like this:

let ieIEMac = navigator.userAgent.toLowerCase().includes("mac") && navigator.userAgent.toLowerCase().includes("ie")

The above code is too lengthy and not conducive to reading. We can break it down into several short and named conditional expressions, as shown below:

let userAgent = navigator.userAgent.toLowerCase();
let isMac = userAgent.includes("mac");
let isIE = userAgent.toLowerCase().includes("ie");
let isMacIE = isMac && isIE;

Merge conditional expressions

Contrary to the above, if there are multiple short conditional expressions, they can be merged into one. For example, we may write code like this:

const x = 5;
const bigEnough = x > 5;
const smallEnough = x < 6;
const inRange = bigEnough && smallEnough;

We can combine it like this:

const x = 5;
const inRange = x > 5 && x < 6;

Because the expression is very short, even combining them together will not make the expression longer, so We can do this.

Merge Duplicate Conditional Fragments

If we have duplicate expressions or statements in the conditional block, we can move them out. For example, we might write code like this:

if (price > 100) {
  //...
  complete();
} else {
  //...
  complete();
}

We can move the repeated content outside the conditional expression, as shown below:

if (price > 100) {
  //...  
} else {
  //...  
}
complete();

In this way, we don’t have to repeat the call # unnecessarily ##completeFunction.

Delete the control flag

If we use the control flag in the loop, the code should look like this:

let done = false;
while (!done) {
  if (condition) {
    done = true;
  }
  //...
}
In the above code,

done is the control flag. When condition is true, set done to true to stop the while loop.

Relative to the above, we can use

break to stop the loop, as follows:

let done = false;
while (!done) {
  if (condition) {
    break;
  }
  //...
}
Use guard statements instead of nested conditions

Guard statements It is to split a complex conditional expression into multiple conditional expressions. For example, a very complex expression nested with several layers of
if-then-else statements is converted into multiple The if statement implements its logic. These multiple if statements are guard statements.
Nested conditional statements are difficult to read, so we can use

guard statements instead of them. For example, we may write code like this:

const fn = () => {
  if (foo) {
    if (bar) {
      if (baz) {
        //...
      }
    }
  }
}
We can optimize like this:

  if (!foo) {
    return;
  }
  if (!bar) {
    return;
  }
  if (baz) {
    //...
  }
}
In the above code, the guard statements are:

if (!foo) {
  return;
}
and

if (!bar) {
  return;
}
If these conditions are false, they will return the function early, so we don't need to nest.

Replacing conditions with polymorphism

Instead of using the

switch statement, we can use the switch statement to create the same subclass for different kinds of data Perform the same operation on different types of data, and then use different methods for the type of object.

For example, we may write code like this:

class Animal {
  constructor(type) {
    this.type = type;
  }
  getBaseSpeed() {
    return 100;
  }
  getSpeed() {
    switch (this.type) {
      case ('cat'): {
        return getBaseSpeed() * 1.5
      }
      case ('dog'): {
        return getBaseSpeed() * 2
      }
      default: {
        return getBaseSpeed()
      }
    }
  }
}
We can refactor it like this:

class Animal {
  constructor(type) {
    this.type = type;
  }
  getBaseSpeed() {
    return 100;
  }
}
class Cat extends Animal {
  getSpeed() {
    return super.getBaseSpeed() * 1.5;
  }
}
class Dog extends Animal {
  getSpeed() {
    return super.getBaseSpeed() * 2;
  }
}
When the

switch statement is very long, it should be Different types of objects customize case blocks.

Take a null object

If we repeatedly check

null or undefined, we can define a null that represents the class Or subclass the undefined version and use it.

For example we might write code like this:

class Person {
  //...
}
We can refactor like this:

class Person {
  //...
}
class NullPerson extends Person {
  //...
}
Then, we set

Person to null or undefined object property instead of setting it to a NullPerson instance.

This eliminates the need to use conditions to check these values.


Recommended tutorial: "

JS Tutorial"

The above is the detailed content of JavaScript Refactoring Tips. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete