Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

It's called dependency injection and there's loads written about it. It's a really powerful technique which is also used for dependency inversion, key for decoupling components. I really like how it enables simple tests without any mocking.

The book Architecture Patterns in Python by Percival and Gregory is one of the few books that talks about this stuff using Python. It's available online and been posted on HN a few times before.



DI (generally) tends to point more towards constructing objects or systems. This would be a bit closer to a functional equivalent of the OO "template method" pattern: https://en.wikipedia.org/wiki/Template_method_pattern

You write a concrete set of steps, but delegate the execution of the steps to the caller by invoking the supplied functions at the desired time with the desired arguments.


Agree with zdragnar; this is not traditional DI which is generally focused on injecting objects.

The difference between the two is that when you inject an object, the receiving side must know a potentially large surface area of the object's behavior.

When injecting a function, now the receiving side only needs to know the inputs and outputs of the singular function.

This subtlety is what makes this approach more powerful.


I don't see the difference, but I do agree that DI is generally used to mean constructing systems. It's what you do in your main or "bootstrap" part of the program and there are frameworks to do it for you. But really it's the same thing. You're just composing functionality by passing objects (functions are objects) that satisfy an interface. It might be more acceptable to just say it's dependency inversion.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: