Monday 14 November 2016

Solid Part 2

Hello everybody, today I am going to continue the five parts about SOLID, and the part 2 is about Open/Closed Principle.

OCP - Open/Closed Principle

As the name suggests, a class must be open for extensions and closed for modifications, this can confuse you but it is very interesting! 
It means that the class can easily change their behavior without a change in their source code.That extension can be made by using inheritance, interface or composition.
This is very important when you are changing a class that works fine in production environment without the need of new unit tests, concern if the class will generate some bugs, unknown errors in stable parts of the code.
The concept of extension remember us the use o inheritance in OOP, the idea is when a class is working in production environment, the class changes only in a fix of development bugs or a change in model classes, for example, adding a new property but other changes  as new resources must be implemented as extension of that class, so this principle says that we should have so many abstractions among the software.

Let me exemplify for you, imagine that we have a class which calculates the interest for bank accounts, if we have two types of account the current account and the savings account our code will be that:

OCP Example
Ok, it works, but if we need to add another account type or make changes on the calculation? It is not cool to add a lot of IFs in our class, it will difficult some analisys and changes in our class and in a large class it can cause so many bugs. To put this class into the Open/Closed Principle we need to use that code:

Account class in OCP
With the code above we can implement new account types without a change in the Account class or the others account types, we just need create a new class inheriting from AccountOCP class and override the CalculateInterest method, so the class is Open for extensions and Closed for modifications and you do not need to change any code in any class when implement a new account type.


1 comment: