When decomposing a large function, how can I avoid the complexity from the extra subfunctions?
- by missingno
Say I have a large function like the following:
function do_lots_of_stuff(){
{ //subpart 1
...
}
...
{ //subpart N
...
}
}
a common pattern is to decompose it into subfunctions
function do_lots_of_stuff(){
subpart_1(...)
subpart_2(...)
...
subpart_N(...)
}
I usually find that decomposition has two main advantages:
The decomposed function becomes much smaller. This can help people read it without getting lost in the details.
Parameters have to be explicitly passed to the underlying subfunctions, instead of being implicitly available by just being in scope. This can help readability and modularity in some situations.
However, I also find that decomposition has some disadvantages:
There are no guarantees that the subfunctions "belong" to do_lots_of_stuff so there is nothing stopping someone from accidentally calling them from a wrong place.
A module's complexity grows quadratically with the number of functions we add to it. (There are more possible ways for things to call each other)
Therefore:
Are there useful convention or coding styles that help me balance the pros and cons of function decomposition or should I just use an editor with code folding and call it a day?
EDIT: This problem also applies to functional code (although in a less pressing manner). For example, in a functional setting we would have the subparts be returning values that are combined in the end and the decomposition problem of having lots of subfunctions being able to use each other is still present.
We can't always assume that the problem domain will be able to be modeled on just some small simple types with just a few highly orthogonal functions. There will always be complicated algorithms or long lists of business rules that we still want to correctly be able to deal with.
function do_lots_of_stuff(){
p1 = subpart_1()
p2 = subpart_2()
pN = subpart_N()
return assembleStuff(p1, p2, ..., pN)
}