The Rule of Three

I use the Rule of Three to determine when to refactor my source code. Often enough I need to implement a little bit different behaviour for a special case. I just copy the code I wrote for the simple case and alter it a little bit until my code pass the new test for the special case. This is the simplest thing to do and although other programmers might think of this as a code smell you didn’t overengineered it.

A little bit later you have to add another special case. This time do not simply copy the code (as this would be a code smell for real), but refactor and generalize it. The three different cases will lead to a more general implementation. Also it is easier to reach this stage from dublicated code than from that overengineered solution you might have come to if you would refactor preemptively.

Decent rule, but the reasons reuse is hard are a little more nuanced: Most people are not taught to code or think in terms of reusable chunks of logic, and attempt to reuse things which are too big and too fraught with assumptions about what they are for. That code that diffs casserole recipes? Not gonna reuse that, sorry. That code that generically diffs two lists? You bet you’re gonna reuse that.

You can code so that a normal product of working is to end up with genuinely reusable things - but it requires a change in thinking, to be more along the lines of “how do I make this a thing that does exactly one thing well” and “how do I isolate purpose-specific customizations to a single abstraction”. As far as I know nobody teaches how to do this.

That being said, someone I know from school got a lot of jobs by showing up and saying "I'm here for my interview" and getting one (for a job he was utterly unqualified for) because the hiring people were embarrassed that they lost track of his non-existent interview. He was very proud of all the jobs he'd gotten and lost this way.

The bit about changing your company is really good advice.
One question though:

Is it three different applications? Or three different audiences? What if its three different applications with the same audience.

Three applications with the same audience would be a different rule of 3; which seems similar to what I’ve been told was called “McBreen’s Rule of Three”, which says that, for any non-trivial problem, you should come up with 3 different designs and then choose the best to implement.

2 Likes