Closures Are Kind of Like Objects


What Do People Mean By An Object?

Lots of things!
  • A collection of data
  • A grouping of data and functions that act on that data
  • When many objects have the same structure of data and/or functions we might start thinking of them as members of a class/type
  • When objects have their data accessed by their functions we start talking about "encapsulation".
  • When object types can share their structures we start talking about inheritance/etc.
So Objects can be typed or untyped.

Let's Look At A Closure!

Compare what is gained and lost.

(define (adder x)
  (lambda (y) (+ x y)))

class PythonClass(object):
    __slots__ = ('x')
    def __init__(self, x):
        self.x = x
    def add_x_to(self, y):
        return self.x + y

Comparison

  • We have state, x
  • We have encapsulation
  • We lost a name
  • One is a function with some state, the other is some named state and a named function

When To Use?

  • When an API expects a function (ex: a callback)
  • When you need to preserve state, but only one time, a closure is a lighter weight solution than an entire class.
  • When you want much stricter enforcement of encapsulation.

Grokking Closures

By Philip Doctor

Grokking Closures

  • 1,110