Friday, November 2, 2007

Class Dependencies and the Factory Pattern

I listened to a Podcast this morning from Software Engineering Radio on Dependencies. In the context of this podcast, dependencies refers to the relationship between objects. The problem discussed was the lack of support for these object relationships in today's OO languages.

I wanted to touch on one specific topic covered in the podcast; the negative effect on dependency visibility that can come from a... misguided?... use of the Factory pattern.

Here's the problem:

Pretend you have a factory that exposes, lets say, 10 objects. And you have a class that uses the factory to obtain 3 of those objects. Without having intimate knowledge of the class or searching the class's implementation for "Factory.getXXXXXXX()", it's impossible to tell exactly what objects an instance of the class depends on. What you end up with is a spider-web like architecture. Many classes depend on the Factory which in turn depends on many classes itself.

So, what's the solution?

One possibility is to enforce a 1:1 ratio between factories, and classes using a factory. If Class A depends on instances of Class B and Class C, the factory Class, FactoryA must only expose instances of Class B and Class C. Also, Class A must only use FactoryA. Doing this provides confidence that all objects exposed by the factory are dependencies of the class.

Another possibility would be implementing Dependency Injection. If you go with constructor injection, class dependencies are visible as parameters to the constructor. If you go with setter injection, all dependencies are visible via the setter methods.

Food for Thought
1. Is Dependency Injection an alternative to Factory Pattern?
2. Does this problem also arise in the use of Service Locator?
3. What do you gain with clear dependency visibility?

No comments: