[Tutor] How (not!) lengthy should functions be?
Ben Finney
ben+python at benfinney.id.au
Thu Apr 16 22:21:14 CEST 2015
boB Stepp <robertvstepp at gmail.com> writes:
> My current understanding of function length best practice is that: 1)
> Each function should have preferably ONE clearly defined purpose.
Yes, that's a principle to follow firmly, improving the design every
time. I know of no exceptions.
“Clearly defined” also entails the function signature (its name, what
parameters it accepts, what return value it emits) is narrowly defined.
> 2) I have seen varying recommendations as to number of lines of code
> per function, but I have seem multiple recommendations that a function
> generally should fit into one screen on one's monitor.
A function that is clearly-designed, as above, should have no more than
a handful of statements. That's intentionally vague, but it's already
shorter than “a screenful”.
> Of course, some people have HUGE monitors! And I assume that any
> guidance applies equally well to methods.
Any function with statements stretching over 20 lines is already too
large, IMO.
Note that the docstring can be rather lengthy, if there is a lot to say
about the function's purpose or strange cases it handles.
> Am I on-track or am I getting carried away?
You're right to care about precision in your code. Overlong, overbroad,
overcomplex, overdetermined functions happen through laziness; it takes
diligence to keep the code readable through refactoring while you go.
That takes more effort at each edit, but saves a lot of debugging time.
Having such a principle in mind, and knowing that it's worth spending
effort to uphold, will serve you well.
--
\ “Outside of a dog, a book is man's best friend. Inside of a |
`\ dog, it's too dark to read.” —Groucho Marx |
_o__) |
Ben Finney
More information about the Tutor
mailing list