Hacker News new | ask | show | jobs
by da39a3ee 953 days ago
A major difference between a long function and multiple short helper functions is that when you look at the local variables in scope in the long function you do not easily know which of them are used by which parts of the function. You see a variable used on lines 756-762 but the function continues to line 900 and perhaps it's used again further down?

Some languages have block scopes that can make this better; my position is against long functions in languages that lack block scopes or written by programmers that do not avail themselves of block scope.

I really struggle to see why anyone is not attracted to that form of abstraction: if local variable foo is computed in 10 lines using local variables bar, baz, and qux, and those 3 are not used for anything else, then clearly matters are improved in a 100-line function by replacing those 10 lines with

  foo = computeFoo(bar, bax, qux)
Authors of long functions are not embracing appropriate modularity, but that seems inexplicable, since modularity is the basis of the software revolution.
1 comments

Personally, I encounter long functions (as you described, around 100 lines) mainly in older codebases that were written over 20 years ago. In many cases, I get them for rework when developing new software, particularly in industries where the adage is 'if it works, don't change it.' This phenomenon could be attributed to the fact that, at that time, OOP was just emerging, and developers were not yet accustomed to it. I strive to write code that is concise and highly readable. It's important that the function's purpose and usage are immediately evident at first glance, rather than relying on copious comments.