var factory = makeCar;
The whole point of having first-class functions is that you can assign them. The problem a factory solves is precisely the lack of this assignability (which is why a constructor function is wrapped in a class). var factory = makeCar;
The whole point of having first-class functions is that you can assign them. The problem a factory solves is precisely the lack of this assignability (which is why a constructor function is wrapped in a class).The specific pattern DI can solve here is:
- one module provides some capability by name
- another module makes use of that capability by name
- the two modules have no knowledge of each other, and no higher-level glue code is required to connect them together (and construct the appropriate objects at the right times).
Your "solution" does not satisfy the requirements because it requires you to manually construct the objects in the correct order. DI on the other hand will automatically analyze the graph of dependencies, invoking the appropriate factories in the right order.
The issue is not how you define your factories, it's how you pass them around and use them in a component that has no knowledge of the outside world.
You pass it as a function argument.
function needs_to_make_a_car(car_maker, road) {
var car = car_maker()
car.drive_on(road)
}
To which you would probably reply: "But that's exactly what FactoryFactory/DependencyInjection/... pattern is!"To which we would reply: "Exactly, which are just fancy words for the re-and-re-discovered concept of functional programming."
I've seen XML configurability used as an extension point for code that would otherwise be closed. I've seen bugs happen because the lifecycle of objects have been mismanaged. You're conflating that things can be done more elegantly using functional programming to think it belongs in a functional paradigm.
IoC containers in .NET are easier to use and more elegant because of functional programming constructs, but their existence doesn't remove the need to have them.
Take a step back, and think why that 'extension point' had to be closed to begin with. You're probably going to find either an architectural flaw, or a problem with your tooling that should not have required this sort of thing in the first place.
Also disturbing is that you are using XML to add a degree of expressiveness missing from whatever tooling you are using.
Actually no. DI does a lot that your simple examples do not. Notably, it understands the graph of dependencies between decoupled compoments and constructs provided values in the correct order.
Maybe you're talking about some particular DI framework. That would be a library with functions and classes to make implementing the DI pattern easier. There are many such frameworks, and some of those frameworks may well do automatic graph analysis. But, graph analysis is not inherent in the pattern.
Your specific framework is not the general pattern.
That's not functional programming.