学习笔记:Legacy code refactor

1 code refactor的定义:

Code refactoring is the process of restructuring existing computer code - changing the factoring- without changing its external behavior. Refactoring improves nonfunctional attributes of the software. Advantages include improved code readability and reduced complexity to improve source code maintainability, and create a more expressive internal architecture or object model to improve extensibility.

关键词:对当前code结构等额重新调整,不改变code本身的外部行为,非功能性的调整,可以从可读性,复杂度,可维护性等方面进行调整。

code refactor能够带来的好处:

主要体现在两个方面:可维护性,可扩展性


code refactor的过程:是一个迭代的过程,小范围的改变,测试确保正确性之后再修改测试。在refactor的过程中单元测试是非常必要的,它可以用来验证failure是由于原来的代码本身有问题还是因为refactor造成的。


常用的refactor技术:

1)更高的抽象:

# Encapsulate Field \u2013 force code to access the field with getter and setter methods(用getter、setter来对属性进行封装)
# Generalize Type \u2013 create more general types to allow for more code sharing
# Replace type-checking code with State/Strategy[5](对类型的检查的code可以使用状态或者策略模式)
# Replace conditional with polymorphism (使用多态来代替条件)

2)对code进行逻辑上更小的分片

    * Componentization breaks code down into reusable semantic units that present clear, well-defined, simple-to-use interfaces.
    * Extract Class moves part of the code from an existing class into a new class.
    * Extract Method, to turn part of a larger method into a new method. By breaking down code in smaller pieces, it is more easily understandable. This is also applicable to functions.

3)code的名称和位置:

    * Move Method or Move Field \u2013 move to a more appropriate Class or source file
    * Rename Method or Rename Field \u2013 changing the name into a new one that better reveals its purpose
    * Pull Up \u2013 in OOP, move to a superclass (讲子类的方法移到父类)
    * Push Down \u2013 in OOP, move to a subclass(将父类的方法移到子类)

一些建议:

Most re-factoring is done to 'make maintenance and future development easier';

But for each re-factor made we can justify 'this specific change will make the actual task we are doing now easier'. Rather than 'this is now cleaner for future work'.



你可能感兴趣的:(学习笔记:Legacy code refactor)