the blog for developers

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 Context object in its constructor, when indeed it only depends on Engine, a violation of 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, hard to reuse and the Google testing team suggests refactoring the code.

Sometimes major refactorings are not possible. With IoC (Dependency Injection) 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();
     }
 }

You can leave a Reply here. Of course, you should follow me on twitter here.

You can share this post!
Do you want to tell others about this article? Use the social bookmark icons to submit this artice to the service of your choice. Thanks.

About the author: Stephan Schmidt is head of development at brands4friends. He has more than 15 years of internet technology experience and 10 years experience in agile. He was head of development, consultant and CTO and is a speaker, author and blog writer. He specializes in organizing and optimizing software development helping companies by increasing productivity with lean software development and agile methodologies. Want to know more? All views are only his own.
Leave a reply.

Comments

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.

stephan

@Doug: Of course you’re right, my error, passing in Context is IoC.

“Sometimes that’s not possible. With IoC this can be solved without (much) refactoring.”

Reading my post again, I didn’t write that passing in a Context is not IoC, just that IoC can solve the problem.

Leave a Reply

What people wrote somewhere else:

Additional comments powered by BackType

Guide to CodeMonkeyism

Over the last 4 years I wrote many articles on this blog. To make it easier for you to find the relevant ones, I've organized them into topics.

Top 10

6 reasons why my VC funded startup did fail

Go Ahead: Next Generation Java Programming Style

Java Interview questions: Write a String Reverser

The dark side of NoSQL

7 Bad Signs not to Work for a Software Company or Startup

Is Java dead?

Scala vs. Clojure

Never, never, never use String in Java

No future for functional programming in 2008 – Scala, F# and Nu

Clojure vs Scala, Part 2

Job Seeker

Another Good (Java) Interview Question

7 Bad Signs not to Work for a Software Company or Startup

Java Interview questions: Write a String Reverser (and use Recursion!)

Java Interview questions: Multiple Inheritance

As a Manager: What I value in developers

Top 10 Tips (+1) to Get a Pay Raise

Java Developer

Is Java Dead?

Go Ahead: Next Generation Java Programming Style

Be careful with magical code

All variables in Java must be final

Never, never, never use String in Java

Bending Java: More readable code with methods that do nothing?

Startup/CTO

Development Dream Teams

6 reasons why my VC funded startup did fail

American vs. European style of Software Development

12 Things to Reduce Your Lead Time and Time to Market

The high cost of overhead when working in parallel

Essential storage tradeoff: Simple Reads vs. Simple Writes

Agilist

What Developers Need to Know About Agile

5 Practices Better to Change in Your Scrum Implementation

Scrum is not about engineering practices

ScrumMaster and ZenMaster: The joke of certification

What is Trans-Scrum?