I have two classes Output
and Timeline
, neither of which violate SR, but the two of them are linked together. So what I’d like to do is have a class called Elco
(there’s a reason behind the name) that has both of them as subclasses. For various reasons (this is just a simplified version) it’s important that I don’t violate the LoD (Law of Demeter). The issue is that technically Elco
now has two responsibilities. It delegates those two responsibilities to two classes, which each have one responsibility. Is that not ok? Why? What’s a better solution?
2
Technically speaking, its a little hard to tell whether you are breaking Law of Demeter or not without actually looking at your implementation.
Based on the principle, as long as the object of Elco
is directly calling methods of Output
and Timeline
and not the methods of any other objects that are obtained by Output
and Timeline
, you are fine.
The problem, however, is that you are coding to an implementation and not abstraction i.e
In your code you will have conditions like:
if(someCondition)
call Timeline methods
else
call Output methods
A better approach to this problem would be to define an interface that both Timeline and Output implements. That way, Elco class only has to know about that interface and not about the implementing classes. Your code will then be:
methodCaller(CommonInterface f) {
f.interfaceMethod()
}
Each of the classes will then provide their own implementations to the method interfaceMethod
. This will decouple your code from its implementation, so that in the future you can plugin as many implementations of CommonInterface
as you want, without changing the above code.
3
To answer the question in your title: a class that only delegates to other classes can violate the single-responsibility principle, but does not do so necessarily.
To tell if your Elco
class violates the SRP, we would need to know more about its design and the reason you created it.
One dead give-away for breaking the SRP (and in my opinion, also LoD) is if you have a hard time thinking of names for the Elco
methods that do not reveal that it is just a thin forwarding wrapper to a similarly names method in Output
or Timeline
. Such names can be acceptable for a small percentage of the methods, but should raise a red flag if it happens for a significant number of them.
On the other hand, if Elco
provides a conceptually higher-level service that can be described in terms of operations on Output
and Timeline
, then Elco
does not violate the SRP and can be seen as an instance of the Facade design pattern.