Dependency Injection – 3 Questions!

Normally the reason why I write blogs is to inform other people about interesting things I found or I am thinking about. Today I will ask some questions and wait for your answer ๐Ÿ˜‰

One of my latest posts was about the spring rich client. Because of this project and picocontainer I read a lot about design patterns. The most obvious design pattern in spring is called dependency injection. This design pattern helps the software architect to loosly couple components. It could work like follows (just for the JSE-developers under us):

class ClassA {
MyInterface objectA;
public void setMyInterface(MyInterface objA) {objectA = objA;}

where we could have defined the interface like this:

interface MyInterface{ String toString(); }

Now, ClassA defines a dependency on an instance of MyInterface and the framework (for Java e.g. picocontainer, spring, juice or others) will inject an instance of an implementation of MyInterface into ClassA. It is up to the configuration if objA is a newly created instance or if it is a ‘singleton’. (MyInterface could be a class as well.)

For example if you call

ClassA classA = framework.getBean(ClassA.class); //code is similar to picocontainer; not to spring!

You will get back an instance of class ClassA, where objectA is not null! The dependency was defined by the method (setMyInterface) – this is called setter injection. Other kinds of injections are:

  • annotation-based injection:
    class ClassA { @Inject Object objectA; }
  • constructor injection:
    class ClassA { Object objectA;
    public ClassA(ObjectA objA) {objectA = objA;}

Where picocontainer campaigns for constructor and spring for setter injection (but both projects offer at least the mentioned kinds of injection).

It is correct that you can create your own small framework or even set up the objecs by hand to achieve the same: dependency injection. But I guess you are lazy and will choose one of the open source frameworks.

Now, all is explained to understand my 3 questions. Hopefully someone out there will have an answer!

1. How should I design a library?

Let me explain. You want to sell a nice designed, but complex library. The library offers a lot of functionality and you want to split it into loosly coupled components. That means you have to use dependency injection (DI), but you don’t know if the customer has or wants such a DI-framework.

So, if you use e.g. the annotation-based injection it would be nearly impossible for the customer to use your library; with setter or constructor injection it is quite difficult to set up the objects for using your library.

I don’t know what to do: Should I really use dependency injection here? Or should I use a (dynamic) service locator instead; to decouple my components within the library?

Martin Fowler says:

“It (dependency injection) tends to be hard to understand and leads to problems when you are trying to debug. […] This isn’t to say it’s a bad thing, just that I think it needs to justify itself over the more straightforward alternative (service locator).”

A common reason people give for preferring dependency injection is that it makes testing easier. The point here is that to do testing, you need to easily replace real service implementations with stubs or mocks. However there is really no difference here between dependency injection and service locator: both are very amenable to stubbing. I suspect this observation comes from projects where people don’t make the effort to ensure that their service locator can be easily substituted.

“So the primary issue is for people who are writing code that expects to be used in applications outside of the control of the writer. In these cases even a minimal assumption about a Service Locator is a problem.”

So: What would you do? Would you use a service locator or dependency injection inside the library?

And this leads me to the next important question:

2. Why is a singleton an antipattern?

I stumbled over this question while I used picocontainer. They say you have to avoid singletons, because it is difficult to test and to replace. My question is: why? Imagine the following singleton:

class LogFactory{
public static Logger getLogger(Class clazz) { … }

Now it is really easy to replace the implementation of the Logger interface e.g. if one defines a setImpl method:


So what’s soo wrong with a singleton?

3. How can I avoid making all classes public?

I don’t know if it is the case for autowiring in spring. But in picocontainer you have to set-up the configuration for the wiring of the classes by yourself e.g. in a separate class (with Java; no xml! compiler checks references! yeah!) or in a separate file with a scripting language (or xml) and nanocontainer. That means you could specify the implementations of the interface by:

framework.setImpl(MyInterface.class, FirstImpl.class);

But wouldn’t it mean that I have to add the modifier public to the class FirstImpl? (To let picocontainer call the default constructor.) This can’t be good design to allow the user of my library to see the implementations of MyInterface.

Whats wrong with my use case and my conclusion?


6 thoughts on “Dependency Injection – 3 Questions!

  1. These are good and useful questions to ask. They really get at API design as much as dependency injection. My answers would be:

    1) Design around interfaces and (minimally) factories. Consider the principle of hard/soft layers. Your library can use injection heavily internally but expose a smaller set of choices through a smaller API at the top. This all depends on what you’re doing of course.

