OOP, Interface Design and Encapsulation
- by Mau
C# project, but it could be applied to any OO languages.
3 interfaces interacting:
public interface IPublicData {}
public /* internal */ interface IInternalDataProducer { string GetData(); }
public interface IPublicWorker {
IPublicData DoWork();
IInternalDataProducer GetInternalProducer();
}
public class Engine {
Engine(IPublicWorker worker) {}
IPublicData Run() {
DoSomethingWith(worker.GetInternalProducer().GetData());
return worker.DoWork();
}
}
Clearly Engine is parametric in the actual worker that does the job. A further source of parametrization is how we produce the 'internal data' via IInternalDataProducer. This implementation requires IInternalDataProducer to be public because it's part of the declaration of the public interface IPublicWorker. However, I'd like it to be internal since it's only used by the engine.
A solution is make the IPublicWorker produce the internal data itself, but that's not very elegant since there's only a couple of ways of producing it (while there are many more worker implementations), therefore it's nice to delegate to a couple of separate concrete classes. Moreover, the IInternalDataProducer is used in more places inside the engine, so it's good for the engine to pass around the actual object.
I'm looking for elegant ideas/patterns.
Cheers :-)