I ran into a design decision on one my engagements. Consider an abstract class implementation that references another (delegate) object. Convenience methods are in the primary class that are called by concrete classes. This pattern can also exist in a concrete that delegates to another implementation.
public class AbstractClass{ private Delegate delegate; void methodCallA() { delegate.methodCallA()); void methodCallB(String arg) { delegate.methodCallB()); }
This is a common idiom applied to the service/dao pattern, where a DAO delegate would never be exposed to consumers using a service instance. However, in my situation I was implementing a framework solution outside of data access, and was mulling over how far to go with hiding access to the delegate instance.
The idea is to provide access to the referenced object only from abstract class methods. However, as this design evolved, sometimes it seemed cumbersome to have to define an additional method in the abstract class, so I asked myself should I always hide delegate access from consumer, as shown below?
public void concreteMethod() { ... delegate.methodCallA(); ... }
I answered this question by asking myself:
Is there a chance that the associated object implementation would ever have to be replaced?
Is there a chance that some kind of pre or post-conditioning may be required?
If there is a chance, then protecting access to the delegate with access methods is worth the extra method definitions in the based class. However, this assumes only the delegate is only providing a few methods for the base class, if more than 7ish methods, then it would be cleaner to eliminate the base class access methods, and let concrete classes access the delegate directly.
If the conditions are met above, then allowing public access to the delegate can shorten the number method implementations, and new methods defined in a delegate are immediately available for consumption.
–David Pitt, [email protected]
About David: I’ve been developing software for 25 years. Got bit by the Object Oriented (OO) bug in the early 90’s with Smalltalk. Ever since I been helping corporate software developers utilize object oriented design and construction to deliver robust high quality software on time and under budget. Post originally published January 23, 2010. Edited and re-published Dec 5, 2011.