|
|
|
|
|
by sethg
6247 days ago
|
|
One thing I've occasionally done to tame large functions is this: def frobWidget(widget):
def frobCog(cog):
## stuff involving both cog and widget
## stuff involving widget
frobbedCogs = [frobCog(cog) for cog in widget]
## more stuff involving widget and frobbedCogs
If frobCog were broken out into a separate function, then it would have to take widget as an argument, and if frobCog is never actually called from anywhere other than within frobWidget, then such separation makes the code harder to understand. Keeping the definition internal lets me take advantage of lexical scope; I can refer to widget within the definition of frobCog. |
|
In general, there's nothing wrong with functions that take everything they use as arguments. This is kind of functional programming (or a good part of it): every function is as independent as possible, which makes them easier to debug, easier to understand, and safer in terms of bugs. Functions that deal with data from outer scopes risk being less readable and less reliable.