I love the idea of dependency injection. I started doing psuedo dependency injection on my own before I knew about DI because I was frustrated programming without it. I then discovered Guice. From a program design point of view, I like it a lot. Everything is much more decoupled and testable.

But from a programming perspective, I absolutely hate it. First off, using generics (because of type erasure) is a nightmare. Creating factories for everything that has paramatized constructors (basically everthing) is almost painfull. When I have a generic factory... I sometimes just stop programming and give up. It's too much boilerplate code. It's too much of a headache.

Am I doing something wrong? Should I have to create factories for vertually every class? Should generics really be this difficult to deal with? Am I doing something wrong!?

Recommended Answers

All 2 Replies

Excellent question! I'm going to need to do some thinking about this before I answer it better, though I'm not sure what this has to do with class factories. I wrote a generic class factory for C++ - create an instance of a class from a name or class id without needing to know anything about that class. When you compiled a class, it would register itself with the factory instantiator. I'm not sure if that is what you are getting at.

In any case, method injection (register a method with a class at run-time vs. compile-time) can be useful, but like most such constructs, usage when needed is good, but over-usage can, as you have seen, create real issues, especially with regard to code maintenance.

Perhaps the question to ask is, "Does the code calling the factory method need to know all the parameter values that the constructed object needs?" Typically, the answer is no. "But the constructed object needs to have dependencies injected into its constructor!" you object. True, but the Dependency Injection (and factory) code should worry about that. The factory method may have no parameters, but may get the values from its constructor (or elsewhere) to pass to the next constructor.

Also, in most systems I've seen, relatively few of the instances are created while the code runs. Most of the instances are darn near singletons, such that you can create them all up-front. So generally, very few factories are needed. Perhaps you could focus your efforts more on creating business logic components with DI, rather than focusing on creating data objects that way.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.