Skip to content

Comment on Don't Shave That Yak (2005)parent

Comments

If you are lucky! Sometimes I reckon it’s so impossible to reason about tangled code that the only option is to rewrite!

That's where refactoring comes in. Start with simple, local things. Make sure all the variables are properly and consistently named. Fix the indentation. De-duplicate cut'n'paste code (carefully!) where appropriate. Expand out functions that are only called from one place, where appropriate. Convert awkward control flow into more natural flow. So on and so forth. Abstract out common functionality into its own functions/classes.

You'll be amazed how, after a few iterations of this approach, even the worst spaghetti turns into something that you can start to reason about. (In fact, I find myself mentally referring to this kind of refactoring as 'combing spaghetti'.) And if you're careful to make sure none of your changes alter the function of the code, you don't lose the 'tried-and-tested' advantage of the original code.

This is peephole refactoring. Architectural redesigns (the ones that result in 1/10th the code with the same functionality but more robust, maintainable, etc etc) aren't feasible to do incrementally like this. If you're resourceful and clever, you can sometimes get to a certain point with both the old and the new architecture in place at the same time, but at some point you have to make the hard cut-over, and redevelop all the old features/edge-cases in the new system.

Even if you're starting with a disgusting hairball, a bottom-up approach will still get you to something understandable. At this stage you'll probably find that you can fix it one subsystem at a time without doing a full blank-slate rewrite. And once all of your subsystems are nice and independent and well designed, changing up the high-level architecture is far, far easier and safer.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.