Functions in functions

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.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store