Code refactoring and unit testing

Purpose of reconstruction:

For the project, refactoring can keep the quality of the code continuously in a controllable state, and will not be corrupted to the point of hopelessly. For individuals, refactoring exercises a person's code ability and is a very fulfilling thing. It is a training ground for theoretical knowledge such as classic design ideas, principles, patterns, and programming specifications that we have learned.

Refactored objects:

According to the scale of reconstruction, we can roughly divide reconstruction into large-scale high-level reconstruction and small-scale low-level reconstruction. Large-scale high-level refactoring includes layering, modularizing, decoupling, sorting out the interaction between classes, abstracting reuse of components, and so on. This part of the work uses more abstract and top-level design ideas, principles, and patterns. Small-scale and low-level refactoring includes standard naming, comments, correction of too many function parameters, elimination of large classes, extraction of duplicate codes, and other programming details, mainly for class and function level refactoring. Small-scale low-level reconstruction is more about using the theoretical knowledge of coding standards.

Timing of reconstruction:

It is necessary to establish a continuous refactoring consciousness, and integrate refactoring into daily development as an essential part of development, instead of waiting for the code to refactor drastically when there are major problems.

Refactoring method: Large-scale and high-level refactoring is more difficult. It needs to be organized and planned, and run in small steps in stages to keep the code in a runnable state at all times. On the other hand, small-scale and low-level refactoring has a small scope of influence and short time-consuming changes. Therefore, as long as you are willing and have the time, you can do it anytime, anywhere.

 

unit test:

The so-called testability of the code refers to the difficulty of writing unit tests for the code. For a piece of code, if it is difficult to write a unit test for it, or the unit test is very laborious to write, and you need to rely on the very advanced features of the unit testing framework, it often means that the code is not well designed and the code is not testable. The most effective way to write testable code Dependency injection is the most effective way to write testable code. Through dependency injection, when we write unit tests, we can use mock methods to de-depend on external services. This is also the most technical challenge in the process of writing unit tests.

Common test-unfriendly codes include the following five types: code containing pending behavior logic, abuse of variable global variables, abuse of static methods, use of complex inheritance relationships, highly coupled code

Guess you like

Origin blog.csdn.net/flandersfields/article/details/107761302