←back to thread

361 points mmphosis | 2 comments | | HN request time: 0.454s | 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. silvestrov ◴[] No.42167993[source]
My favorite anti-example is year based tax calculation.

Rules can change enough from year to year so that parameters isn't enough. You will end up with code specific for each year.

You don't want to introduce any chance of changing results for old years when changing common code.

So best to have no common calc code. Each year is fully set in stone.

replies(1): >>42174776 #
2. TheCoelacanth ◴[] No.42174776[source]
I don't really agree with that example because of bugs.

The rules for how to calculate taxes for a past year don't change, but you probably didn't implement the previous year's rules perfectly.

If you discover a mistake in how you calculated taxes for a previous year, you should recalculate them so that you can file an amendment.