Dependency Injection Addiction? - dependency-injection

Is there a down side? I feel almost dependent on it now. Whenever a project gets past a certain size almost feel an allergic reaction to standard patterns and immediately re-wire it with a Dependency Injection framework.
The largest issue I've found is it can be confusing for other developers who are just learning it.
Also, I'd feel much better if it were a part of the language I was using. Though, for Java at least, there are a couple very lightweight libraries which are quite good.
Thoughts? Bad experiences? Or just stop worrying about it?
[EDIT] Re: Description of Dependency Injection itself
Sorry for being vague. Martin Fowler probably describes it FAR better than I ever could... no need to waste the effort.
Coincidentally, this confirms one point about it, that it's still not widely practiced and might tend to be a barrier when working with teams if everyone is not up to speed on it.

I've taken a stab at describing some of the possible downsides in a blog post here: http://kevin-berridge.blogspot.com/2008/06/ioc-and-di-complexity.html

The problem I have with DI is the same problem I have with COM and with any code that looks something like:
i = GetServiceOrInterfaceOrObject(...)
The problem is that such a system cannot be understood from the code. There must be documentation somewhere [else] that defines what service/interface/object can be requested by service/interface/object X. This documention must not only be maintained, but available as easily as the source.
Unless the document is very well written, it's often still not easy to see the relationships between objects. Sometimes relationships are temporal which makes them even harder to discover.
I like the KISS principle, and I'm a strong believer in using the right tool for the job. If the benefit of DI, for a given project, outweighs the need to write comprehensible code, than use it.

Also, I'd feel much better if it were
a part of the language I was using.
FYI there is a very simple and functional dependecy injection as part of JDK 6. If you need lightweight, straightforward dependency injection, then use it.
Using ServiceLoader class you can request a service (or many implementations of the service) based on a class:
package dependecyinjection;
import java.util.ServiceLoader;
public abstract class FooService {
public static FooService getService() {
ServiceLoader<FooService> loader = ServiceLoader.load(FooService.class);
for (FooService service : loader) {
return provider;
}
throw new Exception ("No service");
}
public abstract int fooOperation();
}
package dependecyinjection;
public class FooImpl extends FooService {
#Override
public int fooOperation() {
return 2;
}
}
How does ServiceLoader defines the service implementations that are returned?
In your project folder create a folder named META-INF/services and create a file named dependencyinjection.FooService. This file contain a line pointing to the service implementation. In that case: dependecyinjection.FooImpl
This is not widely known yet.

I am big beleaver in IO however I saw some projects with huge xml configuration files which no one understand. So beware of programming in xml.

In my opinion, the major drawbacks are the learning curve (as you point out) and the potential for the added abstraction to make it more difficult to debug (which is really part of the learning curve as well).
To me, DI seems to me to be more appropriate for larger, complex systems -- for small one-off apps, it may result in the app being over-architected, basically, having the architecture take more development time to adhere to than it can ever make up for in the value it provides.

Just stop worrying about it. It's my opinion that in time IoC techniques will be second nature to most developers. I'm trying to teach devs here at work about it and I find it difficult to get the message across because it feels so unnatural to the way we've always done things.. which just so happened to have been the wrong way. Also, developers both new to IoC and new to a project I find have an even more hard time. They're use to using the IDE to follow the trail of dependencies to gain an understanding of how the whole thing "hangs together". That information is often written into arcane XML.

Could you add a link or two to explain what Dependency Injection actually is, for those of us playing along at home? The wikipedia article is entertaining, but not very enlightening.

The only down side I can think of is tiny performance decrease through constant virtual calls :)

#Blorgbeard: http://www.martinfowler.com/articles/injection.html is probably one of the best articles on the subject

Related

How to mock a third party Assembly (XNA/MonoGame) in c#

So, I've started playing around with MonoGame, and one of the things I have noticed is that it will be really hard to unit test it.
I could use something like shims in microsoft fakes but as this blog points out http://blog.pluralsight.com/vs11-fakes-framework, it's not really the TDD way.
I could also use something like Duck Typing which is perfect for everything bar the static methods, but there are a huge number of static methods...
I could write adapters for everything, and I'm doing that currently but I've spent a huge amount of time writing adapters and very little writing actual code, which is frustrating.
Final option I can think of is generating the adapters, which seems like a reasonable idea, except I can't find any tool to do it, I mean I'm happy enough to write something that does it, but it seems like one of those problems that has probably been solved already in a better way.
Anyone have any ideas?
The general advice is "don't mock what you don't own" and write adapters that you can mock for unit testing your code and a few integration tests for the adapters and the third party code. Usually you try to keep adapters as thin as possible, but in the case where your code depends on many entry points in the third party code, forcing you to write many adapters, it may be worthwhile to look for an intermediate abstraction that your code depends on, that can be implemented by a few adapters that are a bit "thicker", i.e., that are not 1:1 with the third-party code, but provide some higher-level functions.

