Wiki: Refactoring of Legacy Code
For agents: Markdown version · Wiki index · Explore
- Speaker: Avi Etzioni
- Event: Reversim Summit 2015
- Video: https://www.youtube.com/watch?v=pN40_0waGVw
- Transcript: /transcripts/2015/48-pN40_0waGVw.md
- Language: Hebrew and English · Type: talk · Level: intermediate
- Topics: Software Engineering, Technical Debt, Testing, Java
Written by an LLM from machine transcripts. It can contain errors. Check the transcript before you quote it.
Summary
The speaker demonstrates a systematic, step-by-step approach to refactoring complex legacy code safely in Java. The main argument is that writing comprehensive unit tests first eliminates the fear of breaking existing functionality and guides the understanding of unfamiliar code. Through live coding, the audience learns how to eliminate tight coupling, remove static calls, reduce variable scopes, and handle dependencies effectively.
Key points
- 0:07 The first step in refactoring legacy code is writing tests starting from the shortest and most outer branches to remove the fear of breaking things.
- 0:07 When encountering tightly coupled static calls that frameworks like Mockito cannot mock easily, extracting them to a protected method and overriding them in a test subclass is a practical workaround.
- 14:52 Running test coverage helps visualize which lines of code are covered and which branches still need tests before refactoring begins.
- 20:02 Refactoring should proceed in reverse, starting from the innermost branch where the logic is most self-contained.
- 22:08 Applying Test-Driven Development (TDD) helps refactor domain logic, such as extracting feature-envy code into proper domain object methods.
- 34:47 When changing public APIs that rely on primitive parameters to accept domain objects instead, maintain backward compatibility using deprecation before removing old versions.
- 40:57 Static data access objects (DAOs) can be transitioned to dependency-injected instances to improve testability and allow swapping implementations.
Takeaways
- Always write unit tests for legacy code before attempting any refactoring to ensure safety.
- Start refactoring from the innermost code branches and work your way out.
- Minimize variable scope and remove unnecessary variables to reduce code complexity.
- Convert static method calls into injectable dependencies to enable better mocking and flexibility.
Questions this talk answers
- How can I refactor legacy code safely when there are no existing unit tests?
- What is the best way to handle and mock static method calls in legacy Java code?
- How do I transition from static data access calls to dependency injection without breaking the entire codebase?
Technologies
Java, Mockito
Tags
clean code, dependency injection, java, legacy code, refactoring, tdd, unit testing