Legacy Code Rescue
"Legacy code is code without tests." — Michael Feathers
Rescue Strategies
1. Sprout Method / Class
- When you need to add functionality, write it as new, tested code (a "sprout") and call it from the legacy code.
- Benefit: Ensures new code is tested immediately.
2. Wrap Method / Class
- Wrap an existing method or class with a new one that contains the new logic and calls the original.
- Benefit: Provides a clear boundary for testing new behavior.
3. Breaking Dependencies
- Identify "Seams" (places where you can change behavior without editing code in that place).
- Use Dependency Injection or Subclass & Override to isolate the logic you want to test.
The Rescue Cycle
- Identify a target for change.
- Find a Seam and break dependencies.
- Write a characterization test (to document current behavior).
- Apply your change using TDD.
- Refactor with the safety of your new tests.