shreyansh

Open and Closed Principle

Introduction

  • General Idea for Open for extension but closed for modification is that you can add new functionality to a class without altering its existing code.
  • As a result, when the business requirements change then the entity can be extended, but not modified.

Let's consider this example - InvoicePersistence.java.

Now let's say we want another functionality "saveToFile() : public void saveToFile(Invoice invoice, String filename) {}" in InvoicePersistence.java(which is already tested and live on production) and introducing another function can lead to bugs. This can be improved by introducing an INTERFACE for our class.

Invoice Dao(data access object)

Invoice DaoSQL DB FileMongoDB
interface InvoiceDao{
	public void save(Invoice invoice);
}

DatabaseInvoiceDao.java

class DatabaseInvoiceDao implements InvoiceDao{
	@Override
	public void save(Invoice invoice){
		// saves to db
	}
}

FileInvoiceDao.java

class FileInvoiceDao implements InvoiceDao{
	@Override
	public void save(Invoice invoice){
		// saves to file
	}
}