针对源代码中复杂条件语句将增加程序的复杂性,影响代码的易理解性、可测试性、可维护性和可扩展性等问题,提出了一种基于抽象语法树和多态机制的复杂条件语句自动重构方法,用于识别源代码中复杂条件语句的重构时机并实施自动代码重构。首先将源代码转换为抽象语法树,再探测代码中的条件语句,寻找满足预定条件的条件语句,最后利用多态机制对条件语句进行自动重构,将其封装到一系列子类中。对4个开源项目进行重构时机识别和自动重构实验。实验结果表明,重构时机识别算法的精确率可达100%,并能准确地实现代码的自动重构;经回归测试,重构后的代码未引入任何错误;此外,该算法具有较好的性能,执行时间与系统规模呈线性关系,能够应用于各类不同规模的系统。
In order to solve the problems that complex conditional statements increase the complexity of program, and affect the understandability, testability, maintainability, and extendibility of existing code, a novel approach for automatic refactoring of complex conditional statements based on abstract syntax tree and polymorphism is proposed. The approach can be used to detect the refactoring opportunities for complex conditional statements and implement automatic refactoring. In this approach, the source code file is transformed to an abstract syntax tree at first; then all of the conditional statements are detected and the candidate statements which meet the preconditions are identified; and finally, the conditional statements are refactored automatically by introducing polymorphism, and each branch of the them is encapsulated into a subclass. Four projects are tested to identify refactoring opportunities and implement automatic refactoring. The results show that the precision of the identification algorithm for refactoring opportunities is 100%. Meanwhile, the approach can execute automatic refactoring correctly. The regression testing shows that none error is imported after refactoring. In addition, this approach has good efficiency and the execution time has a linear relationship with the size of system. It means that this approach can be used for projects of different scales.