I have one interface (let's say in C++) that has been implemented by some derived classes. Let's suppose that the interface is like this:
class IBase
{
virtual bool method_1() = 0;
virtual long method_2(const std::string str) = 0;
// other methods
virtual long method_10(int value) = 0;
};
and up to now 6 different derived classes (will be more in future) have implemented the interface. In lots of algorithms in my code, I have used this interface polymorphically. e.g:
// some usage
obj = getObject();
if (obj->method_1())
{
return obj->method_2("Hello");
}
else
{
return obj->method_10(12);
}
Over the time, I have found that there would be lots of methods that only one derived class implements them. So, the Q is that is it the right design to put these methods in the interface or should I put them directly in the derived classes? But note that:
- If I put them in the interface, only one derived class will implement them and for the rest of the derived classes the implementation will be empty.
- If I put them in the derived classes, my implemented algorithms will not be generic anymore and I need to check the type of the derived class during my algorithm implementation.
What is the right way to go ahead in this case?
obj->do_stuff()
and each implementation contains its own logic for whether to callmethod_2
,method_10
, or something else you haven't thought of yet.method_2
probably will callmethod_10
but is never going to callmethod_3
), this should show you that either the methods are too detailed and you can hide them under an implementation using more general methods or that yourIBase
could be separated into multiple separate interfaces (keep in mind that some class might implement both in a particular case, but others will just implement the specific one they need)