preface

Good code is necessarily readable, robust, good performance code, but how to write good front-end code, don’t worry, this article for you to lay a solid foundation.

encapsulation

Packaging can be simply understood as the process of putting a box of apples or pears into a box, and then affiking a label apple or pear so that others can know it is an apple or pear.

Encapsulates the code

Encapsulating code is to hide the implementation of the code logic in the box, and then tell others what function the code encapsulated in the box is, what input it needs, and what output it will have. Just follow the call rules when someone else calls it, and of course the wrapped code is the responsibility of the person who wrapped it. Therefore, no matter how the internal implementation of the encapsulated code is implemented, the internal implementation can be modified at will as long as the external invocation rules are not changed. As far as the caller is concerned, he doesn’t have to care how the encapsulated code is implemented, just follow the invocation rules.

Four elements

From the point of view of a single function, to write good code, we just have to grasp these elements, function name, function parameters, function internal implementation, function return.

The function name

The function name should be defined as “findElementFromArrayById”, for example, to find an element in an array.

Function parameters

Function arguments should follow the rule that if there are too many arguments, they can be defined as objects.

Function internal implementation

The internal implementation of a function should make trade-offs based on specific circumstances, such as choosing between less memory or less computation or a compromise.

The function returns

The function return is the output of the defined function. For example, the function findElementFromArrayById must expect to output an element whose ID is xx.

Note: we should keep functions as simple as possible so that they are more likely to be reused and less likely to be modified.

The sample

/ * * * @functionSelect * from idName; Field idName is an element of ID * @param array Mandatory * @param ID Mandatory * @param idName Mandatory * @returns res {null/Object} */ const findElementFromArrayById = (array, id, idName) => {let res = null
  for (let i = 0; i < array.length; i++) {
    if (id === array[i][idName]) {
      res = array[i]
      break}}return res
}
​
​
const res = findElementFromArrayById([{id: 1}, {id: 2}], 1, 'id')
const res1 = findElementFromArrayById([{pid: 1}, {pid: 2}], 1, 'pid')
console.log(res)
console.log(res1)
Copy the code

In the above example, the function parameter idName is a variable, which can be ID, PID, or other parameters, thus enhancing the scope of application of the function and reducing the amount of code.

Thanks for reading!

Need to add wechat communication, can leave a message!