Chapter 6: Functions and parameters

This chapter will continue the study of programmer-defined functions started in previous chapters, with focus on function parameters. The chapter also addresses the topic of how to encode features of the application such as the rules of a game. After studying this chapter, you will

·  understand the role of function parameters

·  learn how different programming languages provide the function parameter feature and some of the different terminology used

·  understand what is meant by program state and how variables are used to represent the state

·  appreciate how aspects of a representation or encoding can be arbitrary

·  acquire experience using function parameters, arrays, global and local variables, and cel animation in Flash with ActionScript.

Motivating Example

The examples for this chapter are computer versions of the playground game, rock-paper-scissors. Two versions will be described: one with text results and the other with animated results, taking advantages of the facilities of Flash.

An opening screen for the game is shown in Figure 1.

Figure 1. Opening screen shot for rock-paper-scissors.

The 3 pictures on the screen are actually buttons. When the player clicks on one, say rock, the program makes a choice for 'the computer'. In Figure 2, the program indicates a tie because both player and computer have chosen the same thing, the rock.

Figure 2. Screen shot showing a tie.

In Figure 3, the screen displays that the computer has won, since the player clicked on paper and the computer selected scissors. This design does depend on the player remembering his or her choice and having the faith that the program is fair. In this instance, 'fair' means that the computer's choice is based on a random calculation and not knowledge of the player's move.

Figure 3. Screen shot indicating computer win.

A fancier version of the game makes use of the animation features of Flash. In this version, the player's moves and the implementation of the rules of the games are the same. However, depending on which of the 3 non-tie results happens, the player is treated to a short (very short) animation illustrating the result. The next set of screen shots show this for the rock breaks scissors situation. In Figure 4, the rock is partially off the Stage (above the stage). When the published version is shown, the rock will appear to fall from above onto the scissors.

Figure 4. Screen shot of start of animation for rock breaks scissors.

In Figure 5, the rock is falling towards the scissors:

Figure 5. The rock nears the scissors.

In Figure 6, the rock hits the scissors:

Figure 6. The rock is on top of the scissors.

Next, Figure 7 shows the rock on top of the scissors.

Figure 7. The rock has crushed the scissors.

In the last frame of the animation, shown in Figure 8, pieces of the scissors are shown flying off.

Figure 8. Pieces of the scissors fly off.

A similar sequence is created for the two other situations: paper covering rock and scissors cutting paper.

The critical features required by this application include

·  a mechanism for the player to indicate his or her move

·  pseudo-random facilities to produce the computer move

·  ways for the program to display the results

·  incorporating the rules of the game into the program

·  animation: techniques to produce changing displays so that the player sees movement

Introduction to concepts

As was described in previous chapters, all programming languages provide programmers a way to extend the language by defining their own procedures, pieces of code that can be invoked by name. One reason to do this is to avoid writing the same code multiple times. When a procedure is defined, it can be called (invoked) from multiple places. Programming languages have built-in procedures and also provide a way for programmers to define their own procedures.

TECHNICAL NOTE: The terminology varies. In some languages, a function is a procedure that returns a value so that the function call can occur within an expression or wherever an expression can occur, for example, the right side of an assignment statement. In some languages, subroutines are procedures that do not return values. The strongly-typed languages require definition of the datatype of the returned value in the definition of the procedure.

Methods are procedures defined as part of the definition of a class. A class defines code (the methods) and data (called properties or attributes that the methods act on). Strings are implemented in JavaScript and ActionScript as instances of a String class. If a variable is assigned a string literal, as in

title = "Logic";

then you can write code making use of String properties

title.length

and String methods

title.substring(a,b)

There are many other String methods.

NOTE: JavaScript and ActionScript use the term 'function' for any procedure, returning a value or not, so, for the most part, that is the terminology of this book. However, here and elsewhere, you will find some examples of other languages.

Procedures can be called with extra information, a folksy way of describing what you have seen go in-between the parentheses after the function name as part of the call. Here again, terminology differs. Some languages refer to the values in the call as arguments and the values in the procedure definition as parameters.

Games and other applications often require aspects of the application to be encoded in some way in the program. This encoding can take different forms and you will read about strategies in this and other chapters. One subtle point is that often the encodings are arbitrary, that is, totally up to you, the programmer. Many different ways would work. This arbitrariness can be unsettling. Every application has its own distinct set of representation issues, but we hope the rock-paper-scissors example and then the others in this text will contribute to your programming education.

EXAMPLE: The examples will feature calling one procedure with different parameters. The parameter will indicate the player move. The rules of the game will be encoded in logical statements: a sequence of if statements. The animated rock-paper-scissors example will demonstrate a basic facility of the Flash system: cel or frame by frame animation. The Flash-specific mechanism of control passing from frame to next frame or to a specified frame can be compared to flow of control in procedures.

Description: procedure definition header line

A programmer-defined procedure is defined in different programming languages by a header or prototype line with a mixture of keywords; sometimes called modifiers, that specify attributes of the procedure; the programmer-given name of the procedure; and names and, with some languages, datatype information for the parameters. If the procedure returns a value, the strongly-typed languages require datatype information on the returned value. In JavaScript and ActionScript, the header takes the following format:

