Skip to main content

Command Palette

Search for a command to run...

Mastering "O" in S.O.L.I.D 😜

Updated
2 min read
Mastering "O" in S.O.L.I.D 😜

A class should be open for extension but closed for modification.

Nai aya samajh 🤔 ?

💡 Simple Meaning:

  • You can add new behavior to the class

  • But you should not change its existing code

Agaya samajh but Abhi clear nai hua example se dekhte hai…

🧍‍♂️ Real-Life Example:

Imagine you have a mobile phone.
Now, you want to:

  • Add a new back cover

  • Add a screen guard

You don't open the mobile’s internal parts, right?
You just add things on top of it → that’s extension without modification

❌ Bad Java Example (Breaks OCP):


 public class PaymentService {
    public void makePayment(String paymentType) {
        if (paymentType.equals("creditcard")) {
            System.out.println("Paid with Credit Card");
        } else if (paymentType.equals("paypal")) {
            System.out.println("Paid with PayPal");
        }
    }
}

😵 Problem:

  • Every time a new payment method comes (like UPI, Bitcoin), you have to edit this class.

➡️ Code is not closed for modification

✅ Good Java Example (Follows OCP):

Step 1: Create an interface


public interface PaymentMethod {
    void pay();
}

Step 2: Implement different payment methods


public class CreditCardPayment implements PaymentMethod {
    public void pay() {
        System.out.println("Paid with Credit Card");
    }
}

public class PayPalPayment implements PaymentMethod {
    public void pay() {
        System.out.println("Paid with PayPal");
    }
}

Step 3: Use them without changing logic


public class PaymentService {
    public void makePayment(PaymentMethod method) {
        method.pay();  // No if-else, no changing code
    }
}

✅ Now, to add a new method like UPI:


public class UpiPayment implements PaymentMethod {
    public void pay() {
        System.out.println("Paid with UPI");
    }
}

No need to touch PaymentService — just extend the code with a new class 🚀.

💡 Hinglish Explanation:

Jab hum koi class banate hain, toh hum chahte hain ki:

  • Naya feature add kar sakein (open for extension ✅)

  • Purani code ko change na karna pade (closed for modification ✅)

Matlab:

  • Jab naye requirement aaye, toh nayi class banao ya existing class ko extend karo

  • Lekin purane code ko touch mat karo, warna bugs aa sakte hain