YAGNI
The YAGNI principle in programming
The YAGNI (You Aren't Gonna Need It) principle is a programming concept that advises developers not to implement functionality that is not currently needed. This principle is part of the Agile methodology and aims to improve software efficiency by avoiding unnecessary complexity and resource waste.
The YAGNI principle is important for the following reasons:
Let’s look at examples of applying the YAGNI principle to demonstrate how to avoid unnecessary code:
❌ Bad Example (Unnecessary Code)
function calculateTotalPrice(items: { price: number; quantity: number }[], discount: number = 0): number {
let total = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
if (discount > 0) {
total -= total * discount;
}
return total;
}
In this example, the developer has added a discount feature, even though it is not currently needed. This can lead to unnecessary complexity and potential errors.
✅ Good Example (YAGNI Approach)
function calculateTotalPrice(items: { price: number; quantity: number }[]): number {
return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}
In this example, the code is kept simple and focuses only on current requirements. If a discount feature is needed in the future, it can be added later.
To apply the YAGNI principle, you can follow these steps:
Although YAGNI is a useful principle, it can lead to certain risks if applied too strictly. For example, if a developer focuses exclusively on current requirements, it may become difficult to extend the system in the future. It is important to maintain a balance and consider future requirements without adding unnecessary code.
The YAGNI principle is an important programming concept that helps avoid unnecessary complexity and resource waste. It encourages developers to focus only on the functionality that is currently needed, leading to simpler, more understandable, and maintainable code. However, it is important to remember to consider future requirements without adding unnecessary code.