09 October 2007

Factoring Code

Code factoring is something I work on with some of my developers. The basic idea is to reuse code whenever practical, so you don’t need to fix bugs in multiple places.

There was a nice comment about this in Worse Than Failure today, quoting Phil Haack: “Avoid premature generalization. ... The first time you notice something that might repeat, don’t generalize it. The second time the situation occurs, develop in a similar fashion — possibly even copy/paste — but don’t generalize yet. On the third time, look to generalize the approach.”

This seems like a pretty good guideline. I’ve certainly worked on projects that were far more general-purpose than they ever needed to be, and were thus harder to learn and maintain.

1 comment:

Unknown said...

At this moment, I am up late, fixing a bug (not mine of course ;)) three times because of lack of factoring.

I agree with sentiment on not generalizing early. Deciding how much architecture is too much is the better part of the art of programming IMHO.

That said, I had a great C instructor back in the day (back when they said - if you really want to get a job, learn COBOL)

He drilled into our head the mantra that if you find yourself copy/pasting more than a couple lines of code, a red flag should go up.

This guidance has served me really well over the years.