Using LLMs for efficient learning
DRY stands for "Don't Repeat Yourself". It's a fundamental principle in programming that encourages you to avoid writing the same code multiple times. Instead, you should write code once and reuse it wherever needed. Using the DRY principle has a few huge advantages:
<aside> 💡
The main idea is simple: if you find yourself copying and pasting code, there's probably a better way to organise it.
</aside>
// Calculating areas and perimeters without functions
const rectangle1Width = 5;
let rectangle1Height = 10;
let rectangle1Area = calculateArea(rectangle1Width, rectangle1Height);
console.log("Rectangle 1 area:", rectangle1Area);
let rectangle2Width = 8;
let rectangle2Height = 12;
let rectangle2Area = rectangle2Width * rectangle2Height;
console.log("Rectangle 2 area:", rectangle2Area);
let rectangle3Width = 3;
let rectangle3Height = 7;
let rectangle3Area = rectangle3Width * rectangle3Height;
console.log("Rectangle 3 area:", rectangle3Area);
Notice how we're repeating the same calculation (width * height) three times. If we realise we need to change how we calculate area, we'd have to update it in three places!
// Calculating areas with a reusable function
function calculateRectangleArea(width, height) {
return width * height;
}
let rectangle1Area = calculateRectangleArea(5, 10);
console.log("Rectangle 1 area:", rectangle1Area);
let rectangle2Area = calculateRectangleArea(8, 12);
console.log("Rectangle 2 area:", rectangle2Area);
let rectangle3Area = calculateRectangleArea(3, 7);
console.log("Rectangle 3 area:", rectangle3Area);
Much better! The calculation logic is in one place. If we need to change it, we only update the function.
❌ Without DRY:
console.log("Hello, Alice! Welcome to our website.");
console.log("Hello, Bob! Welcome to our website.");
console.log("Hello, Charlie! Welcome to our website.");
✅ With DRY:
function greetUser(name) {
console.log(`Hello, ${name}! Welcome to our website.`);
}
greetUser("Alice");
greetUser("Bob");
greetUser("Charlie");
Now if we want to change the greeting message (for example, change "website" to "app"), we only need to change it once in the function!
The HackYourFuture curriculum is licensed under CC BY-NC-SA 4.0 **
