Imagine a long and complicated process, which is started by calling function foo()
. There are several consecutive steps in this process, each of them depending on result of the previous step. The function itself is, say, about 250 lines. It is highly unlikely that these steps would be useful on their own, not as a part of this whole process.
Languages such as Javascript allow creating inner functions inside a parent function, which are inaccessible to outer functions (unless they are passed as a parameter).
A colleague of mine suggest that we can split up the content of foo()
into 5 inner functions, each function being a step. These functions are inaccessible to outer functions (signifying their uselessness outside of the parent function). The main body of foo()
simply calls these inner function one by one:
foo(stuff) {
var barred = bar(stuff);
var bazzed = baz(barred);
var confabulated = confabulate(bazzed);
var reticulated = reticulate(confabulated);
var spliced = splice(reticulated);
return spliced;
// function definitions follow ...
}
Is this an anti-pattern of some sort? Or is this a reasonable way to split up long functions? Another question is: is this acceptable when using OOP paradigm in Javascript? Is it OK to split an object's method this way, or does this warrant another object, which contains all these inner functions as private methods?
See also:
Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else? - a previous question of mine, which leads into this one.
@KilianFoth's answer to a very similar question which provides a different perspective compared to the answers given here.