Skip to content

Instantly share code, notes, and snippets.

@henokkhm
Created June 19, 2023 13:59
Show Gist options
  • Select an option

  • Save henokkhm/c6b3e92d2aa204506e70209818831ad9 to your computer and use it in GitHub Desktop.

Select an option

Save henokkhm/c6b3e92d2aa204506e70209818831ad9 to your computer and use it in GitHub Desktop.

Instructions: For each of the following code snippets, answer the following questions:

  • Is it DRY?
  • If it is not DRY, show how you can make it DRY by adding your version of the code.
  • If it is DRY, explain why it is DRY.

Code Snippet 1

const pets = ['Cat', 'Dog', 'Bird', 'Fish', 'Frog', 'Hamster', 'Pig', 'Horse', 'Lion', 'Dragon'];
// Print all pets
console.log(pets[0]);
console.log(pets[1]);
console.log(pets[2]);
console.log(pets[3]);
...
  • The above code snippet is not DRY. We can improve it by using the forEach Array method, as follows:
const pets = ['Cat', 'Dog', 'Bird', 'Fish', 'Frog', 'Hamster', 'Pig', 'Horse', 'Lion', 'Dragon'];
// Print all pets
pets.forEach((pet) => console.log(pet));

Code Snippet 2

.cat {
  font-family: "Times New Roman", Times, serif;
  font-size: 1rem;
  color: #FFF;

}

.dog {
  font-family: "Times New Roman", Times, serif;
  font-size: 1rem;
  color: #000;
}

.dragon {
  font-family: "Times New Roman", Times, serif;
  font-size: 1rem;
  color: #009933;
}
  • The above CSS snippet is not DRY. We can improve it by extracting common styles to a different class, as follows:
.pet {
  font-family: "Times New Roman", Times, serif;
  font-size: 1rem;
}

.cat {  
  color: #FFF;
}

.dog {
  color: #000;
}

.dragon {
  color: #009933;
}

Code Snippet 3

const greet = (message, name) => {
  console.log(`${message}, ${name}!`)
}

greet('Hello', 'John');
greet('Hola', 'Antonio');
greet('Ciao', 'Luigi')
  • In my opinion, the code snippet above is DRY. If we have to call a function with different arguments, and if those areguments are not in an array, the above approach is okay. If we have to do this many times, however, using an array and a forEach method is preferable.One improvement we can make is shorten the function declaration. But we have to keep in mind that the following returns the value as well.
const greet = (message, name) => console.log(`${message}, ${name}!`);

Code Snippet 4

.greetings {
  font-family: Arial, sans-serif;
  font-size: 1.5rem;
}

.greetings.english {
  background-color: #000;
  color: #FFF;
}

.greetings.spanish {
  background-color: #FFF;
  color: #000;
}
  • The above CSS snippet is DRY since all the properties are different.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment