Video in progress
How do you safely break up a 5000-line "god class" in a legacy system with no tests?
First I pin down the behavior with characterization tests, then I separate responsibilities with small, mechanical refactoring steps (extract method/class, automated IDE refactorings). Each step is deployed on its own; I don't go for a big "rewrite".
📖 Answer
A big rewrite almost always fails: the old class holds hundreds of undocumented rules and you lose them in the new code.
My sequence:
-
Draw the map. Who calls which methods (IDE call hierarchy), which methods use which fields. Usually 3–5 hidden groups of responsibility appear. This is a manual version of LCOM.
-
Characterization tests. You pin down the current behavior, not the correct one. I take real inputs from prod logs or the database and snapshot the results (approval testing). Even if I see a bug, I keep it in the test for now: fixing it is a separate change.
@ParameterizedTest
@MethodSource("realOrdersFromProdDump")
void calculateTotal_keepsCurrentBehaviour(OrderInput in, String expectedJson) {
assertThat(toJson(legacy.calculateTotal(in))).isEqualTo(expectedJson);
}
-
Cut the dependencies. If there's a
new HttpClient(),Instant.now()or a static singleton inside, I move them out to constructor parameters (creating a "seam"). Without that you can't write a test. -
Mechanical extraction. With automated refactorings (Extract Method, Move Method, Extract Class), starting with one group. The old class delegates to the new class, so the external API doesn't change.
-
Small PRs, frequent deploys. After each step I watch metrics and errors on prod. In critical places I run the new and old paths in parallel (shadow mode) and log the comparison of results.
What I don't do: mix refactoring and behavior changes in one PR. If something goes wrong on prod, you can't separate the cause.
In real time: a class like this melts away piece by piece in 2–3 months, in parallel with the main work. Explaining it to the business as "with every ticket we clean up the part of this class we touch" is much easier to accept than "give me two months for refactoring".
Sign up to mark studied questions and save your progress.