Are first-class functions a substitute for the Strategy pattern?
- by Prog
The Strategy design pattern is often regarded as a substitute for first-class functions in languages that lack them.
So for example say you wanted to pass functionality into an object. In Java you'd have to pass in the object another object which encapsulates the desired behavior. In a language such as Ruby, you'd just pass the functionality itself in the form of an annonymous function.
However I was thinking about it and decided that maybe Strategy offers more than a plain annonymous function does.
This is because an object can hold state that exists independently of the period when it's method runs. However an annonymous function by itself can only hold state that ceases to exist the moment the function finishes execution.
So my question is: when using a language that features first-class functions, would you ever use the Strategy pattern (i.e. encapsulate the functionality you want to pass around in an explicit object), or would you always use an annonymous function?
When would you decide to use Strategy when you can use a first-class function?