C++ Notes: Function Concepts
Purpose of functions
The purpose of functions is to make the programmer's life easier.
- Write code once, and call it from many places. This insures consistency, and
reduces the cost of writing and debugging.
- A function allows code to be parameterized by passing values to it.
- Functions can be collected in libraries and reused in other programs.
- Functions create new conceptual units
that form the units that programmers use in thinking about a problem.
Naming
For a function to work well as a conceptual unit it has to have a name that
is clear to the human reader.
- Choose a name that has a clear meaning. Eg, "f" is not
a good name.
- Void functions are often more readable if a verb name is used
that describes what it does.
Eg, "printAverage" would be a good name for a void function that prints the
average of some numbers.
- boolean functions should usually start with "is" or another word
that suggests a yes/no answer. Eg, "isOdd(n)" for a function that returns
true if its parameter is odd.
- Start the name with lowercase and capitalize the first
letter of each additional word in the name.
- Value-returning functions are often named after the value that
they return. Eg, "sum(a, b)" would be a good name for a function that
adds a and b.
Cohesion
Each function should do only one thing.
Side-effects
Functions should avoid side-effects such as communicating by means
of global variables.
Functional Decomposition - top-down programming
The top-down programming style is to write
a short main program that calls on additional functions to
accomplish it task. These functions should similarly
be kept short and call more functions if necessary to
get their task done. Start with the main function, and write
only function stubs which do almost nothing except
maybe print a message that they were called.
Get this running, then expand one of the stubs, get this
running, ... . This very productive style of programming
is related to iterative programming and is one of
the cornerstones of Extreme Programming.
One page
It is generally a good idea to keep functions shorter
than one page or one screen. This makes them easy
to comprehend, If one page is not enuf space, then
write additional functions to help perform the task
(top-down programming).