DEV Community


Posted on


DRY “Don't Repeat Yourself”

DRY is a basic principle in any software development. Certainly, it is the most understandable software principle, but not everything is so obvious. I want to show you when you don’t need to follow this principle.

DRY is an acronym, of “Don’t Repeat Yourself”. The main problem that DRY can solve is a reducing repetition of code. Sometimes you need to have already existed function in another module, class, etc. And the easiest way to do that is just copy&paste this function.Congratulations, DRY principle violated. Factual copping of code creates for you one huge problem:

It is hard to maintain all these functions on the whole project, and if you need to change this function — you should change it in all places where did you copy it.

How to reduce DRY
the key points for how to apply abstraction to write code that doesn’t repeat itself:

  • Create functions for common software patterns. We call them higher order function.
  • Replace the boilerplate in your code with higher order funcitons.

Some examples of higher order functions include:

  • map --- modifying each element in the array based on give rule
const finalParticipants = ["Taylor", "Donald", "Don"];

// add string after each final participant
const announcements = => {
  return member + " joined the contest.";

// [
//   "Taylor joined the contest.",
//   "Donald joined the contest.",
//   "Don joined the contest.",
// ];
Enter fullscreen mode Exit fullscreen mode
  • filter --- getting subset of the array the passes a given criterion
const randomNumbers = [4, 11, 42, 14, 39];
const filteredArray = randomNumbers.filter((n) => {
  return n > 5;
console.log(filteredArray); //[ 11, 42, 14, 39 ]
Enter fullscreen mode Exit fullscreen mode
  • reduce --- combining everything in the array based on a given rule

const arrayOfNumbers = [1, 2, 3, 4];

const sum = arrayOfNumbers.reduce((accumulator, currentValue) => {  
  return accumulator + currentValue;

console.log(sum); // 10

Enter fullscreen mode Exit fullscreen mode
  • forEach --- executes a callback function on each of the elements in an array in order.
const numbers = [28, 77, 45];

numbers.forEach((number) => {
  // 28
  // 77
  // 45
Enter fullscreen mode Exit fullscreen mode

Advantages of DRY

  • Maintainability
  • Readability
  • Reuse
  • Cost
  • Testing

Disadvantages of DRY

  • Not all code needs to be merged into one piece. Some times 2 pieces of code can look similar but with subtle differences.
  • If the code is “over dried”, it becomes difficult to read and understand.
  • Often missed, DRY is not to be limited to just the code. It is to be applied in equal measure to database design, documentation, testing code etc.

Yes, these codes are identical right now. Does the change of one duplicated part can affect some other duplicated part? If It isn’t — you can duplicate the code

Top comments (0)