COMPOSING FUNCTIONS
The idea of composition is based on a very simple thought. Using an example of simple calculations, consider these lines of code:
int a = 10;
int b = a * 3;
int c = b + 27;
The first line assigns a value to a. The second line calculates b from a, by applying a calculation. Finally, the third line calculates c from b, again by applying a calculation. Instead of performing these calculations directly, you could create functions like this:
int CalcB(int a) {
return a * 3;
}
int CalcC(int b) {
return b + 27;
}
int a = 10;
int b = CalcB(a);
int c = CalcC(b);
In any real-world application, it is quite likely that you would have helper functions similar (in structure, not in the calculations themselves!) to CalcB and CalcC. Now imagine you have a particular algorithm somewhere in your application that starts with a values and needs to calculate c values from them — in other words, you’re not interested in b at all. There are several things you could do now. For instance, you could create a new function CalcCfromA:
int CalcCfromA(int a) {
return a * 3 + 27;
}
That is not a very good idea because you might need the original functions elsewhere, and of course it’s generally a good guideline to separate functionality as much as possible, which leads to several small functions that each do just one thing. Instead, you could implement the function like this:
int CalcCfromA(int a) {
return CalcC(CalcB(a));
}
This is much better, and you will see in a moment ...