Saturday, September 08, 2007

Problems with Dependency Injection

I'm having an issue with Dependency Injection that I need some clarification on.

I have a static factory method that takes a parameter:


public static GeographicalMap createGeographicalMap(String inputMap) throws DuplicateRoadException {
    GeographicalMap map = new GeographicalMap();
    map.initialize(inputMap);
    return map;
}



Its perfectly possible to use static factory methods in most DIF's. The problem is, the parameter won't be known until runtime, so it can't be configured before runtime. So, how can an object that uses a GeograpicalMap have the GeographicalMap injected into it?

One solution is to remove the "known at runtime only" parameter from the static factory method, and expose the initialize method. The client code then becomes:



GeographicalMap map;
public GeographicalMap getGeograpicalMap{ return map; }
public void setGeograpicalMap( GeograpicalMap map ){
    this.map = map;
}
public void someMethodThatUsesMap(){
    map.initialize(inputMap);
    map.doSomething();
}



This does not sit well with me at all. I have to break encapsulation, and return an object that is not fully initialized. Clients have to remember to initialize the map before using it, precisely the reason why I added the static factory method to begin with. (As a simple side note, I prefer static factory methods over constructors for readability.)


I'm certain someone must have solved this issue without violation OO principles so badly. I am determined to find the right answer.

No comments:

Post a Comment