Function Definitions
Function Definitions Thus far, we have discussed existing functions that are built into WMLScript objects. We now consider how programmers write their own customized functions and call them in a script. Consider a script (Fig. 16.2) that uses a programmer-defined function count to obtain a number from the user, convert it to an integer and call a second programmer-defined funcChapter 16 WMLScript: Functions 285 © Copyright 2001 by Deitel & Associates, Inc. All Rights Reserved. review Packet 5/7/01. tion square. The function square calculates the square of the integer supplied by the user. Lines 6 and 7 var inputNumber = Dialogs.prompt( "Enter a number to be squared", "" ); prompt the user for a number and store that number as a string into the variable input- Number. On line 8, the function square (defined at line 16) is invoked or called with the expression var numberSquared = square( Lang.parseInt( inputNumber ) ); In fact, the () represent the function call operator, which has high precedence. At this point, the variable inputNumber (the argument to the function call) is converted to an integer using Lang.parseInt, a copy is made by the program and program control transfers to the first line of function square. Function square receives the copy of the value of inputNumber in the parameter y. Then square calculates y * y. The result is passed back to the point in line 8 where square was invoked and stored in the variable numberSquared. The statement on lines 9 and 10 concatenates the value of the variable inputNumber, " squared is ", and the value of the variable numberSquared, The resulting string is stored in the browser variable result1 which is displayed in the associated WML document. The definition of function square (line 16) shows that square expects a single parameter y—this will be the name used in the body of function square to manipulate the value passed to square from line 8. Note that the WMLScript keyword var is not used to declare variables in the parameter list of a function. The return statement in square passes the result of the calculation y * y back to the calling function. 1 // Fig. 16.2: squareNumbers.wmls 2 // Programmer defined functions 34 extern function count() 5 { 6 var inputNumber = Dialogs.prompt( 7 "Enter a number to be squared", "" ); 8 var numberSquared = square( Lang.parseInt( inputNumber ) ); 9 var outputSquare = inputNumber + " squared is " 10 + numberSquared; 11 12 WMLBrowser.setVar( "result1", outputSquare ); 13 WMLBrowser.go( "#result" ); 14 } 15 16 function square( y ) 17 { 18 return ( y * y ); 19 } Fig. 16.2 Using programmer-defined functions to square a number. 286 WMLScript: Functions Chapter 16 © Copyright 2001 by Deitel & Associates, Inc. All Rights Reserved. review Packet 5/7/01. Common Programming Error 16.1 Using the WMLScript var keyword to declare a variable in a function parameter list results in a WMLScript runtime error. 16.1 Note that function square follows the rest of the script. When the count function terminates, WMLScript will not continue to flow sequentially into function square. A function must explicitly be called for the code in its body to execute. Good Programming Practice 16.2 Place a blank line between function definitions to separate the functions and enhance program readability. 16.2 Software Engineering Observation 16.4 Statements that are enclosed in the body of a function definition will not be executed by the WMLScript interpreter unless the function is explicitly invoked (called) 16.4 Figure16.3 shows the WML document that is used to call the count function in Figure16.2. The document is simple; it contains only two cards. One card provides a soft key (lines 10–12) that is used to call the count function and the other displays the output. 1 <?xml version="1.0"?> 2 <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD 3 WML 1.2//EN" "http://www.wapforum.org/DTD/wml12.dtd"> 45 <!-- Fig. 16.3: fig16_3.wml --> 6 <!-- Squaring Numbers --> 78 <wml> 9 <card id="index" title="Number Squared"> 10 <do type="accept" label="OK"> 11 <go href="squareNumbers.wmls#count()"/> 12 </do> 13 14 <p> 15 Press OK to square a number. 16 </p> 17 </card> 18 19 <card id="result" title="Results" > 20 <do type="accept" label="Home" > 21 <prev/> 22 </do> 23 24 <p> 25 $result1 26 </p> 27 </card> 28 </wml> Fig. 16.3 Squaring a number using programmer-defined functions. Chapter 16 WMLScript: Functions 287 © Copyright 2001 by Deitel & Associates, Inc. All Rights Reserved. review Packet 5/7/01. Lines 10–12 <do type="accept" label="OK"> <go href="squareNumbers.wmls#count()"/> </do> add a soft key to the card. Line 11 contains the go element that calls the count function located in the WMLScript document squareNumber.wmls. Earlier we showed that the count function prompts the user for a number, squares it, and then sends the user to another card where the result is displayed. The result is shown on line 26 using $result to reference the variable set by the count function. The format of a function definition is extern function function-name ( parameter-list ) { declarations and statements } Fig. 16.3 Squaring a number using programmer-defined functions. 288 WMLScript: Functions Chapter 16 © Copyright 2001 by Deitel & Associates, Inc. All Rights Reserved. review Packet 5/7/01. The function-name is any valid identifier. The parameter-list is comma-separated and contains the names of the parameters received by the function when it is called (remember that the arguments in the function call are assigned to the corresponding parameter in the function definition). There should be one argument in the function call for each parameter in the function definition. If a function does not receive any values, the parameter-list is empty (the function name is followed by an empty set of parentheses). The declarations and statements within braces form the function body. The function body is also referred to as a block. A block is a compound statement that includes declarations. Common Programming Error 16.2 Forgetting to return a value from a function that is supposed to return a value is a logic error. 16.2 Common Programming Error 16.3 Placing a semicolon after the right parenthesis enclosing the parameter list of a function definition results in a WMLScript runtime error. 16.3 Common Programming Error 16.4 Redefining a function parameter as a local variable in the function is a logic error. 16.4 Common Programming Error 16.5 Passing to a function an argument that is not compatible with the corresponding parameter’s expected type is a logic error and may result in a WMLScript runtime error. 16.5 Good Programming Practice 16.3 Although it is not incorrect to do so, do not use the same name for an argument passed to a function and the corresponding parameter in the function definition. This avoids ambiguity. 16.3 Good Programming Practice 16.4 Choosing meaningful function names and meaningful parameter names makes programs more readable and helps avoid excessive use of comments. 16.4 Software Engineering Observation 16.5 A function should usually be no longer than one printed page. Better yet, a function should usually be no longer than half a printed page. Regardless of how long a function is, it should perform one task well. Small functions promote software reusability. 16.5 Software Engineering Observation 16.6 Scripts should be written as collections of small functions. This makes programs easier to write, debug, maintain and modify. 16.6 Software Engineering Observation 16.7 A function requiring a large number of parameters may be performing too many tasks. Consider dividing the function into smaller functions that perform the separate tasks. The function header should fit on one line if possible. 16.7 Chapter 16 WMLScript: Functions 289 © Copyright 2001 by Deitel & Associates, Inc. All Rights Reserved. review Packet 5/7/01. Software Engineering Observation 16.8 Modularizing programs in a neat, hierarchical manner promotes good software engineering, sometimes at the expense of performance. 16.8 Performance Tip 16.2 A heavily modularized program—as compared to a monolithic (i.e., one-piece) program without functions—makes potentially large numbers of function calls, and these consume execution time and space on a computer’s processor(s). But monolithic programs are difficult to program, test, debug, maintain and evolve. So modularize programs judiciously, always keeping in mind the [ balance between performance and good software engineering. 16.2 Testing and Debugging Tip 16.1 Small functions are easier to test, debug and understand than large ones. 16.1 Some functions perform simple tasks, such as the addition of two numbers. Instead of including this code in the body of a function, a user-defined function may be created to perform this task which will be called by another function. When this separate function is called, control is given to that function. There are three ways to return control to the point at which a function was invoked. If the function does not return a result, control is returned when the function-ending right brace is reached (the end of the function) or by executing the statement return; If the function does return a result, the statement return expression; returns the value of expression to the caller. When a return statement is executed, control returns immediately to the point at which a function was invoked. The script in our next example (Fig. 16.4) uses a programmer-defined function called maximum to determine and return the largest of three floating-point values. 1 // Fig 16.4: maximum.wmls 2 // Using the max function 34 extern function max() 5 { 6 var num1 = Lang.parseFloat( WMLBrowser.getVar( "number1" ) ); 7 var num2 = Lang.parseFloat( WMLBrowser.getVar( "number2" ) ); 8 var num3 = Lang.parseFloat( WMLBrowser.getVar( "number3" ) ); 9 var maxNum = maximum( num1, num2, num3 ); 10 11 WMLBrowser.setVar( "maximumNumber", maxNum ); 12 WMLBrowser.go( "#maximum" ); 13 } 14 15 extern function maximum( x, y, z ) 16 { Fig. 16.4 WMLScript function which returns the largest of three numbers. 290 WMLScript: Functions Chapter 16 © Copyright 2001 by Deitel & Associates, Inc. All Rights Reserved. review Packet 5/7/01. Lines 6–8 declare and initialize the variables num1, num2 and num3. These variables store three numbers input by a user. We use the WMLBrowser object’s getVar method to obtain the values of three variables from our WML document. Arguments number1, number2 and number3 passed to the getVar method are references to three input elements found on the first card of the WML document shown in Fig.16.5. Once the values have been obtained, the method parseFloat is used to convert the strings input by the user to floating-point values. The statement at line 9 var maxNum = maximum( num1, num2, num3 ); passes the three floating-point values to function maximum (defined at line 15), which determines the largest floating-point value. This value is returned to line 9 by the return statement in function maximum. The value returned is assigned to variable maxNum. The value of maxNum is stored in the browser variable maximumNumber (line 11) using the setVar method. This value is displayed in the WML document shown in Fig.16.5. Notice the implementation of the function maximum (line 15). The first line indicates that the function takes three parameters (x, y and z). The body of the function contains the statement return Lang.max( x, Lang.max( y, z ) ); which returns the largest of the three floating-point values using two calls to the Lang object’s max method. First, method Lang.max is invoked with the values of variables y and z to determine the larger of these two values. Next, the value of variable x and the result of the first call to Lang.max are passed to method Lang.max. Finally, the result of the second call to Lang.max is returned to the point at which maximum is invoked (line 9). Note once again that the script terminates before sequentially reaching the definition of function maximum. The statement in the body of function maximum is executed only when the function is invoked from line 9. Figure 16.5 shows the WML document that takes the user’s input, calls the max function and displays the largest of the three numbers input by the user. 17 return Lang.max( x, Lang.max( y, z ) ); 18 } Fig. 16.4 WMLScript function which returns the largest of three numbers. 1 <?xml version="1.0"?> 2 <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD 3 WML 1.2//EN" "http://www.wapforum.org/DTD/wml12.dtd"> 45 <!-- Fig. 16.5: fig16_5.wml --> 6 <!-- Using the max function --> 78 <wml> 9 <card id="index" title="Max Function"> 10 <do type="accept" label="Next"> 11 <go href="maximum.wmls#max()"/> 12 </do> Fig. 16.5 WML listing that calls a programmer-defined function. Chapter 16 WMLScript: Functions 291 © Copyright 2001 by Deitel & Associates, Inc. All Rights Reserved. review Packet 5/7/01. 13 14 <p> 15 Enter first number: 16 <input name="number1" value=""/><br/> 17 Enter second number: 18 <input name="number2" value=""/><br/> 19 Enter third number: 20 <input name="number3" value=""/> 21 </p> 22 </card> 23 24 <card id="maximum" title="Maximum"> 25 <do type="accept" label="Home"> 26 <go href="#index"/> 27 </do> 28 29 <p> 30 First number: $number1 <br/> 31 Second number: $number2 <br/> 32 Third number: $number3 <br/> 33 Maximum is: $maximumNumber 34 </p> 35 </card> 36 </wml> Fig. 16.5 WML listing that calls a programmer-defined function. 292 WMLScript: Functions Chapter 16 © Copyright 2001 by Deitel & Associates, Inc. All Rights Reserved. review Packet 5/7/01. Lines 15–20 Enter first number: <input name="number1" value=""/><br/> Enter second number: <input name="number2" value=""/><br/> Enter third number: <input name="number3" value=""/> contain three input elements that obtain numbers from the user. The name attributes for the elements are set to number1, number2 and number3. The names are important when accessing the values from the script. You may recall that in Fig. 16.4, the WMLBrowser object’s getVar method accesses the values of these input elements by referencing their names. The result card also references these values on lines 30–32. In line 33, we display the maximum of the three numbers by using $maximumNumber, which references the variable set by the maximum function in Fig.16.4.
937 times read
|