3 ms·
Whether a function is anonymous or not is sugar. The important thing is functions aren't special, they can be passed around (i.e. the are 1st class objects). I
by njharman 15y ago
Whether a function is anonymous or not is sugar. The important thing is functions aren't special, they can be passed around (i.e. the are 1st class objects).
I actually can't fathom having to code in a language in which you can't pass functions around.
Call backs is my biggest use of function passing. This is really, really huge.
Currying, decorating/wrapping functions
Replacing methods/functions at run time. Great for testing.
Putting them in data structures. Often dictionaries. Often to create more dynamic switch like logic. dict[key] = func_that_handles_key, etc. then later, dict[key](key)
Lots of data is code stuff.
Closures just make the passed functions more powerful / convenient as they capture their scope. Which is often used (at least by me in Python) to create function factories that return custom functions.
A contrived example but a pattern I use often. Logging object with warn, debug, error functions. You could hardcode / boilerplate each of those functions but that is boring, tedious, and nonDRY. So instead you create a function factory and use it to return anonymous functions, like so. Python.
def log_func_factory(level):
def closure(msg):
print level, msg
return closure
class logging(object):
debug = log_func_factory('debug')
warn = log_func_factory('warn')
error = log_func_factory('error')
With real code I'd not repeat those assignments and instead use a loop driven by data.
for level in ('debug', 'warn', 'error'):
setattr(logger, level) = log_func_factory(level)
Bam, data driven code. Very DRY, very concise, very dynamic. Maintenance is adding one text string in one place.