←back to thread

361 points mmphosis | 1 comments | | HN request time: 0.213s | source
Show context
layer8 ◴[] No.42167919[source]
> Copy-paste is OK once. The second time you're introducing duplication (i.e., three copies), don't. You should have enough data points to create a good enough abstraction. The risk of diverging implementations of the same thing is too high at this point, and consolidation is needed.

This heavily depends on how likely it is for the reasons of change to also apply to the other copies. If the reasons for why the code is the way it is are likely to evolve differently for the different copies, then it’s better to just leave them as copies.

Just being the same code initially is not a sufficient reason to create an abstraction. Don’t focus on the fact that the code is currently the same, instead focus on whether a change in one copy would necessarily prompt the same change in the other copy.

This also applies to pieces of code that are different from the beginning, but are likely to have to change in conjunction, because they rely on shared or mutual assumptions. If possible place those pieces of code next to each other, and maybe add a source comment about the relevant mutual assumptions.

In other words, avoiding code duplication is a non-goal. Keeping code together that needs to evolve together is a goal. Instead of DRY or WET (don’t repeat yourself, write everything twice), think SPOT (single point of truth).

replies(2): >>42167981 #>>42167993 #
1. devjab ◴[] No.42167981[source]
The only absolute rule that you’ll ever need is that you probably won’t need the abstraction you’re thinking about. To be frank though, it started with putting a function into a new module or class. I think the list is rather bad as a whole. It’s the same as a lot of other “best practices”. It’s vague enough that you can’t really use it, but also so that you can’t really fault it.

Copy pasting code multiple times is never really “fine”. I’d argue that for most things you’d probably be better off writing a duplication script rather than abstracting it into some over complicated nonsense. It’s much easier to change, and delete, things later this way. It’s obviously not what we teach in CS though, but we really should.