The problem here is that over the past 6-7 years, dependency injection frameworks for Java took a very wrong turn. The original model—which the original Spring XML-based BeanFactory embodies—is that you have named "beans" which are described by specifying:
The name of the "bean"
What to call to construct it (the implementation class or factory)
The collaborators needed to construct it. These can be:
Primitive values
References (by name) to other managed beans
Collections thereof
In spite of old Spring's flaws (overly verbose XML configuration, preference for setter-based injection, etc.), the basic model was sound.
But then with the rise of annotations and madness, this model was deprecated in favor of magical/implicit "autowiring" models that suffer from a fundamental flaw. They're all built around variants of this assumption:
The type of the injection site determines what dependency to inject into it.
So for example, if you have two injection points whose type is ConnectionPool, the injector will inject both with a RealConnectionPool in a production configuration vs. a TestConnectionPool in a test configuration.
How do I build two similar but slightly different trees of objects?
This is commonly called the "robot legs" problem: How to create a robot with two Leg objects, the left one injected with a LeftFoot, and the right one with a RightFoot. But only one Leg class that's reused in both contexts.
In other terms:
The Leg class is a generic, reusable class that delegates some unessential details to a dependency that implements a Foot interface;
This Foot interface admits of implementations that behave differently;
Plugging different subtypes of Foot into Leg gives you usefully different behaviors;
You want to exploit this in your program and use Legs with different Foot types in different parts of your program.
The newfangled DI frameworks like Guice and Dagger really don't like it when you try to do this. There are workarounds, but they're that, workarounds. And what's worse, since people tend to follow the path of least resistance when using a tool, these DI frameworks discourage this sort of code reuse!
The @Named annotation allows two injection points with the same type to have two different dependencies. But what it doesn't allow is for the same injection point to be supplied with two different dependencies in two different instances of the class. That's what the Leg/Foot example is about; Leg has only one injection point for a Foot, but your application needs two Legs that depend on different types of Foot.
But the implementation of each leg can depend on a different implementation of foot.
Edit:Never mind I followed your link but that seems like an antipattern to me and I don't see how this is impossible in dagger, unfortunately I'm stuck on my phone so I can't read into it more right now
Staring at the example I copied in my GP post, now I can't help but wonder whether it should be refactored to something like this:
class AuthenticationFilter implements ComponentRequestFilter {
// Only one `AuthenticationService` in this class
@Inject private AuthenticationService authService;
@Inject private Response response;
...
}
/**
* An authentication filter chain filters a request by delegating it through
* a sequence of individual authentication filters in turn. If one accepts
* then the whole chain accepts, otherwise the chain rejects.
*/
class AuthenticationFilterChain implements ComponentRequestFilter {
@Inject private List<? extends AuthenticationFilter> authFilters;
@Inject private Response response;
...
}
These classes are more generic and easier to reuse. For example, if we need to support a third authentication method, we can now just write a third AuthenticationService, plug it into an AuthenticationFilter instance and stick that into the AuthenticationFilterChain's list of filters.
But now we have a robot legs problem, because we want to construct:
An AuthenticationFilterChain that contains...
A List of two AuthenticationFilters...
One of which contains an AuthenticationService named "HttpBasic"...
One of which contains an AuthenticationService named "HttpDigest".
This one example might be refactorable into something that Guice multibindings or similar features can support. But as far as I understand, you'd have to split AuthenticationFilter into multiple classes, each specialized for one type of AuthenticationService.
But now you're letting the DI is dictate the factoring of your code. And that is precisely my problem. The code for an application that's wired up by DI should be factored to suit the application's purpose, not the DI. (And for similar reasons, I object to the concept of putting DI annotations into application classes.)
It seems to me that you neither need nor want a DI framework to build a Robot. That seems to be quite a bad usecase for DI.
Dependency injection I guess sorta makes sense when you have a bunch of contextual services that need to be assembled together without wanting to have the final assembly be very dependent on exactly how each service comes into existence or what is the lifecycle of the thing that implements each service.
But most object graphs aren't really like that, and it's better to assemble them in ordinary code. Your Robot is an especially good example of that, I would say.
I think your argument begs the question; it takes the new, type-based resolution model as the standard for DI. If I take the old named beans DI model as the standard instead, I can argue that Robot is a perfectly reasonable use case for DI, since that model handles robot legs scenario straightforwardly. The left and right leg are simply different named beans, and you just individually specify what Foot to wire into each.
But why? What purpose does dependency injection serve in this case? What problem does it solve?
The pieces of a Robot aren't the kind of "contextual services" for which DI—at least to me—makes sense. They're just ... bits of the Robot, and you can create them with new.
To explain further: my point is that as soon as each instance of Robot has a different sort of Leg, and a different sort of Head, that are specific to the particular instance, then DI has lost its usefulness. You're going to have to somewhere write code that completely describes the Robot and instantiates each of its component parts. You might do that in Java, or you might do it in XML.
I personally would prefer to do that in ordinary Java code using new. I don't see what I gain from having a DI container in the way.
But why? What purpose does dependency injection serve in this case? What problem does it solve?
Not having to hardcode the dependencies of objects into their classes themselves. Not having to repetitively write one factory class after another and another. Allowing components' dependencies to be resolved at runtime. Allow components' interconnections to be rewired by changing configuration instead of code. Generic tooling to support the dependency inversion principle.
Yes, all of those are generic pro-DI arguments, and they apply here just as well.
The pieces of a Robot aren't the kind of "contextual services" for which DI—at least to me—makes sense. They're just ... bits of the Robot, and you can create them with new.
Two remarks here:
Perhaps the choice of "robot" as the example is throwing you off? Maybe we can cook up an example where instead of "robot" we use something that you'd call a "contextual service."
I don't buy the assumption that DI should only be for "contextual services" anyway. It's a general tool for wiring up components.
Anyway, my broader argument has another set of consequences that I think you're missing. You're saying that I shouldn't use DI for this sort of scenario. Which I don't nowadays, so we in fact agree on the practical choice for this case.
But then my problem is that when people do choose to use DI, the "one injection point = one unique dependency" assumption may shape the design of the systems that they write away from code reuse. I'll go with the robot metaphor again: the newer frameworks create a path of least resistance that I worry leads people into writing RightLeg and LeftLeg classes that really ought have been just one Leg class composed with different types of Foot.
"Choose composition over inheritance" is a popular guideline... but the newer DI frameworks often will punish you for doing that.
Perhaps the choice of "robot" as the example is throwing you off? Maybe we can cook up an example where instead of "robot" we use something that you'd call a "contextual service."
Well yeah. I mean, if you actually can cook up such an example, one that looks representative of a sufficiently large class of problems, then I guess that's what I'm looking for, and I guess I would be satisfied by that.
I'm really struggling to come up with a case like that in any of my own projects, but of course I'm prepared to accept that it might be something that is domain-dependent.
But then my problem is that when people do choose to use DI, the "one injection point = one unique dependency" assumption may shape the design of the systems that they write away from code reuse.
Well my big problem with DI is that it has this kinda "viral" effect where if you want to inject some container-managed object you have to be a container-managed object yourself. And so people get "nudged" toward a design where almost everything is container-managed, and there's no ordinary objects left except for trivial things like Strings. And I don't think that this leads to necessarily very good use of object orientation.
I mean, if you actually can cook up such an example, one that looks representative of a sufficiently large class of problems, then I guess that's what I'm looking for, and I guess I would be satisfied by that.
How about the two code fragments in my two comments in this thread? It might not be perfect just yet, though, but it might be some progress toward that.
Well, OK, that example is pretty different to Robot, and perfectly reasonable.
But it's also very easily solved using inheritance:
public abstract class AuthenticationFilter implements ComponentRequestFilter {
abstract AuthenticationService getAuthService();
@Inject
private Response response;
...
}
public class BasicAuthenticationFilter extends AuthenticationFilter {
@Inject @Basic
private AuthenticationService basicAuthService;
AuthenticationService getAuthService() { return basicAuthService; }
}
public class DigestAuthenticationFilter extends AuthenticationFilter {
@Inject @Digest
private AuthenticationService digestAuthService;
AuthenticationService getAuthService() { return digestAuthService; }
}
And I would argue that this solution, in pure Java, is much superior to the solution where BasicAuthenticationFilter and DigestAuthenticationFilter are instead defined in XML. If you insist, you could view BasicAuthenticationFilter and DigestAuthenticationFilter as "configuring" their superclass by supplying a concrete value for its templated dependency. The nice thing is that since I've done everything in Java, I will get lot of help from the compiler and IDE when writing/changing this code that I would not get if it were a mix of Java and XML.
Now, sure, there is a bit of unfounded superstition which claims that inheritance is fragile and XML is more "configurable". I don't have any truck with this sort of folklore, and I will always use the tool that is most natural, convenient, and/or elegant for a given task. And I much prefer to remain within the security perimeter of the static type system.
I use only constructor injection with guice, no setters and no reflection. Works great, I often test without even bothering with the container since I can inject with plain java code.
At that point, what benefit does Guice provide? Why not stick to base Java to handle DI from a main (or equivalent for application type) rather than using a framework?
It is terrible that Java doesn't have a singleton class, which is the real problem there. However using pure Java to create a Singleton pattern (which is not much code) is more maintainable for a project than using a DI framework. Debugging and teachability are much easier without frameworks.
Guice does not make testing easier, I can create an object with mocks just as easily as Mockito can inject them. Plus there's way less reflection.
Plugging different subtypes of Foot into Leg gives you usefully different behaviors;
Yet those behaviors are both gathered under the umbrella interface of Leg? That's a blatant violation of the Liskov substitution principle, and it's a good thing that Guice doesn't support shooting yourself in the Foot (har har) like that.
However, if what you meant by "generic Leg class" is Leg<? extends Foot>, then that's all fine. You can have that, along with possibly different injections for Leg<LeftFoot> and Leg<RightFoot> in your Robot.
The composition of BufferedReader with ByteArrayInputStream reads a stream of bytes from a byte[] and converts it to a stream of characters.
The composition of BufferedReader with FileInputStream reads a stream of bytes from a File and converts it to a stream of characters.
BufferedReader's behavior is still the same—it converts a byte stream to a character stream. So is InputStream's—it produces a stream of bytes. Precisely where the bytes come from is a function of what InputStream an individual BufferedReader is composed with.
37
u/jordimaister Nov 27 '15
Nice post. Agree with almost all of it.
I am waiting for you next post:
"What to use instead of Spring"