Saturday, January 23, 2010

Code Design Decision - Protecting Delegate Access?

Ran into this design desicion on one my engagements. Consider an abstract class implementation  that references a reference to another (delegate) object. Convenience methods are in the primary class class that are callled 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 accesss 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 accessf from consumer, as shown below?

.....
public void concreteMethod() {
...
delegate.methodCallA();
...
}

I answered this question by asking myself there was a chance that the associated object implementation would ever have to be replaced, or some kind of pre or post conditioning may be required? If there's 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 delegete 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 immediatly available for consumption.