Grokking SOLID Design Principles

0% completed

Real World Analogies and Code Example

In the previous lesson, we learned the definition of the Open/Closed Principle (OCP). Now, in this lesson, we’ll explore a real-world coding example to understand how this principle is applied.

Initial Code Example Without OCP

Let’s start with a code example where all methods and logic are placed within a single class. This approach violates the Open/Closed Principle because adding new functionality will require us to modify the existing class.

In this example, the Invoice class is responsible for generating invoices and applying discounts

.....

.....

.....

Like the course? Get enrolled and start learning!
Keshav Garg

Keshav Garg

· 2 years ago

public class Invoice { private double amount; public Invoice(double amount) { this.amount = amount; } public double getAmount() { return amount; } // This method handles generating basic invoices public void generateInvoice() { System.out.println("Generating basic invoice for amount: " + amount); } // This method handles applying discounts on the invoice public void applyDiscount() { System.out.println("Applying discount on invoice: " + amount); } } public class InternationalInvoice extends Invoice { @Override public void generateInvoice() { System.out.println("Generating International invoice for amount: " + amount); } }
Show 3 replies