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();  
     }  
 } 

Stephan Schmidt Administrator
CTO Coach , svese
Stephan is a CTO coach. He has been a coder since the early 80s, has founded several startups and worked in small and large companies as CTO. After he sold his latest startup he took up CTO coaching. He can be found on LinkedIn or follow him in Twitter.
follow me