Practices vs. Simplicity


Practices vs. Simplicity

I’ve been (slowly) reading Scott Bain’s book Emergent Design. I’m roughly halfway through it, and I agree with most of his views and recommendations.

I cannot agree with the practice of encapsulating the constructor, though.

Bain recommends making constructors private and adding static factory methods to classes when they will be used by client classes. This avoids the new keyword outside of the class, with the goal of reducing coupling and making the system more open-closed.

I completely agree with the goals of this practice, and generally agree with Bain’s underlying principle (separating use from construction). I disagree with making this a standard practice.

To be fair, Bain states that this is an “at least do this” practice, and that separate factories and other techniques may be used instead where appropriate. I still believe it is not appropriate for general use.

Being a fan of XP, I favor doing the simplest thing that could possibly work. Bain suggests that factory methods support adding subclasses at a later time. I would not add the factory until that time comes. This practice provides benefit only if the class with the encapsulated constructor becomes polymorphic. If we favor composition over inheritance, that’s not as common as it once was.

He talks about issues extrinsic to the client for determining which subclass to instantiate. He actually implies (p. 160) that coupling the factory method to a GUI might be acceptable! Don’t do it. The moment you do, your class with the encapsulated constructor becomes effectively untestable.

What’s more, I believe that extrinsic issues like configuration settings will tempt developers to use Singletons (read: global state) as “determiners.” Again, this makes for classes that are difficult to test.

So what would I recommend instead? Dependency Injection works well for me. This can be done simply through manual constructor injection. If the system is sufficiently complex, I introduce an IoC (Inversion of Control) container. This decouples my classes, makes them easy to test, and provides great flexibility.

An IoC container is not needed on every project. Neither are factory methods.

Update - May 3, 2009

I sent Mr. Bain a link to the post, and he was kind enough to respond in the comments. Please read his well-stated position. Again, we both have the same goals.

Update - June 21, 2009

See also: Mini-review: Emergent Design

Your Host:
Copyright © 2000-2013 by William Sorensen. All rights reserved.