samedi 15 août 2015

Code refactoring with existing classes in C++

I code in C++ and since the interface keyword is not there in the language, I will use interface as a concept( a contract) here.

Suppose you have an interface say IBase, which has been implemented by dozens of classes. Now you need to add another method in that interface IBase.

What would be the approach to make that change in minimal way to solve the problem of overriding that method in all implementing classes?

One way could be adding the new method with a default implementation in the Ibase class and have the derived class that need it override it.

In the above solution I feel like I am going wrong at two places, breaking the open closed principle by touching the interface and also breaking the contract by telling the user you can also call another method.

Another thing that strikes me here is , I am adding a method to the base and only one derived class is overriding it , which basically means that the other classes don’t need that method.

So that brings me to the another solution, where the class which needs this method would inherit from another class which provides this feature or use composition to use the feature of another class.

With the above solution I hit another problem, how would the client access the new functionality of the derived class through the Ibase interface. Dynamic dispatch in C++ would only work if the function is present in the base class.

Can someone please help!

Aucun commentaire:

Enregistrer un commentaire