I find myself wishing an interface could be composed of methods that are fulfilled in several classes. If I could do that, I could make an interface for a role that has one function from this class and one function from that class.
Does any language support this? Is it possible in the typical Java/C#/VB.NET style OO?
For example: I have a function that takes an value object, and saves all the parts into the correct tables. I just made an interface called StatsPersistence that I inject to a function so I can unit test its behavior, but it is missing a method. I want to be able add a method to that, but that method is on a different class from the first two, so this is obviously not possible. So, I have 2 methods in one class and 1 are in the other, but they both are needed for the “role” of “StatsPersistence”. Also, those methods are all three needed for other roles too, not just this one.
What I have:
interface StatsPersistence
public saveSession(session) // fulfilled in much larger StatsActiveRecord
public saveAppUse(appUse) // fulfilled in much larger StatsActiveRecord
What I want:
interface StatsPersistence
public saveSession(session) // fulfilled in much larger StatsActiveRecord
public saveAppUse(appUse) // fulfilled in much larger StatsActiveRecord
public updateUnit(name) // fulfilled in much larger UnitActiveRecord
I could just make a new class that wraps all three methods, and have that class just make calls to the two implementers, but that seems just like a lot of OOverkill.
My thoughts are leaning towards:
- My interface role is too broad
- Make a class that wraps these three, and have it implement my desired interface
Assume you have a variable of type
StatsPersistence. An interface contract forces any instance of aStatsPersistenceto have the three methods. Therefore, aStatsActiveRecordcannot be stored as aStatsPersistence, and same for theUnitActiveRecord. This means that neither object can be an instance ofStatsPersistence, since neither object fulfills the interface contract. Thus, it is impossible to split an interface implementation between classes.There are a few alternatives.
As you mentioned, you could have a master class that implements the interface and calls the two separate classes. That could be tricky, since the two ‘subclasses’ are tied together by the master.
You mentioned the interface being too broad. You could split the interface, if appropriate.
The best solution (in the general case) is to combine the classes. If two classes have to work together to decide who does certain things, they may as well be one class.