Hacker News new | ask | show | jobs
by martinpw 294 days ago
Closely related to the Rule of Three - ok to duplicate once, but if it is needed a third time, consider refactoring: https://en.wikipedia.org/wiki/Rule_of_three_(computer_progra...

I think it's a pretty good compromise. I have tried in the past not to duplicate code at all, and it often ends up more pain than gain. Allow copy/paste if code is needed in two different places, but refactor if needed in three or more, is a pretty good rule of thumb.

4 comments

And just like the rule that it replaced, the rule of three is now often interpreted as the "correct" approach always, while I still find reality to be more nuanced.

Sometimes you do have the domain expertise to make the judgment call.

A recent example that comes to mind is a payment calculation. You can go ahead and tie that up in a nice reusable function from the get go - if you've ever dealt with a bug where payment calculations appeared different in some places and it somehow made it in front of a customer you're well aware of how painful this can be. For some things having a single source of truth outweighs any negatives associated with refactoring.

On the other hand, just because you know you're going to have to refactor, doesn't mean you should start refactoring once you reach three; you might not yet know the ideal shape for this code until many more duplications.
Agreed, it works pretty well for me.

The hard edge case is when you have a thing that needs to be duplicated along two axes. So now you have two pairs of things, four total. Four simple things or one complex thing.

also called WET (write everything twice or write everything thrice)