onse
ProgrammingSoftware Design

DRY

Do not Repeat Yourself.

What is DRY?

DRY is an acronym for Do not Repeat Yourself. It is often misinterpreted as:

"a principle of software development that states that the same code should be written once and reused multiple times."

and applied indiscriminately so that a simple string utility method ends up shared by multiple modules and components, coupling them unnecessarily.

The real formulation of this principle is:

What it means is that you should only have one place in your system that represents some knowledge or logic.


Story Time

Suppose you are building an online ordering system for a restaurant. You are going to have an endpoint that allows you to put items in a basket, something like:

PUT /api/v1/basket/{basketId}/items
Content-Type: application/json
{
  "items": [
    {
      "productId": "pizza-1",
      "quantity": 2
    }
  ]
}

and returns the updated basket (with some metadata like item prices, number of items, voucher discount amount, processing fee, and the total amount to be paid, etc.):

{
  "basketId": "basket-1",
  "items": [
    {
      "productId": "pizza-1",
      "quantity": 2,
      "price": 10.00
    }
  ],
  "numberOfItems": 2,
  "voucherDiscountAmount": -5.00,
  "processingFeeAmount": 0.70,
  "totalToPayAmount": 15.70
}

This is nice because the client (a web app or a mobile app) can now display the basket with all the metadata:

    pizza margherita x 2 @ 10.00 = 20.00
    Voucher discount = -5.00
    Processing fee = 0.70
    Total to pay = 15.70

In this case the user had a 25% discount voucher that amounted to 5.00.

25% off food voucher

Now, imagine that the user applies a 100% voucher — a free meal.

100% off food voucher

The API returns:

{
  "basketId": "basket-1",
  "items": [
    {
      "productId": "pizza-1",
      "quantity": 2,
      "price": 10.00
    }
  ],
  "numberOfItems": 2,
  "voucherDiscountAmount": 20.00,
  "processingFeeAmount": 0.70,
  "totalToPayAmount": 0.00
}

The total to pay is 0.00, because the voucher covers the items and the processing fee.

Unfortunately, "someone" wrote the mobile apps so that they ignore the server total and do the calculations by themselves:

food: 2 * 10.00             =  20.00
voucher discount            = -20.00
processing fee              =   0.70
------------------------------------
total: 20.00 − 20.00 + 0.70 =   0.70

The (obvious?) problem is that the knowledge of how a basket totals - what gets added, what gets subtracted, when a fee is waived - lives in two places.

The server knows to waive the processing fee, but the mobile apps don't. And if you don't have a way to force the users to update the app, they will continue to see the old logic.

In comes one of the ugliest hacks I have had to ship. We had to modify the API to recognize it's dealing with an old version of the app, and adjust the voucher amount it returns to compensate for the processing fee.

The real voucher amount is still -10.00, and that is what web clients (which don't do the calculations by themselves) get. For mobile, the server inflates the voucher amount by the processing fee:

food: 2 * 10.00             =  20.00
voucher discount:           = -20.70
processing fee:                 0.70
------------------------------------
total: 20.00 − 20.70 + 0.70 =   0.00

So the whole problem came about because the rule "how much does this basket cost, and when is the fee waived" was repeated in two places. In other words, it did not have a single, unambiguous, authoritative representation in the system.


What It's Really about

So DRY is about not repeating the (business) logic, not just code. If you write 10 times a method that safely cuts down a string to max 50 characters and makes-it-kebab-case, it's no big deal. It's not business logic.

formatKebabMax50Characters(text: string) : string {
  // ...
}

Unless it is, e.g. it is how a slug for posts in your blogging app are created -- you should then write the method only once, because it's crucial that the slug is always created in the same way. You would probably give the method some meaningful (in the context of your application) name:

generateSlug(title: string) : string {
  /// ...
}

Common Logic

The focus on logic rather than code could go even further. In the example above the server code was C#, and the mobile apps were Java and Swift.

Say we wanted to save the roundtrip to the server to obtain the basket total -- to make the user experience more snappy. Since the code is in different languages, we can't really share it (and not repeat it).

One way of addressing this would be to invent a dedicated (simple) language in which I could express the basket-totaling logic, and then have interpreters in C#, Java and Swift. The danger here is that the interpreter is a piece of logic that is now repeated, so unless you invent a pretty universal language, you're back to square one.

Another way would be to choose one language (C# for example, since it's on the server) as the source of truth in terms of the basket-totaling logic, and then generate the code in Java and Swift from it (presumably during the build process of the mobile apps). This way, even though you're "repeating" the code, you are not repeating the logic.

On this page