2. Open-Closed in [S.O.L.I.D] Principles.

2. Open-Closed in [S.O.L.I.D] Principles.

Introduction:

-- In this series, I will explain the five rules of S.O.L.I.D principles in detail.
The reason these are important is so that, your code will be readable, maintainable, and testable.

You can find the previous chapters of the series below:

1. [S] in [S.O.L.I.D] Single Responsibility

Let`s go through the second principle [Open-Closed]:

The class should be open for extension and closed for modifications.

  • Modification means changing the code of an existing class.
  • Extension means adding a new functionality.


As our example in the previous chapter of the series.
We have the following code snippet -->

Code Snippet

  • Now we need to add new functionality to SaveInvoice Class [Save this invoice into File].

As per the Open-Closed Principle rule, our class must be closed to modification which means the code should be the same.

Applying this rule through the interface and implementing it in different classes with different implementations.

interface Save{
    fun saveInvoice(cashier: Cashier)
}

class SaveInvoiceToDatabase() : Save{
    override fun saveInvoice(cashier: Cashier) {
        TODO("not implemented")
    }
}

class SaveInvoiceToFile() : Save {
    override fun saveInvoice(cashier: Cashier) {
        TODO("not implemented")
    }
}

It will be easier now to add new functionality if you need to save this invoice into API it will be much easier to create its own class with different implementations for Network saving and so on.

Happy coding 😀🎉
If you enjoyed this blog post ♥, follow✔, and let`s share the knowledge LinkedIn