| ▲ | tikhonj 4 hours ago | |||||||||||||
The rule of 3 is awful because it focuses on the wrong thing. If two instances of the same logic represent the same concept, they should be shared. If 10 instances of the same logic represent unrelated concepts, they should be duplicated. The goal is to have code that corresponds to a coherent conceptual model for whatever you are doing, and the resulting codebase should clearly reflect the design of the system. Once I started thinking about code in these terms, I realized that questions like "DRY vs YAGNI" were not meaningful. | ||||||||||||||
| ▲ | miloignis 4 hours ago | parent | next [-] | |||||||||||||
Of course, the rule of 3 is saying that you often _can't tell_ what the shared concept between different instances is until you have at least 3 examples. It's not about copying identical code twice, it's about refactoring similar code into a shared function once you have enough examples to be able to see what the shared core is. | ||||||||||||||
| ||||||||||||||
| ▲ | eyelidlessness 3 hours ago | parent | prev | next [-] | |||||||||||||
I agree. And I think this also distills down to Rob Pike’s rule 5, or something quite like it. If your design prioritizes modeling the domain’s data, shaping algorithms around that model, it’s usually trivial to determine how likely some “duplication” is operating on shared concepts, versus merely following a similar pattern. It may even help you refine the data model itself when confronted with the question. | ||||||||||||||
| ▲ | fauigerzigerk 2 hours ago | parent | prev | next [-] | |||||||||||||
Agreed. DRY is a compression algorithm. The rule of 3 is a bad compression algorithm. Good abstraction is not compression at all. | ||||||||||||||
| ▲ | sph 4 hours ago | parent | prev | next [-] | |||||||||||||
The devil’s in the details, as usual. No rule should be followed to the letter, which is what the top comment was initially complaining about. Yet again, understanding when to follow a rule of thumb or not is another thing that separates the junior from the senior. | ||||||||||||||
| ▲ | taneq 4 hours ago | parent | prev [-] | |||||||||||||
> If two instances of the same logic represent the same concept, they should be shared. If 10 instances of the same logic represent unrelated concepts, they should be duplicated. Exactly. | ||||||||||||||