Using Google Guice Providers to Solve Law of Demeter Problems
A post on the Google testing blog made me think. Their post presents an example of a class
class Mechanic {
Engine engine;
Mechanic(Context context) {
this.engine = context.getEngine();
}
}
which depends on an object Context in the constructor, when indeed it only depends on Engine, a violation the law of demeter. This often happens with Context objects which play the role of a central object repository to give access to objects in different parts of an application. The resulting code is hard to test and hard to reuse and the Google testing team suggest refactoring the code.
Sometimes that’s not possible. With IoC this can be solved without (much) refactoring.
For example with Google Guice one can write a Provider that provides an object of a given class, in this case Engine.
public class EngineProvider extends Provider<Engine> {
private Context context;
@Inject
public EngineProvider(Context context) {
this.context = context;
}
public Engine get() {
return context.getEngine();
}
}
Binding the Provider to Engine,
bind(Engine.class).toProvider(EngineProvider.class);
the application will use the provider (probably from the @Request scope) to extract the engine from the context. The Mechanic can be rewritten to use Engine directly, but no other code in the potentially large application needs to change.
class Mechanic {
Engine engine;
@Inject
Mechanic(Engine engine) {
this.engine = engine;
}
}
Thanks for listening.
Update: Are more clever Provider could support the NullObject Pattern.
public class EngineProvider extends Provider{ private Context context; @Inject public EngineProvider(Context context) { this.context = context; } public Engine get() { if (null == context ||context.getEngine() == null) { return new NullEngine(); // better Engine.NULLOBJECT } return context.getEngine(); } }
To be picky about terminology, passing a Context object IS a form of IoC. It’s what used to be called “Type 1″ IoC, or “Contextualized Dependency Lookup”. It’s not Dependency Injection, but it IS Inversion of Control. (One could argue that the dependency on the injected context qualifies as DI, but I don’t think that argument would win many supporters.) As noted, it’s harder to test than DI is.
As for the Law of Demeter, I say “ptthht.” There are some places where it’s a reasonable guideline, and many places where it isn’t. The real problem with passing a Context object instead of an Engine object is one of increased coupling: the method is not only coupled to the Engine class but to the Context class as well.
July 24th, 2008