What does it mean when code is DRY?


#1

Quesion

What does it mean when code is DRY?

Answer

Some may not know it or not remember it, but it is an acronym used in programming to describe good practices, DRY stands for Don’t Repeat Yourself, meaning that we should look at our written code and check if there are any lines that we can condense or that we can turn into something reusable mainly for time and space economy, for example, if we have two functions for let’s say two buttons that show and hide an element:

let hidden = true;

function show(){
  return hidden = false;
}

function hide(){
  return hidden = true;
}

if we see it, we have two functions that are almost doing the same, we are switching the value of our variable hidden, if we want to make our code DRY, we can adjust to have one function that can toggle the value.

let hidden = true;

function toggleHidden( ){
  return hidden = !hidden; //using the not operator will negate the current value of hidden
}

button.addEventListenet('click', toggleHidden);

the same way we can use DRY practices to have a middleware function (a function that can be reused and plugged when needed) in our express servers if working on the back end.

DRY code will always be code that can be reused and that does not contain any unnecessary arguments, variables, functions, or repeated code which makes files and libraries more maintainable, cost-effective, and easier to read.