Skip to content

Instantly share code, notes, and snippets.

@marcusradell
Last active March 3, 2016 10:39
Show Gist options
  • Save marcusradell/540974398a5165b7766b to your computer and use it in GitHub Desktop.
Save marcusradell/540974398a5165b7766b to your computer and use it in GitHub Desktop.

One paragraph rule

There are lots of rules of how to indent and divide rows of code into paragraphs. André Staltz suggested that we limit ourselves to 6 rows of code. I would try to stay in the working memory limit of 7 +/-2 bits according to Miller's law to keep cognitive strain down while reading other people's code. The number 6 still holds well enough, just want to add a reason for it.

One issue that might occurr, is that you need to return a function that has access to a variable on the parent scope:

// the caller needs to call #destroyFn() at some future time (the testrunner ends)
// and #destroyFn() needs to access the variable `server` in the parent scope.
function createServer() {
  const server = http.createServer()
  return function destroyFn() {
    server.close()
  }
}

You have access to the entire parent scope here, which I don't like. And if the destroyFn wants to add some logging message and such, you really want to extract the function. My (yeah, I totally invented it..) proposed solution is to have a higher order function creator that takes the needed variable in as an argument, and thus isolating the scope:

function createDestroyFn(server) {
  return function destroyFn() {
    server.close()
  }
}

function createServer() {
  const server = http.createServer()

  return createDestroyFn(server)
}

Boom! Isolated parent scope, and you get a real life example of a higher order function.

Referenses

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment