18 — Refactoring Foundations¶
Driving question: What must remain invariant when internal structure changes?
Learning objectives¶
- Define refactoring as behavior-preserving restructuring.
- Use preconditions and tests to reduce transformation risk.
- Distinguish refactoring from feature work and optimization.
- Compose small transformations into larger design changes.
Behavior preservation¶
Refactoring changes internal structure while preserving externally observable behavior under an agreed observation model. That model matters: performance, timing, logging, exception types, serialization order, or reflection behavior may be observable in some systems.
Safe sequence¶
Small refactorings create checkpoints. When automation is available, precondition checking should prevent transformations known to alter binding, visibility, type resolution, or control/data flow.
Refactoring mechanics¶
Examples:
- Extract Method / Function;
- Move Method / Field;
- Extract Class / Interface;
- Inline Method / Class;
- Rename;
- Replace Conditional with Polymorphism;
- Introduce Parameter Object;
- Encapsulate Field;
- Pull Up / Push Down members.
Design / research exercise¶
Choose a refactoring supported by your IDE. Enumerate semantic preconditions that the IDE must check. Then construct one edge case involving inheritance, overload resolution, aliasing, or exceptions.
Suggested reading¶
- Martin Fowler, Refactoring.
- William Opdyke, early refactoring research.