Modularity
Example: The Cookbook
A good everyday example of modularity can be found in a cookbook. Let's
say we want to make Boston Cream style doughnuts. These are the ones with
that great vanilla cream filling and the chocolate icing on top. If we
look up the recipe for Boston Cream doughnuts, it will give us the ingredients
and instructions for baking the cake part of the doughnut. The recipe will go
on to say :
- "After baking and cooling, use a pastry bag to fill the hollow center
with custard filling
- Use the recipe for Very-Vanilla Custard (p. 212)
- "Frost the top of each doughnut with chocolate frosting
- Use the recipe for Deep-Dark Chocolate Frosting (p. 351)"
The recipe for Very-Vanilla Custard is a module and so is the recipe for
Deep-Dark Chocolate Frosting. The cookbook could have given all of the
ingredients and instructions for making these things as part of the Boston
Cream Doughnut recipe. By making these recipes be independent modules, many
other recipes can also use them. For instance, now the cookbook can refer to
the recipe for Deep-Dark Chocolate Frosting as the frosting for chocolate
cake.
Definition of a Module
The American Heritage Dictionary of the English Language defines a
module as :
A standardized, often interchangeable component of
a system or construction that is designed for easy assembly or flexible use:
a sofa consisting of two end modules.
A unit of education or instruction with a relatively high
teacher-to-student ratio, in which a single topic or a small section of a
broad topic is studied for a given period of time.
(In Computer Science.) A portion of a program that
carries out a specific function and may be used alone or combined with
other modules of the same program.
Functions as Modules
So functions can be used as modules. They are the building blocks of programs.
The modular approach can also save us time and effort in the longrun. If we
strive to write functions that are very general in nature, then we may be able
to reuse the function in some other project that requires solving some similar
problem. Here is an example of a very general and reusable function.
/*GetValidInt gets an integer from the user between */
/*specified minimum and maximum values, and will */
/*reprompt the user until it gets one that is valid.*/
/* */
/*Inputs: min and max, the minimum and maximum */
/* (inclusive) values for the entered integer */
/*Outputs: returns an integer between min and max, */
/* inclusively */
int GetValidInt(int min, int max)
{
/* is set greater than max so the loop will be entered*/
int input = max + 1;
while( input < min || input > max )
{
printf("Please enter an integer between");
printf(" %d and %d : ", min, max);
scanf("%d", &input);
}
return input;
}