- Refactoring is the process of changing a software system in such a way that the external behavior of the code is unchanged but its internal structure and architecture are improved.
- It is a behavior-preserving source code transformation.
Why Do We Need to Refactor?
- Improve readability and understandability
- Improve extensibility
- Add flexibility
- Improve performance
How Do You Refactor?
The key is generalization
- Abstractions are found bottom-up by examining many concrete examples
You generalize by
- Finding things with different names that behave the same
- Parameterizing to eliminate differences
- Decomposing large things into smaller, more reusable pieces
When Do You Refactor?
1. During application
- Maintenance
- Testing
- Coding
2. During framework development
The Refactoring Cycle:
- Program source code should go through expansion and contraction phases
- Expansion phase
- code is added to meet functional requirements
- Contraction phase
- code is removed and refactored to better address those requirements and plan for the future.
To Refactor or Not to Refactor :
- This cycle will be repeated many times during a program's lifetime
- “Changing the design/code might break the system”. Use tests to prove behavior preservation
- Learn through the process.
- Build documentation as you refactor and simplify
- Refactoring will pay for itself later.
Refactoring Techniques:
- Creating and removing classes, methods, variables
- Moving methods, instance variables
- Up/down a hierarchy
- Into other classes
- Reorganizing
- Inheritance, implementation hierarchies
- Method code