function functionname (parametername1, parametername2…)

The keyword function is required and must be spelled correctly! What is indicated here as functionname is up to the programmer. Generally, names need to start with a letter and cannot have blanks.

TIP: Make function names, variable names, and parameter names meaningful even if that means making them longer. We refer to this as not economizing on typing. You will spend more time examining your code than typing it.

If there are no parameters, then the functionname is followed by opening and closing parentheses. If there are parameters, then when the function is invoked, the values specified in the call are given the parameter names for use 'in' the function. Using the rock-paper-scissors example, if the function starts with the header statement

function computerturn (player)

and the function is called with the statement

computerturn("rock");

the technical jargon is that "rock" is passed as the parameter. In the function computerturn, whenever code refers to player, as in

if (computer==player)

player will have the value "rock" unless player has been assigned a different value earlier in the function. The parameter player is treated as a local variable with the value set by the call. When computerturn completes, the variable is no longer accessible.

TECHNICAL NOTE: In the implementation of most programming languages, space for the local variables is assigned in the memory circuitry of the computer when a function is invoked. When the function completes, the association between the locations in memory and the variable names goes away and the memory is available for other purposes.

Examples in Java

The general notion of parameters applies to other programming languages, but some of them have other mechanisms concerning parameters. As you may guess if you think about what have been described as strongly-typed languages, the parameter definitions also must contain datatype information. In Java[1], a class is a way of specifying a combination of procedures and variables. An object or object instance can be declared to be of the class. The procedures are called methods. Without going into too much detail at this time on the definition of classes, the definition of a method for building a rectangle object could start with

public Rectangle (float x1, float y1, float x2, float y2)

This method would be part of a class definition for objects of type Rectangle. The modifier public means that statements in other classes in other files can invoke this method. This method builds the rectangle. It accepts 4 parameters, indicating two opposing corners of the rectangle, each as floating point numbers. It is assumed that the other two corners are at (x1, y2) and (x2, y1). Specifying the datatype of the parameters means that the compiler can do type checking for all uses of the parameters inside the function. It also means the compiler does type checking for the calls of the function. This last leads to a feature of Java called method overloading. Programmers can specify different versions of a method with the same name, the versions differing based on different definitions for the parameters. These are sometimes called different signatures or prototypes. For example, for rectangles, a programmer may decide that it is useful to think of default situations. The method starting off (with prototype)

public Rectangle (float x, float y)

will build the rectangle with corners at (0,0), (x, 0), (0,y), and (x, y).

The method starting off

public Rectangle (float side)

will build the rectangle, which happens to be a square, with corners (0,0), (0,side), (side,0) and (side, side).

The compiler examines each call of the method and chooses the one with the corresponding signature.

There is one more feature of procedures that is specified in Java and certain other languages: the return value. You may have seen the following as the prototype of the method required for any Java program:

public static void main(String args[])

The void modifier indicates that this method does not return any value. If a programmer wanted to specify a method that returned a value of a certain datatype then the prototype would follow the format

modifiers datatype functionname (parameter types and names)

Let us assume there was a method in the rectangle class named contains that accepted two values of datatype double representing the x and y coordinates of a point and returned true if this point was in the rectangle and false otherwise. The prototype would be

public Boolean contains(double x, double y)

This indicates that the method returns a value of true or false. The compiler can check that contains is invoked in places that require Boolean values, such as the condition expression of if statements.

END OF JAVA EXAMPLES

Description: call by value versus call by reference

The discussion so far has focused on use of the parameter values. What if the code changes the parameter value, that is, the variable in the procedure holding the parameter that was passed? When local variables are changed, the change lasts as long as the variable last, only until the procedure ends. If a procedure is called with a variable A as one of the parameters, and that parameter is changed in the procedure, will the variable A be changed when the procedure is complete and control returns to the point of the call? The answer is: it depends. In JavaScript, the parameters are called by value. This means that the value of the parameter is calculated and passed to the called procedure. The opposite of this is call by reference. In this case, what is passed to the procedure is a reference to the variable and so the variable itself will be changed if it is changed within the called procedure. In some languages, the programmer has a choice and can specify which of the two it is to be for each parameter.

An exception to the 'call by value' rule in JavaScript concerns arrays. Recall that an array is a sequence of values. In the rock-paper-scissors example, an array will be used to hold the three strings "rock", "paper", and "scissors". The JavaScript processor passes a copy of header type information about an array when an array variable is named in the function call. This information allows the called program to make some changes to the original array, such as changing one of the elements. The following HTML/JavaScript file demonstrates this:

<html>

<head>

<script>

var origa = [1, 2, 3];

testparms(origa);

alert("This is origa after the call: "+origa);

function testparms (a) {

a[1] = "Hello";

}

</script>

</head>

<body>

nothing

</body>

</html>

The sequence of operations, also referred to as the flow of control, is as follows:

load script element

execute var statement setting up the variable origa as an array

set up definition of the testparms function

execute call of testparms, using origa as the parameter

execute the statements in testparms, with a set to be origa

return from testparms

execute alert statement

load body element

[The purpose of this exercise is to see what appears in the alert box. After clicking on the OK for the alert box, the <body> element is loaded and the word nothing appears on the screen.]