Tuesday, February 20, 2018

The Perils of Dependency Injection

When we worked with the Java Spring Framework (4.3 at the time) one of the things we had to adjust to was the fact that rather than have a J2E app server spring provided access to our realized objects through their dependency injection framework.

Now this is a lot like Windows versus linux. One time windows insisted on installing a security patch even though I had done everything I could possibly do to turn that off. So my computer rebooted twice, took several hours at load time with a threat "dont turn off!" and finally died altogether.

The idea of the computer taking control from you and believing "I know best" is really a new thing. One of the few pleasures we used to have was that computers unlike wives only did what we told them to do.

Now Spring is a lot like that. One of the first things that was confounding was what classes which used other classes which used other classes could actually be injected. This often wasn't as obvious as possible or predictable. Several times simple atomic classes which used other injects were not allowed. Why? This made no sense. It had to do with the internal class representation they had hacked into their injection representational model classes. It didn't have to make sense.

Another big issue which I think I mentioned before is how in the case of errors, again Spring would intercept the exception and re-wrote it to the callers callers callers class. The first time I tried to fix it with simple encapsulation. No dice it was thrown above that. Then we put in another set of classes specifically to get the throw. Nope still no dice. Finally we had a fully artifical layer calling a fascade calling into the classes. This made the code very hard to read and maintain. Why were we doing this? One developer suggested removing all this unnecessary code. Another did something similar the day of the big demo.

Now why WHY is this dependency injection stuff so high on the hog? I can always predict the classes I need from a constructor factory and have the same abilities. I've never had issues with getting hit with a new class type it just never comes up. Well a lot of it has to do with the MOCKIT or MOKITO type of testing. Testing can be difficult with the requirement to be in a fully live system. By using Mock object injection you can spoof your system to make it think its live and still test the function with the right state, say for example an object that has a handle which must be set by the system.

Again, yes useful, but real system tests always prove better. And rarely have I seen mockit object testing done well or ubiquitously it simply takes too long to setup.

Dependency injection seems like something they realized they could do, without actually looking at the pattern of use. does it have its place on some projects? Perhaps. But I advise caution.

No comments:

Post a Comment