08 April 2005

Functions cubed

As I've mentioned, I've been looking at different coding standards (props to Christopher Lott on his nice collection). After a reading a couple, you come to appreciate the competing philosophies at work. In fact, much of buying into a code style is buying into a philosophy. Code styles range from a simple list of rules to manifestos. One I thought got things off to a start with a bang was Programming Style for Foundations of Computer Science:

FUNCTIONS, FUNCTIONS, FUNCTIONS!!!

You must decompose your programs into smaller parts. One function won't cut it. This is one of the most common pitfalls of novice programmers. As a general rule of thumb, no function should consist of more than 20 lines of code. Yes, it's arbitrary, but think of it as a learning exercise; by having to fit within such constraints, you will come to appreciate what modular coding does for you, and when it is right to use bigger functions.

The decomposition process does not occur at the very end. Some students bring code, promising that they'll split it into smaller functions, "when they're done". That's not the point--you don't do this just to make the program look pretty. You want to decompose the problem (and your solution, i.e. the program) starting at the design phase. By forcing yourself to design modularly (i.e., use functions) from the beginning, your program will go together faster, be easier to debug and easier to read. Think Legos© and Tinker-toys©: lots of small pieces, each easy to comprehend and debug. Plug them together and you can get great stuff!

As you write code, if you find a function becoming too large (too many variables, etc.), it's probably time to split the function into smaller parts.

For "toy" programming assignments like most of those of this course, you can get away with poor design technique (like not thinking modularly). But, believe me, you will fall down, *hard*, when you get to bigger programs.

More philosophy: Rob Pike's Notes on Programming in C. Automated Linux from scratch's folding Linus's Linux kernel style guide into theirs. Don't forget to revel in the glory of Microsoft's Hungarian Notation for VB. And, the most ideological of all: GNU. What does Linus think of GNU's coding standards?

First off, I'd suggest printing out a copy of the GNU coding standards, and NOT read it. Burn them, it's a great symbolic gesture.

Everyone has got an opinion once they wade in.

No comments: