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.

NOTE

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)

InvoiceDao

âš  Switch to EXCALIDRAW VIEW in the MORE OPTIONS menu of this document. âš 

Text Elements

Invoice Dao

SQL DB

File

MongoDB

Link to original

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
	}
}