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.
-
André Staltz video: https://egghead.io/lessons/javascript-refactoring-tip-no-empty-lines-inside-a-function
-
Miller's law: https://en.wikipedia.org/wiki/The_Magical_Number_Seven,_Plus_or_Minus_Two
-
My RxJS server project using the higher order function creator with a testrunner (work in progress): https://github.com/marcusnielsen/rxjs-server/blob/master/app/server/index.js#L5