Hiding Details
Functions can also be used to hide details from
other programmers who use them
What is the point?
Improve program readability
To make our main program simpler and easier to read. For instance, we could call
a function named PrintGreeting( ) and assume that it will do just that. We have
now managed to remove many lines of code that just clutter the main program. Here
is an example
/*******************************************************************
*
* PrintGreeting( ) prints an initial message when the program starts.
*
* INPUTS: none
* OUTPUT: none
* SIDE EFFECTS: prints to stdout
*
*******************************************************************/
void PrintGreeting( void )
{
printf("\n\n");
printf("*************************************\n");
printf("*Hello. *\n");
printf("*This program finds the surface area*\n");
printf("*and volume of a sphere. *\n");
printf("*************************************\n\n");
}
Information hiding promotes modularity
- In order for other programmers to make use of functions we've written, it
is sufficient for them to know what the function does, what arguments it takes
and its return type. They do not need to know how we decided to write the
code within the function definition.
- This means that we are free to change or improve the working of our function
without effecting the other programmers who are using it. (Assuming we don't
break it!)
- Such "information hiding" is a key to building modular programs,
especially among a group of programmers.
The functional approach
This only works of we are careful to avoid (as much as possible)
- Having our functions perform unexpected side effects
- Depend on variables or constants not passed as arguments
We'll see more of these ideas later