Saturday 12 November 2011

Functions Should Be Concise

Functions Should Be Concise

In light of the previously stated rule of thumb—that the difficulty of debugging a block of code is equivalent
to the square of its length—this rule about keeping functions concise should make perfect sense. However, there’s even more to it than that. If a function is concise, you should need a few moments of careful examination and a few careful tests to assure yourself that the function is bug free. After doing this, you can proceed to code the rest of the program, confident in the knowledge that one of your building blocks is OK. You should never have to look at it again. You are unlikely to have this level of confidence in a long, complex routine
Another benefit of using small building-block functions is that after a small, functional bit of code has been
defined, you might find it useful in other parts of your program as well. For example, if you were writing a financial program, you might need, in different parts of your program, to calculate interest by quarters, by
months, by weeks, by days in a month, and so forth. If you were writing the program in an unstructured fashion, you might believe that you need separate code in each of these cases to compute the results. The
program would become large and unreadable, in part due to repeated computations of compound interest.
However, you could break off this task into a separate function like the one that follows:
/*
* Compute what the “real” rate of interest would be
* for a given flat interest rate, divided into N segments
*/
double Compute Interest( double Rate , int Segments )
{
int a;
double Result = 1.0;
Rate /= (double) Segments;
for( a = 0 ; a < Segments ; ++ a )
Result *= Rate;
return Result;
}

After you have written this function, you can use it anywhere you need to compute compound interest. You
have not only possibly eliminated several errors in all the duplicated code, but considerably shortened and
clarified the rest of the code. This technique might make other errors easier to find.

After this technique of breaking down a program into manageable components becomes a habit, you will
see many subtler applications of its magic.

No comments:

Post a Comment