The decomposition process does not occur at the very end. Some of you have brought code to me to look at, 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.
sizeOfBalloon
.
gSizeOfBalloon
.
SIZE_OF_BALLOON
.
SizeOfBalloon()
.
balloon
class, balloon.h
, in the textbook
presents a good example. A part of that file's header comment follows:
Each function header must also contain a PRECONDITION and POSTCONDITION lines. The PRECONDITION comment specifies the preconditions that must exist for the function to execute correctly. Usually this is a relation or predicate that must hold on the parameters and global variables used by the function. The POSTCONDITION comment must specify what value the function returns, and any changes that will be made to reference parameters and global variables.
The following example is taken from craps2.cc:
if
, do
,
while
, for
, and function call.)
See code below, also taken from craps2.cc for some examples:
int main() { int k; // Iteration counter. int gamesWon = 0; // Number of games won. int simulations = // Number of games to simulate. PromptRange("enter # games to simulate",1,1000000); for(k=0; k < simulations; k++) // For each simulated game.... { if (WinGame()) { gamesWon++; } } // After running all the simulations, we output the results.... cout << "# of games = " << simulations; cout << " # won = " << gamesWon << " = "; cout << double(gamesWon)/simulations * 100 << "%" << endl; return 0; }