When building applications, we often need to add new features or change behavior. A common mistake is modifying existing code every time we need something new. This can easily introduce bugs and break parts of the system that were already working. The Open-Closed Principle (OCP) helps solve this problem. What is Open-Closed Principle? The idea is simple: Software entities should be open for extension, but closed for modification. That means: You should be able to add new behavior Without changing existing code Why This Matters When we modify existing code: We risk breaking existing functionality Testing becomes harder The code becomes less stable over time Instead, we should extend the code in a safe way. Bad Example (Modifying Existing Code) Let’s say we have a class that calculates discounts: class DiscountService { calculate(price, type) { if (type === "regular") { return price * 0.1; } els...
When writing code, it’s common to put multiple responsibilities inside a single file or class. It might work at first, but over time it becomes difficult to manage and update. The Single Responsibility Principle (SRP) helps solve this. It is one of the core ideas from SOLID and focuses on keeping code simple and maintainable. What is Single Responsibility Principle? The idea is simple: A class should have only one responsibility. That means: It should do one job It should have only one reason to change Why This Matters When a class does too many things: Changes become risky Bugs become harder to track Code becomes difficult to understand Keeping responsibilities separate makes your code: Cleaner Easier to maintain Easier to scale Bad Example (Multiple Responsibilities in One Class) Let’s look at a class that handles everything: class UserService { validateUser(user) { if (!user.email) { console.log...