In the previous article we split out the computation of the mean into a separate function:
double cmean( const double * data,
size_t n)
{
double sum =0;
for (size_t i =0 ; i < n ; ++i )
{
sum += data[i];
}
return (sum/n);
}
In words, the algorithm of the function cmean can be described as:
That seems simple enough, but given that the description of what this function accomplishes splits into two points so easily, it would make sense to also split this function into two smaller functions that do only one conceptual operation.
In general splitting algorithms into functions that accomplish only one tasks greatly improves the readability, maintainability and usability of a program.
Here is the improved version of the mean program:
// mean_v4.cpp
// Bojan Nikolic <bojan@bnikolic.co.uk>
// Short functions
#include <iostream>
double csum(const double * data,
size_t n)
{
double sum =0;
for (size_t i =0 ; i < n ; ++i )
{
sum += data[i];
}
return sum;
}
double cmean( const double * data,
size_t n)
{
return (csum(data,n)/n);
}
int main(void)
{
const double data[] = { 1,2,3,4,5};
const size_t n = 5;
std::cout<<"The sum is: "<<csum(data,n)
<<" and the mean is: "<< cmean(data, n) <<std::endl;
}
The main change is that now we have two separate functions each of which does only one conceptual operation:
1. Function csum which computes the sum of elements of an array of double precision numbers.
2. Function cmean which computes the arithmetic mean by dividing the sum (computed using csum) by the number of elements in the array.
Besides improving the readability of the program, this approach allows us to print out the sum of the numbers whiteout any repetition of code.
Keeping functions short so that each performs as small a conceptual task as practical is the key to writing high quality programs in any language.