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

Great examples. We were taught to pass variables, scalar or compound, into API's. Most of us were never taught to pass functions.

Even Python examples in trainings that look functional might not be. They put the function calls in as arguments. The beginner thinks the function returns some data, that would be in a variable, and they are implicitly passing that variable. Might as well, for readability, do the function call first to pass a well-named variable instead.

That was my experience. That plus minimizing side effects in functions. I've yet to really learn functional programming where I'd think to pass a function in an API. What are the best articles or books for us to learn that in general or in Python?



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: