Re: DI/wiring
On 4/18/13 9:03 AM, Stefan Ram wrote:
I have ?invented? myself something that also seems to be
known as ?dependency injection? or ?wiring?. I am doing it
in pure Java SE without any framework, for example:
I think "invented" is the wrong word here. Discovered? Uncovered?
Migrated toward? Maybe reinvented.
component0.acceptPrinter( printer0 );
component0.acceptEngine( engine0 );
component1.acceptPrinter( printer0 );
component1.acceptEngine( engine0 );
component2.acceptPrinter( printer0 );
component2.acceptEngine( engine0 );
Why aren't those simply setters? Must you go against all convention in
every possible way?
. Now, however, every component needs to have all that
boilerplate code like an implementation of ?acceptPrinter?
and so.
Most IDE's will generate getters/setters for you automatically. Yes, it
is boilerplate, but it is useful to have such explicit declarations.
The whole project would need much less boilerplate, if
I would just do:
Globals.printer = printer0;
Globals.engine = engine0;
and every component that needs the printer or the engine
would just use ?Globals.printer? or ?Globals.engine?, just
as we use the ?global? ?java.lang.System.out?.
Some people, however, frown upon such globals. But would
it be that bad?
It depends on the scope of your project, the size of your team, and the
expected lifespan of the product.
For a small project with a one person team for a product which will last
a week, that's absolutely fine.
For any other combination, it *will* cause problems at some point. A
new feature will require component0 to use a different printer than
component2, and component1 uses a different engine. Or, someone will
unwittingly change the value of a Global value, and effect more than
they intended. Especially if this ends up being concurrent code.
java.lang.System.out is global accessible because it truly is a global
entity. It isn't just "an output", it is *the* system's output. I
wouldn't want to use it in most code directly, but instead pass around a
PrintWriter, PrintStream, or even an OutputStream. That way, if the
main program wants to redirect the output of the library, it can do so
with no hoops to jump through.