Say you have interfaces IBuilding and IDwelling, and class House which implements both. It encapsulates a building and a dwelling:
class House implements IBuilding, IDwelling
{
private IBuilding building;
private IDwelling dwelling;
}
If IBuilding and IDwelling each define 15 methods, is it really normal to write 30 methods in the House class that just forward to the methods of the door or window?
That seems very, very tedious. Is this really a thing? A lot of resources indicate that, yes, that’s what you’d do, but they all use super-simple examples that don’t make it look as daunting as I imagine it would be in real life.
Or is there some smarter way to compose that I’m not aware of?
Does it have to be this tedious? No. Is there any smarter way? Yes.
There are 3 reasons I can think of why You would use the composition:
Of the three, only case #2 may require that You forward every call from Your wrapper class to the wrapped one. Even so, there are some languages that may allow You to create a so called “dynamic” proxy, so that You don’t have to create a method in Your outer class for every method in Your inner class just to forward the call. For example, in Java it’s called the
Dynamic Proxy Class, in PHP it’s the magic__call()method.Another thing is that situations like the one You described in Your question are very rare in practice.
UPDATE
The main problem here is that while using PHP if we want the wrapper class to implement the wrapped class’s interface, the
__call()method, indeed, can’t really help us. If the interface has few methods, it’s not difficult to implement them, but what if it has 15? This problem, I believe, is not a problem of the composition, it’s a problem of big interfaces. To avoid such problems You need to follow the Interface Segregation Principle. Sometimes, though, if You’re writing a general purpose API it’s hard to follow the principle. If this is the case, then there’s nothing else left You can do except for one-to-one mapping of method calls. Sorry.