Classes should be open for extension and closed to modification.
Modification means changing the code of an existing class, and extension means adding new functionality.
We should be able to add new functionality without touching the existing code for the class. This is because whenever we modify the existing code, we are taking the risk of creating potential bugs. So we should avoid touching the tested and reliable (mostly) production code if possible.
From the last example, if we want invoices to be saved to a database so that we can search them easily.
We think it is easy, We create the database, connect to it, and we add a save method to our InvoicePersistence class.
public class InvoicePersistence {
Invoice invoice;
public:
InvoicePersistence(Invoice invoice) {
this.invoice = invoice;
}
void saveToFile(String filename) {
// Creates a file with given name and writes the invoice
}
void saveToDatabase() {
// Saves the invoice to database
}
}
If we add this feature, we have modified the InvoicePersistence class. It doesn’t follow the Open-Closed principle.
We will create an interface(abstract class in c++) InvoicePersistence and add the save method.
Each persistence class will implement this save method by implement(inherit) this InvoicePersistence interface.
public class DatabasePersistence implements InvoicePersistence {
@Override
public void save(Invoice invoice) {
// Save to DB
}
}
public class FilePersistence implements InvoicePersistence {
@Override
public void save(Invoice invoice) {
// Save to file
}
}
Now our persistence logic is easily extendable. If our boss asks us to add another database and have 2 different types of databases like MySQL and MongoDB, we can easily do that.
I was pretty pleased to discover this great site. I want to to thank you for ones time due to this fantastic read!! I definitely appreciated every part of it and I have you book marked to look at new stuff on your web site.
I was very happy to discover this great site. I need to to thank you for your time for this particularly wonderful read!! I definitely liked every part of it and I have you bookmarked to check out new information on your blog.
Good day! I simply want to offer you a big thumbs up for the excellent info youve got right here on this post. Ill be coming back to your site for more soon.