Skip to content

Instantly share code, notes, and snippets.

@ahangarha
Last active February 21, 2022 08:28
Show Gist options
  • Save ahangarha/aeca2ffff451cd2ee96c1ffaa233baa4 to your computer and use it in GitHub Desktop.
Save ahangarha/aeca2ffff451cd2ee96c1ffaa233baa4 to your computer and use it in GitHub Desktop.
// == EXAMPLE 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]);
//...
// == EXAMPLE 2 ====================================
const greet = (message, name) => {
console.log(`${message}, ${name}!`)
}
greet('Hello', 'John');
greet('Hola', 'Antonio');
greet('Ciao', 'Luigi')
@ahangarha
Copy link
Author

ahangarha commented Feb 21, 2022

The code in the example 1 is not DRY. Not only we need to repeat same lines of code again and again, we need to modify them manually. This is not scalable and also maintainable.

This is a DRY code which does the same thing:

const pets = ['Cat', 'Dog', 'Bird', 'Fish', 'Frog', 'Hamster', 'Pig', 'Horse', 'Lion', 'Dragon'];
// Print all pets
pets.forEach((pet) => console.log(pet));

The code in the example 2 also is not DRY. We can make it better by looping over and object:

const greet = (message, name) => {
  console.log(`${message}, ${name}!`)
}
const messages = [
  {
    message: 'Hello',
    name: 'John'
  },
  {
    message: 'Hola',
    name: 'Antonio'
  },
  {
    message: 'Ciao',
    name: 'Luigi'
  },
];

messages.forEach(({message, name}) => greet(message, name));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment