Programmer-Defined Functions
 
Programmer-Defined Functions Functions allow the programmer to modularize a program. All variables declared in function definitions are local variables—they are known only in the function in which they are defined. Most functions have a list of parameters that provide the means for communicating information between functions via function calls. When a function is called, the arguments in the function call are assigned to the corresponding parameters in the function definition. A function’s parameters are also considered to be local variables. Several motivations exist for modularizing a program with functions. The divide-andconquer approach makes program development more manageable. Another motivation is software reusability—using existing functions as building blocks to create new programs. With good function naming, programs can be created from prepackaged functions rather than being built using customized code. For example, we did not have to define how to convert strings to integers and floating-point numbers—WMLScript already provides method parseInt to convert a string to an integer and method parseFloat to convert a string to a floating-point number. A third motivation is to avoid repeating code in a program. Packaging code as a function allows that code to be executed at different points in a program by calling the function. Software Engineering Observation 16.2 Each function should be limited to performing a single, well-defined task and the function name should effectively express that task. This promotes software reusability. 16.2 Software Engineering Observation 16.3 If you cannot choose a concise name that expresses what the function does, it is possible that your function is attempting to perform too many diverse tasks. It is usually best to break such a function into several smaller functions. 16.3
189 times read
|
|
|
|