Object-oriented – Combinatorial explosion of interfaces: How many is too many

cdesigninterfacesobject-orientedpolymorphism

I'm a relative newcomer to OOP, and I'm having a bit of trouble creating good designs when it comes to interfaces.

Consider a class A with N public methods. There are a number of other classes, B, C, …, each of which interacts with A in a different way, that is, accesses some subset (<= N) of A's methods.

The maximum degree of encapsulation is achieved by implementing an interface of A for each other class, i.e. AInterfaceForB, AInterfaceForC, etc.

However, if B, C, … etc. also interact with A and with each other, then there will be a combinatorial explosion of interfaces (a maximum of n(n-1), to be precise), and the benefit of encapsulation becomes outweighed by a code-bloat.

What is the best practice in this scenario?

Is the whole idea of restricting access to a class's public functions in different ways for other different classes just silly altogether? One could imagine a language that explicitly allows for this sort of encapsulation (e.g. instead of declaring a function public, one could specify exactly which classes it is visible to); Since this is not a feature of C++, maybe it's misguided to try to do it through the back door with interaces?

Best Answer

The point of interfaces is to allow piece of code to express what API it works with. And then allow this API to be implemented by multiple classes. In your case, instead of AforB or AforC, make it Bneeds and Cneeds interface.

What you are saying also hints that there is actually only one implementation of those interfaces in form of A. If there is only one implementation, then there is serious flaw in the design, because point of interface is to be able to be implemented by multiple classes. If interface limits by which class it is implemented, then it is bad interface.

Related Topic