Code Refactor
Process of restructuring existing computer code without changing/breaking its external behavior.
Advantages
- Important step of TDD. Give confidence that code is not broken.
- improved code readability and reduced complexity
- improve the maintainability by making easier to fix bugs
- create a simpler, cleaner, or more expressive internal architecture or object model to improve extensibility.
- improved performance
Steps to Refactor Project
Get Understanding of Code
- Program Dependence Graph - explicit representation of data and control dependencies
- System Dependence Graph - representation of procedure calls between PDG
- Software intelligence - reverse engineers the initial state to understand existing intra-application dependencies
Add Abstraction
- Encapsulate field – force code to access the field with getter and setter methods
- Generalize type – create more general types to allow for more code sharing
- Replace type-checking code in switch with state/strategy of subclass
- Replace conditional with polymorphism of sub class
Break down 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.
Improve name & location
- Move method or move field – move to a more appropriate class or source file
- Rename method or rename field – changing the name into a new one that better reveals its purpose
- Pull up – in object-oriented programming (OOP), move to a superclass
- Push down – in OOP, move to a subclass
- Automatic duplicate code detection
