
A great example would be a math function like log2. We should try to only merge code that’s fundamentally the same. The solution is likely to remain disciplined about splitting out code that, while it may be similar now, is only coincidentally similar. … and those flags make the logic do different things depending upon whether it’s a Facebook or Instagram post. One day, Instagram might introduce something dumb like “filters” or “stories” and all of a sudden the common abstraction needs crazy flags and parameters like: Just because they’re coincidentally the same, probably doesn’t mean that the logic should only be written once. A hypothetical example of this would be if the Facebook and Instagram APIs had the same way to create a social post. It’s really hard to guarantee that duplicate blocks of code will remain perfect copies of each other forever. Sometimes two pieces of code happen to be the same at a given point in time, but later on, they become distinct in some way. That said, let’s look at some of the drawbacks that come along with too much centralization. It seems like a good idea to reduce code duplication right? Well, yes, in general, it is.

Start the Back-end Career Path Why wouldn’t you DRY out your code? 🔗 This might not be a big problem with just 2 API calls, but what if we have 30? Or maybe 1000? Instead, we can DRY up this code by writing a simple fetchWithAuth() function that centralizes all the client’s authentication logic in a single place: You may have noticed that the beginnings of those two API calls are nearly identical - the first few lines check to see if a user is properly authenticated and sends authentication data in the respective requests.

Let’s take a look at some examples in JavaScript.Įxport async function updateUserHandle ( handle ) Let’s explore why I think DRY can be a good heuristic for better code but is far from an “absolute good”. We’ll trade usefulness for cleanliness, complexity for speed, ownership for ease of development, and abstractions for reusability.ĭRY code is often held aloft as an ideal in the quest for clean code. With that in mind, our pursuit of “clean code” will necessarily consist of tradeoffs.

Without code, an application can’t provide value to users. I’m happy to admit that a perfectly clean (empty) codebase is useless. The only clean code is code that doesn’t exist at all. First, why should we care about cleaner code? 🔗Ĭlean code is like clean garbage - it doesn’t really exist. DRY purports to accomplish this by reducing repetition in your codebase and replacing that duplicate code with abstractions like functions, classes, and methods. It aims to make code cleaner, which is to say less buggy and easier to work with.

“Don’t repeat yourself”, or “DRY” for short, is a somewhat controversial principle of software development.