    2) I’ve written quite a lot about this ( but my take is that the notion of something that exists only once in your system is not inherently bad. The class Singleton pattern in Java is bad. Singleton-by-configuration is ok.

    3) Rely on interfaces and factories, not on impls. These days I generally care a lot less about public/package/private. If you design your packages and interfaces well, it will be clear what’s public and what’s not. (See Eclipse convention of .internal packages for example.)

  2. Hiya,

    The short answer is: definitely use Dependency Injection.

    I feel your pain. It is difficult when you have a large library where people may need access to a number of the objects within your library but you’d like to have a single interface into the library.

    Either setter or constructor based injection works fine.

    1. Make sure that all of your objects are DI capable because it is very likely that people will want to configure your library in different ways.

    Instead of using a ServiceLocator (which will tie users of your library to your ServiceLocator class), try and create 3 or 4 large composite objects that are preconfigured in what you’d consider a standard sense. By large, I mean for example:

    interface IA { void doA(); }
    interface IB { void doB(); }

    class A implements IA {…}
    class B implements IB {…}

    class LargeAB implements IA, IB {
    private A a; private B b;
    void doA() { a.doA(); }
    void doB() { b.doB(); }
    public LargeAB() { /** configure a and b **/; }


    Singleton is definitely an antipattern. And yes, even for logging it’s an anti pattern, just one that is so widespread that it’s painful to avoid. The reasons are:

    a. you may want to use a different implementation in different parts of your project but a singleton forces you to only have one implementation. this is true for logging as well as many other libraries that Java loads from things like (XML parsers etc.)
    b. you may want to use a different implementation for two intances of exactly the same class, singletons stop you doing that i.e. singletons significantly reduce reusability.
    c. your classes hide their coupling, i.e. you only know that you class depends on the singleton by looking at the source code. with constructor based, and slightly less so with setter based DI, you know what your class depends on. With constructor based it’s compiler enforced, with setter based it’s obvious from the documentation.

    3. Make them public. In my 10 years of programming Java including 1 bank, 1 ISP, 1 large mobile operator and several high profile open source projects, I have never had a situation where I’ve written a library or seen one written where I was was unhappy that a constructor was public instead of private. There have been many, many times, I’ve been unhappy that either I or someone else had used a singleton.

    Other preferences: Spring over Pico or Guice. Setters or Constructor injection over annotations. I also like wiring objects using Java if I can.

  3. While reading all your useful comments I got another point:
    And one big drawback of a singleton is threading! Either the singleton is not thread-save or you can get performance problems, because of synchronization.

    @ Alex Miller: >>The class Singleton pattern in Java is bad.
    What do you mean with ‘the class singleton pattern’?

    Good article, I picked up some phrases here:
    1. A Singleton hides dependencies (like SL do as well)
    3. Hard to subclass
    (But you could make it replaceable with setSingleton, right?)
    4. It’s a lie: Singletons in Java are based on static variables, which are held per-classloader, not per-VM.
    5. A singleton today is a multiple tomorrow – Itโ€™s not at all unusual to discover that you now need 2 or more of something you previously only needed one of.

    See the Javalobby repost for more comments:

    from Ronald: … the Service Locator requires the calling class to have enough ‘information’ about the dependency to make the lookup. For example, if you just ask for an object of type ‘T’, and your Service Locator may contain references of two implementations, how do you resolve this?
    (With ‘enough information’ he means e.g. passsing a string to the SL call to choose the right implementation.)
    Other solution is configuring the Service Locator to return a specific instance when called from class A, and another from class B (could it be named ‘Locator-based Injection’? :D).
    (My note: Yes you are right, this will be really ugly.)

    from Steven: If you give people the parts to wire up [for DI] they can easily write the code themselves, or if you want to make it easier for them, create some simple bootstrap classes to do it for them.

    Now my notes:
    1. avoid singletons
    2. do not configure everything with DI, but prefer this pattern. from Ronald: ‘there is no one-size-fits-all’
    3. maybe Java should remove the keyword ‘static’ from its language specification ๐Ÿ˜‰

  4. Pingback: DZone weekly links #3 | Sergi Castillo

  5. DI is fine in my opinion as long as the parameter is an interface that allows you to pass an already constructed object to the method. This allows you to hide the implementation details of the object that implements said interface.

    Singleton is generally a pain and does little for you, but there are times when it is valdid and usefull, such as an application wide caches in a multi-threaded server ( comes to mind)

Comments are closed.