3 ms·
If the code is really intricate, I refactor it to understand how it works (and how it ought to work, which can be an important way of spotting bugs). But even
by jmostert2 17y ago
If the code is really intricate, I refactor it to understand how it works (and how it ought to work, which can be an important way of spotting bugs).
But even though refactoring is supposed to be perfectly mechanical and "harmless" (especially when supported with unit tests) I'll usually throw away my refactoring, because the risk of breaking the existing code is just too high. It depends on how invasive the new feature is -- if I'm going to have to change a lot to get it done anyway, I might as well incorporate the refactorings. But if the change literally is finding the right position to add a single line of code, no way I'm going to change things once I find it.
When it's clear that adding even simple features takes an extraordinary amount of time because the code is that hard to understand and maintain, getting/making time for proper refactoring is easier, but it's worthwhile even as a way of creating a mental model.
I've never tried unit tests to figure out the semantics of existing code, though, even if it seems obvious in retrospect. I think the code base would have to become very complicated indeed before I go into full scientist mode and construct hypotheses on the semantics and verify them with unit tests. If the code is a tangled mess, it could also be tough to extract the proper bits to test on and/or set up a test environment complete enough for that.