There are several simple guidelines for writing functions or methods (guidelines that I like that is).
- Keep them clean, don't intersperse them with comments. If they require more then one or two inline comments it's too complicated and you should restructure.
- Keep them short, it should fit on one screen. I'm flexible, a screen is an emacs buffer, not a vi in a terminal as Linus requires <http://lxr.linux.no/linux/Documentation/CodingStyle>.
- Write a clear description at the top, explaining parameters, return values, exceptions etc whenever these things might not be blatingly obvious in a month's time. As soon as you explain one parameter you you should describe the whole lot though.
In C this is quite nice, it looks like this:
/** Print an integer number
*
* The number is printed to stdout. Really that's
* all there is to it.
*
* param - The integer to print.
*/
void my_func(int param)
{
printf("This is an integer: %d", param);
}
While in Python this would look like this:
def my_func(param)
"""Print a number
The number is printed to stdout. Really that's
all there is to it.
param - The number to print.
"""
print "This is a number: %d" % param
While python code is generally very lovely readable this is something that annoys me about it. Suddenly my function definition is separated from the code by the docstring, often causing the definition and the code not to fit on one screen anymore (it is foolish IMHO to require the documentation and code to fit on one screen, given my documentation conventions).
While I understand every reason for the way things are and acknowledge that it probably won't ever change it still annoys me from time to time so I felt like moaning about it.