Open-Closed Principle

What is the Open-Closed Principle?

Implementation Guidelines for the Open-Closed Principle

Problems of Not following the Open-Closed Principle

Let us understand the Open-Closed Principle with one example.

public class Invoice {  public void getInvoice(InvoiceType invoiceType) {    switch(invoiceType) {        case BasicInvoice:
System.out.println("Basic Invoice");
break;
case PremiumInvoice:
System.out.println("Premium Invoice");
break;
}
}

enum InvoiceType {
BasicInvoice,
PremiumInvoice
}
}
public void getInvoice(InvoiceType invoiceType) {switch(invoiceType) {    case BasicInvoice:
System.out.println("Basic Invoice");
break;
case PremiumInvoice:
System.out.println("Premium Invoice");
break;
case BusinessInvoice:
System.out.println("Business Invoice");
break;
}
}

enum InvoiceType {
BasicInvoice,
PremiumInvoice,
BusinessInvoice
}
}
interface Invoice {
void getInvoice();
}
class BasicInvoice implements Invoice { @Override
public void getInvoice() {

}
}

class PremiumInvoice implements Invoice {
@Override
public void getInvoice() {

}
}
public class InvoiceWithOpenClosePrinciple {

public static void main(String args[]) {

Invoice basicInvoice = new BasicInvoice();
basicInvoice.getInvoice();
Invoice premiumInvoice = new PremiumInvoice();
invoice.getInvoice();
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Panchal Amit

Panchal Amit

📱 Android Engineer, 📝 Writer, 💻 Open Source Contributor, Techie, IoT, Interactive Projects, ☁ AWS, Google Cloud, Firebase, Python, React.