Would it be safe to rely on DeHL for new projects?

I've been browsing the DeHL repository on GoogleCode, and it looks really good to me.
Many interesting features that make basic programming tasks easier; Some neat things that are in the DotNet FCL, but are missing from the Delphi RTL can be found in this library;
Coded in a modern way, making good use of new language features;
Each class, record type, member function and parameter is documented in such a way that it'll show in the code completion of the Delphi IDE;
Well-organized and clean code;
Plenty of unit tests;
Open source and Free;
Basically, it looks like this library should've been included with Delphi, as part of the RTL.
One major drawback: The project has been discontinued. :-(
Now my question is:
Would it be safe to rely on this library for future projects, and use it as a base framework to build upon?
Basically I'd like to hear from somebody who's actually used this library whether or not it's worth it to invest time in getting to know this library, and why.
IIRC the project was discontinued because it was an over-engineered first attempt and a lot of its features turned out really messy and bloated. You should look at Alex Ciobanu's second attempt, which is simply called Collections. It contains most of the interesting features from DeHL, but leaner.
Be careful, though. It still makes heavy use of generics, which will make your binary size really big if you use it a lot, because the compiler team hasn't implemented a way to collapse duplicate code yet.

Which pattern is appropriate for my project?

I've been seeing a lot of articles and references about how to use this patterns for my first (please keep this in mind) serious project with ASP.NET MVC 3 and EF.
The project is not so big (13 tables) and it's basically a CRUD maintenance: organisations that have some users; users that can belong to a group and can create some work areas and templates... Nothing complicated. The point is that this will be the first of a project series and I'd like to create a base to work with.
My questions are:
Which of the previous patterns is the best? Does it depend of the project size?
My models would be these:
Unit of work
Dependency Injection
Do you think they are good enough and appropriate for my project?
I appreciate all your comments.
Serious application doesn't mean to be complex at first sight.
Over engineering an application upfront can be a real disaster, especially if you don't grasp all the technologies involved.
My advice would be to keep it simple. Create a basic application that fulfill requirements (get the thing done and make your boss happy) and then add new concepts along your learning path.
That doesn't mean I promote bad code, no way! Keep your code clean, well organized, etc. But don't be killed by the fear of doing something wrong.
It's normal for a developer to look back to an application made a few weeks ago and then realize that he did some shitty stuff. That's how we progress!
Last but not least, have FUN!
ASP.NET website provides usefull resources to learn the framework and all related guidances. There are a few application samples created step-by-step.
ASP.NET MVC was built with Dependency Injection in mind.
If you want to give a chance to your code to be loosely coupled and easier to change in the future you have to follow the patterns like Dependency Injection, Repository (for presistance abstraction), and UoW (for transaction abstraction).
So my answer is, you should learn about them in the first place to decide after if you want or no to follow the best practices. Even for simple project it's good to apply these patterns because often it gets bigger and bigger. and it's easy to do it in MVC so why to avoid it ?
There is many resources around to learn about. You can just google it.
I would like to answer this question in more generic way. Creating something which can be used in future is difficult than what it seems. All the pattern above can provide you infrastructure pieces to come up with some base framework.
But I would strongly suggest you to look at S.O.L.I.D principals (DI being part of it) to understand some qualities of good code. These are applicable irrespective of the technology involved.
You cannot predict the future requirement of a product\framework, but following these principle you can be better prepare to handle any future modification to the software
You might want to check out S#arp Lite which has many good examples of how to implement the things you want and can serve as a very good base on which to build something quickly.
None of the mentioned patterns are mutually exclusive. You should use the patterns that make sense based on what you are trying to accomplish, not attempt to shoehorn your application design into someone elses idea of how it should work. Sometimes trying to bend your scenario to fit a particular design pattern / practice is the worst thing you can do.
Want to make sure good unit test coverage / do TDD / ensure loose coupling? Then Dependency injection is your friend, as is the Unit of Work pattern. This is definitely a good idea for creating a maintainable, scalable application, but you can go too far with it for a small-scale application.
Need a centralized caching strategy for your data source? Then use the repository pattern. Or an ORM like NHibernate, which might do it for you.

Dependency Injection Frameworks: Why do I care?

I was reading over Injection by Hand and Ninjection (as well as Why use Ninject ). I encountered two pieces of confusion:
The inject by hand technique I am already familiar with, but I am not familiar with Ninjection, and thus am not sure how the complete program would work. Perhaps it would help to provide a complete program rather than, as is done on that page, showing a program broken up into pieces
I still don't really get how this makes things easier. I think I'm missing something important. I can kind of see how an injection framework would be helpful if you were creating a group of injections and then switching between two large groups all at once (this is useful for mocking, among other things), but I think there is more to it than that. But I'm not sure what. Or maybe I just need more examples of why this is exciting to drive home the point.
When injecting your dependencies without a DI framework you end up with arrow code all over your application telling classes how to build their dependencies.
public Contact()
: this(new DataGateWay())
{
}
But if you use something like Ninject, all the arrow code is in one spot making it easier to change a dependency for all the classes using it.
internal class ProductionModule : StandardModule
{
public override void Load()
{
Bind<IDataGateway>().To<DataGateWay>();
}
}
I still don't really get how this makes things easier. I think I'm missing something important.
Wouldn't it would be great if we only had to develop discrete components where each provided distinct functionality we could easily understand, re-use and maintain. Where we only worked on components.
What prevents us from doing so, is we need some infrastructure that can somehow combine and manage these components into a working application automatically. Infrastructure that does this is available to us - an IOC framework.
So an IOC framework isn't about managing dependencies or testing or configuration. Instead it is about managing complexity, by enabling you to only work and think about components.
It allows you to easily test your code by mocking the interfaces that you need for a particular code block. It also allows you to easily swap functionality without breaking other parts of the code.
It's all about cohesion and coupling.
You probably won't see the benefit on small projects, but once you get past small it becomes really apparent when you have to make changes to the system. It's a breeze when you've used DI.
I really like the autowiring aspect of some frameworks ... when you do not have to care about what your types need to be instantiated.
EDIT:
I read this article by Ayende # Rahien. And I really support his point.
Dependency injection using most frameworks can be configured at runtime, without requiring a recompile.
Dependency injection can get really interesting if you get your code to the point where there are very few dependencies in the code at all. Some dependency injection frameworks will allow you define your dependencies in a configuration file. This can be very useful if you need a really flexible piece of software that needs to be changed without modifying the code. For example, workflow software is a prime candidate for this type of solution.
Dependency Injection is essential for the Component Driven Development. The latter allows to build really complex applications in a much more efficient and reliable manner.
Also, it allows to separate common cross-cutting concerns cleanly from the other code (this results in more reusable and flexible codebase).
Related links:
Inversion of Control and Dependency Injection - Wiki
Component-Driven Development - Wiki
Cross-cutting concerns - Wiki

Best practices for refactoring classic ASP?

I've got to do some significant development in a large, old, spaghetti-ridden ASP system. I've been away from ASP for a long time, focusing my energies on Rails development.
One basic step I've taken is to refactor pages into subs and functions with meaningful names, so that at least it's easy to understand # the top of the file what's generally going on.
Is there a worthwhile MVC framework for ASP? Or a best practice at how to at least get business logic out of the views? (I remember doing a lot of includes back in the day -- is that still the way to do it?)
I'd love to get some unit testing going for business logic too, but maybe I'm asking too much?
Update:
There are over 200 ASP scripts in the project, some thousands of lines long ;) UGH!
We may opt for the "big rewrite" but until then, when I'm in changing a page, I want to spend a little extra time cleaning up the spaghetti.
Assumptions
The documentation for the Classic ASP system is rather light.
Management is not looking for a rewrite.
Since you have been doing ruby on rails, your (VB/C#) ASP.NET is passable at best.
My experience
I too inherited a classic ASP system that was slapped together willy-nilly by ex excel-vba types. There was a lot of this stuff <font size=3>crap</font> (and sometimes missing closing tags; Argggh!). Over the course of 2.5 years I added a security system, a common library, CSS+XHTML and was able to coerce the thing to validate xhtml1.1 (sans proper mime type, unfortunately) and built a fairly robust and ajaxy reporting system that's being used daily by 80 users.
I used jEdit, with cTags (as mentioned by jamting above), and a bunch of other plugins.
My Advice
Try to create a master include file from which to import all the stuff that's commonly used. Stuff like login/logout, database access, web services, javascript libs, etc.
Do use classes. They are ultra-primitive (no inheritance) but as jamting said, they can be convenient.
Indent the scripts properly.
Comment
Write an external architecture document. I personally use LyX, because it's brain-dead to produce a nicely formatted pdf, but you can use whatever you like. If you use a wiki, get the graphviz add-in installed and use it. It's super easy to make quick diagrams that can be easily modified.
Since I have no idea how substantial the enhancements need to be, I suggest having a good high-level to mid-level architecture document will be quite useful in planning the enhancements.
On the business logic unit tests, the only thing I found that works is setting up an xml-rpc listener in asp that imports the main library and exposes the functions (not subroutines though) in any of the main library's sub-includes, and then build, separately, a unit test system in a language with better support for the stuff that calls the ASP functions through xml-rpc. I use python, but I think Ruby should do the trick. (Does that make sense?). The cool thing is that the person writing the unit-test part of the software does not need to even look at the ASP code, as long as they have decent descriptions of the functions to call, so they can be someone beside you.
There is a project called aspunit at sourceforge but the last release was in 2004 and it's marked as inactive. Never used it but it's pure vbscript. A cursory look at the code tells me it looks like the authors knew what they were doing.
Finally, if you need help, I have some availability to do contract telecommuting work (maybe 8 hours/week max). Follow the link trail for contact info.
Good luck! HTH.
Since a complete rewrite of a working system can be very dangerous i can only give you a small tip: Set up exuberant tags, ctags, on your project. This way you can jump to the definition of a function and sub easy, which i think helps a lot.
On separating logic from "views". VBScript supports som kind of OO with classes. I tend to write classes which do the logic which I include on the asp-page which acts as a "view". Then i hook together the view with the class like Username: <%= MyAccount.UserName %>. The MyAccount class can also have methods like: MyAccount.Login() and so on.
Kind of primitive, but at least you can capsulate some code and hide it from the HTML.
My advice would be to carry on refactoring, classic ASP supports classes, so you should be able to move all everything but the display code into included ASP files which just contain classes.
See this article of details of moving from old fashioned asp towards ASP.NET
Refactoring ASP
Regarding a future direction, I wouldn't aim for ASP.NET web forms, instead I'd go for Microsoft's new MVC framework an add-on to of ASP.NET) It will be much simpler migrating to this from classic ASP.
I use ASPUnit for unit testing some of our classic ASP and find it to be helpful. It may be old, but so is ASP. It's simple, but it does work and you can customize or extend it if necessary.
I've also found Working Effectively with Legacy Code by Michael Feathers to be a helpful guide for finding ways to get some of that old code under test.
Include files can help as long as you keep it simple. At one point I tried creating an include for each class and that didn't work out too well. I like having a couple main includes with common business logic, and for complicated pages sometimes an include with logic for each of those pages. I suppose you could do MVC with a similar setup.
Is there any chance you could move from ASP to ASP.Net? Or are you looking at keeping it in classic ASP, but just cleaning it up. If at all possible, I would recommend moving as much as possible moving to .Net. It looks like you may be rewriting/reorganizing a lot of code anyway, so moving to .Net may not be a lot of extra effort.
Presumably someone else wrote most or all of the system that you're now maintaining. Look for the usual bad habits (repeated code, variables that are too widely scoped, nested if statements, etc.), and refactor as you would any other language. Keep an eye out for recurring things in the same file or different files and abstract them into functions.
If the code was written/maintained by various people, there might be some issues with inconsistent coding style. I find that bringing the code back into line makes it easier to see things that can be refactored.
"Thousands of lines long" makes me suspicious that there may also be situations where loosely-related things are being displayed on the same page. There again, you want to abstract them into separate subroutines.
Eventually you want to be writing objects to help encapsulate stuff like database connectivity, but it will be a while before you get there.
This is very old, but couldn't resist adding my two cents. If you must rewrite, and must continue to use classic ASP:
use JScript! much more powerful, you get inheritance, and there some good side benefits like using the same methods for server-side validation as you use for client-side
you can absolutely do MVC - I wrote an MVC framework, and it was not that many lines of code
you can also generate your model classes automatically with a bit of work. I have some code for this that worked quite well
make sure you are doing parameterized queries, and always returning disconnected recordsets
Software Development Project Management practices indicates that softwares like this are requiring to retire.
I know how hard it is to do the right thing, even more when the responsible manager knows sht and is scared of everything other than the wost way possible.
But still. It's necessary to start working on the development of a new software. It's simply impossible to maintain this one forever, and the loger they wait for retiring it the worse.
If you don't have proper specification/requirements documentation (I think no asp software in the world does, given the noobatry hability of those coders), you'll need both a group of users that know the software features and a manager to be responsible for validating the requirements. You'll need to review every feature and document its requirements.
During that process you'll go learning more about the software and its business. Once you have enough info, you can start developing a new one.

Resources