One of the most important concepts of programming is the ability to group some lines of code into a unit that can be included in our program. The original wording for this was a sub-program. Other names include: macro, sub-routine, procedure, module and function. We are going to use the term function for that is what they are called in the two predominant programming languages of today: C++ and Java. Functions are important because they allow us to take large complicated programs and to divide them into smaller manageable pieces. Because the function is a smaller piece of the overall program, we can concentrate on what we want it to do and test it to make sure it works properly. Generally functions fall into two categories:
- Program Control -Functions used to simply sub divide and control the program. These functions are unique to the program being written. Other programs may use similar functions maybe even functions with the same name, but the content of the functions are almost always very different.
- Specifc Task -Functions designed to be used with several programs. These functions perform a specific task and thus are useable in many different programs because the other programs also need to do the specific task. Specifc task functions are sometimes referred to as building blocks. Because they are already coded and tested, we can use them with confdence to more efciently write a large program.
The main program must establish the existence of functions used in that program. Depending on the programming language, there is a formal way to:
- define a function (it's definition or the code it will execute)
- call a function
- declare a function (a prototype is a declaration to a complier)
Program Control functions normally do not communicate information to each other but use a common area for variable storage. Specifc Task functions are constructed so that data can be communicated between the calling program piece (which is usually another function) and the function being called. This ability to communicate data is what allows us to build a specific task function that may be used in many programs. The rules for how the data is communicated in and out of a function vary greatly by programming language, but the concept is the same. The data items passed (or communicated) are called parameters. Thus the wording: parameter passing. The four data communication options include:
- no communication in with no communication out
- some communication in with no communication out
- some communication in with some communication out
- no communication in with some communication out