3 ms·
> How do you modify functions over 1000 lines long? I don't modify them. I refactor and replace them. I do it carefully, and with hatred in my heart for the pu
by EddieDante 4y ago
> How do you modify functions over 1000 lines long?
I don't modify them. I refactor and replace them. I do it carefully, and with hatred in my heart for the pusbags who couldn't be bothered to get it right the first time.
First, I curse the people who let these functions get that big in the first place. My go-to is the PERP (public explosive rectal prolapse) because I think people who write such gargantuan methods deserve to shit themselves to death, but for particularly egregious cases I find myself praying that the original authors' children grow up to be everything they hate and fear. Once I've vented my hatred, I document the method by saying it's deprecated and will soon be replaced and commit to give every other poor bastard working on this codebase fair warning.
Next, I write a unit test against the original function, or at least try to do so, so that I have a baseline.
After I've written the test, I set about identifying in broad strokes everything the function does. I create stub methods with names representing each "step" in the procedure implemented by the original function, and call them in order from a new function. I then write tests for the new outer function as well, and I make sure that the test for the old function also runs against the new function.
Once I have my stubs in place, I reimplement the big function as a bunch of little functions called in sequence. If a function exceeds thirty lines, I break it down into smaller functions. Once I am confident that the new functions work together and provide the same results as the old function, I set about replacing every reference to the old function with calls to the new one.
Once the replacement process is done, I spend some time on regression testing and documentation. I don't remove the old function until I'm sure that it's no longer needed.
PS: You might benefit from reading The Pragmatic Programmer. The authors dropped a new edition in 2019.