Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any need for dependency injection in Dynamic Languages?

In order to write testable C# code, I use DI heavily.

However lately I've been messing around with IronPython and found that as you can mock any methods/classes/functions etc... you like, the need for DI is gone.

Is this the case for dynamic langagues such as Python?

Instead of:

class Person(Address) {
...

You can have:

class Person() {
...
    // Address initialised in here.

For dynamic languages and therefore following manaual DI for dynamic langagues is simply not needed.

Any advice on this?

like image 443
Finglas Avatar asked Dec 24 '09 00:12

Finglas


2 Answers

Dependency Injection is also about how you wire things together --- which has nothing to do about the mockability of depended-on objects. There's a difference between having a Foo-instance that needs a Bar-connection of some kind instantiate it directly and having it completely ignore how it gets that connection as long as it has it.

If you use dependency injection you also gain better testability. But the converse isn't true. Easier testability by being able to overwrite anything doesn't bring the other advantages of dependency injection. There are many component/DI-frameworks for Python available exactly for these reasons.

like image 95
Alex Brasetvik Avatar answered Nov 15 '22 23:11

Alex Brasetvik


I strongly disagree with your statement that Dependency Injection is not needed in dynamically typed languages. The reasons for why DI is useful and necessary are completely independent of the typing discipline of the language.

The main difference is that DI in dynamically typed languages is easy and painless: you don't need a heavyweight framework and a gazillion lines of XML configuration.

In Ruby, for example, there are only two DI frameworks. Both were written by a Java programmer. Neither of the two frameworks is used by a single project. Not even by the author of those frameworks.

However, DI is used all over the place in Ruby.

Jamis Buck, who is the author of both of those frameworks gave a talk called Recovering from Enterprise at RubyConf 2008 about how and why he wrote those frameworks and why that was a bad idea, which is well worth watching. There’s also an accompanying blog post if you’d like to read. (Just substitute “Python” everytime he says “Ruby” and everything will be just as valid.)

like image 40
Jörg W Mittag Avatar answered Nov 16 '22 01:11

Jörg W Mittag