Refining function

In JavaScript development, we spend most of our time working with functions, so we want those functions to be well named and the logic inside the function to be clear. If a function is too long and has to be commented to make it more readable, it may be worth refactoring

If there is a piece of code in a function that can be isolated, it is best to put the code in a separate function. This is a very common optimization exercise, and the main benefits of doing so are as follows.

  • Avoid super-large functions.
  • Separate functions facilitate code reuse.
  • Independent functions are easier to overwrite.
  • A separate function with a good name acts as a comment in itself.

Merge repeated conditional fragments

If a function has conditional branches that are strewn with duplicate code, merge de-duplication is necessary.

Distill conditional branch statements into functions

In programming, complex conditional branching is an important reason that makes the program difficult to read and understand, and easily leads to a huge function. We can encapsulate the condition as a function and call the function to determine it

Fair use cycle

If some of the code in the function body is actually doing repetitive work, the proper use of loops can not only do the same thing, but also reduce the amount of code.

Instead of nesting conditional branches, let the function exit early

Nested conditional branch statements are a code maintainer’s nightmare. Nested if and else statements are more difficult to read and understand than tiled if and else statements. Sometimes the open and close parentheses of an outer if branch are 500 meters apart. In the language of Refactoring, nested conditional branches are often written by programmers who believe that “there can only be one exit per function.” But in practice, if you’re not interested in the rest of the function, you should quit immediately.

Preferential exit principle

Pass object arguments instead of long argument lists

Sometimes it is possible for a function to take more than one argument, and the more arguments there are, the harder the function is to understand and use. The user of this function must first understand the meaning of all the arguments, and be careful not to pass one argument too little or put two arguments in the wrong place. At this point we can pass the function an object, all the values are taken from the object, so we don’t have to worry about missing arguments, and it will make a lot of sense

Minimize the number of parameters

Use less ternary operators

Use chain calls wisely

Decompose large classes

The single responsibility principle, try to break down large categories into smaller ones

Exit multiple loops with return

Suppose we have a double loop in the body of a function, and we need to evaluate the inner loop and exit the outer loop when a critical condition is reached.