2 Code duplication is not always bad: Code duplication vs. flexibility

 

This chapter covers

  • Sharing common code between independent codebases
  • Tradeoffs between code duplication, flexibility, and delivery
  • When code duplication is a sensible choice giving us loose coupling

The DRY (don’t repeat yourself) principle is one of the most well-known software engineering rules. The main idea behind this is to remove duplicated code, which leads to fewer bugs and better reusability of our software. But over focusing on the DRY principle when building every possible system may be dangerous and hides a lot of complexities. It is easier to follow the DRY principle if the system we are building is monolithic, meaning that almost the whole codebase is in one repository.

In today’s evolved systems, we tend to build distributed systems with many moving parts. In such architectures, the choice of reducing code duplication has more tradeoffs like, for example, introducing tight coupling between components or reducing the development speed of the team. If you have one piece of code used in multiple places, changing it may require a lot of coordination. Where coordination is needed, the process of delivering business value slows down. This chapter will delve into patterns and tradeoffs involving duplication of code. We will try to answer the question: when is code duplication a reasonable tradeoff, and when should we avoid it?

2.1 Common code between codebases and duplication

2.1.1 Adding a new business requirement that requires code duplication

2.1.2 Implementing the new business requirement

2.1.3 Evaluating the result

2.2 Libraries and sharing code between codebases

2.2.1 Evaluating the tradeoffs and disadvantages of shared libraries

2.2.2 Creating a shared library

2.3 Code extraction to a separate microservice

2.3.1 Looking at the tradeoffs and disadvantages of a separate service

2.3.2 Conclusions about separate service

2.4 Improving loose coupling by code duplication

2.5 An API design with inheritance to reduce duplication

2.5.1 Extracting a base request handler

2.5.2 Looking at inheritance and tight coupling