Functions in functions

Thai Pangsakulyanont
2 min readOct 27, 2015

I also sometimes prefer straight-line functions as well, especially in imperative code.

But when a function starts to get longer than 15 lines, I start feeling that the code becomes less readable.

What I learned is that people have different tolerance on the number of lines of code that they can comprehend, before they need to refactor it to be able to work on it.

For me it’s about 15–20 lines, but I also believe it’s also because of my low tolerance that makes me very productive when I work on my own code.

Quoting Sandi Metz’ Rules For Developers
1. Classes can be no longer than one hundred lines of code.
2. Methods can be no longer than five lines of code.

As I learn more functional programming, I start to love extracting things into functions, so that at any given line, only the necessary variables can be accessed.

However, in JavaScript, once you create a variable, it remains there for the rest of the lexical scope.

Therefore, longer block of code means more things to keep track of, and more assumptions are involved, and that makes your code harder to comprehend.

But when you extract your code into another function, your code will lose some cohesiveness, which also makes your code harder to comprehend.

One of the pattern I found very useful when writing JavaScript code is to write functions in functions.

function onKeyPress (event) {
{
if (event.metaKey || event.ctrlKey) return
const letter = letterFromKeycode(event.keyCode)
if (!letter) return
const scrollContainer = getScrollContainer()
if (scrollContainer) sortlistLetterJump(scrollContainer, letter)
}
function letterFromKeycode (keycode) {
// ...
}
function getScrollContainer () {
// ...
}
function sortlistLetterJump (scrollContainer, letter) {
// ...
}
}

At the top part, you have an executive overview of what your code is doing, making it easy to comprehend.

But if you want to know more about what really happens, just look at the functions below the first block. This helps keeping different concerns separated.

But they all reside in one big block of onKeyPress. This helps keeping related code together.

--

--

Thai Pangsakulyanont

(@dtinth) A software engineer and frontend enthusiast. A Christian. A JavaScript musician. A Ruby and Vim lover.