Video in progress

The same validation or calculation code is duplicated in three services. Do you make a shared library or leave the duplication?

If it's one business rule that must change together, I give it a single owner (a library or a service). If it just looks similar but changes for different reasons, I leave the duplication.

📖 Answer

The main question: "Should this code change for one reason, at the same time?"

Two cases:

  • Calculating VAT. It's a government rule and has to be identical everywhere. If it's duplicated in three places, one gets forgotten when the rate changes and the reports don't match. That's a real DRY violation.
  • Formatting a phone number. Billing may want one format for SMS and the CRM another for display. They look the same today and differ tomorrow. If you make a shared library, if (forBilling) parameters start to creep into it.

The cost of a shared library is not in the code but in the organization:

  • versioning, a changelog, releasing;
  • who owns it: who fixes it when there's a bug;
  • every service has to upgrade, otherwise different versions live side by side and you still don't get a "single source of truth".

Options:

Option When
Copy the code the rule is local, small, rarely changes
Small library a pure function, no external dependencies, with semver
Service/endpoint the rule changes fast and must be updated everywhere at once
Configuration/table the rule is data (rates, limits)

The "rule of three" is a good starting point: abstract on the third repetition, not the second. A wrong abstraction costs more than duplication: to get out of it you first have to inline everything again.