Chapter 3: Extending the Basic Language

Total Page:16

File Type:pdf, Size:1020Kb

Chapter 3: Extending the Basic Language

Chapter 3: Extending the basic language

This chapter will focus on the mechanisms used in all computer languages to extend the language beyond what is possible with the basic statements and expressions. This is done through providing built-in procedures and ways for programmers to define their own procedures. There are variations in the details of the mechanisms and the terminology. Because this is the most important concept in programming, other chapters will include discussion on this topic as well. After studying this chapter, you will  understand what is meant by function and procedure  understand what is meant by programmer defined procedure or function  understand the distinction between defining a procedure and invoking a procedure  acquire experience using built-in facilities and defining your own functions using HTML and JavaScript

Motivating Example The examples for the chapter show a web page that changes depending on different conditions.

Figure 1 shows a Web page with one line of text against one background. Note that HTML tiles the image specified in the background attribute to fill the screen.

Figure 1. Web page with bird background.

Figure 2 shows another version of the same Web page. This one has a different background.

1 Figure 2. Web page with frog background. In one implementation, this application is constructed so that each time the document is invoked by the browser, the background is determined by a pseudo-random procedure. In a variation of this application, the internal clock is consulted and if it is midnight to noon, one background is chosen; otherwise, the other background is displayed. The critical features required by these examples include  a way to simulate randomness such as would be achieved by flipping a coin or rolling dice so that something can occur without any obvious pattern  access to the time-of-day

Introduction to concepts Though examples of built-in procedures have slipped into the earlier sample applications, the official topics have included only assignment statements with operators such as addition and multiplication and combination statements such as conditionals and looping. In a theoretical sense, this is practically all you need. (The hedging here is because building the human-computer interface (HCI) and providing the pseudo-random feature found in many games are tasks requiring additional facilities beyond basic calculations.) However, all computer languages provide ways for the programmers to incorporate such things as common mathematical functions in expressions without the effort of writing out all the steps. The developers of different programming languages would not find any customers if it were necessary to re-code these common procedures. Procedures such as common mathematical functions typically take inputs, called arguments, and produce results, the returned values. For example, the "square of a number" is a function for which the argument is the given number (say, 3) and the returned value is its square (in this case, 9). Some procedures are not like mathematical functions and perform some action without returning any result. For example, a

2 procedure in a game may fire a (virtual) cannonball into the air. Certain languages distinguish in terminology and syntax between procedures that return results and ones that do not. JavaScript and ActionScript do not. Computer languages typically provide other facilities in addition to mathematical functions, for example, implementing interface functions, control of special devices, interactions with the operating systems and other programs, or simply implementing code that have proven useful in the past. One relatively new notion is that since development of software is so difficult, programmers should re-use proven code as opposed to re- inventing everything themselves for each new project. This is a change from the early days in which each programmer essentially did everything to build each new application. HISTORICAL NOTE: After establishing a systematic mechanism for enhancing the language to make a more comprehensive, usable product, the developers realized that programmers also may want to add to the base language. This motivated the development of programmer-defined procedures: give programmers a way to define sets of statements, give each set a name, and specify where the named set of statements are to be invoked in a program. (Note: sometimes these are called user-defined procedures, but that phrase can be confusing since it is not the end-user of the finished application, but the creator of the application that is the user in this situation.) The mechanism to define new procedures helps teams of people share programs or parts of programs. For example, it can be useful to share and re-use sets of values or ways that programs may interact. Building an application is best done by dividing the project into parts. Defining procedures or functions is a part of this. Description: procedures, functions, methods The formal way that these additions are provided varies across the different languages. For example, some programming languages provide global procedures that can be used anywhere. In Chapter 1, you read about two Flash global procedures: stop and goToAndPlay that each affect the flow of control from frame to frame. Some languages support a construct called classes and objects in which data and code are tightly coupled. This subject will be expanded further in later chapters. Briefly, for now, classes hold the definition of data and procedures, called methods, for manipulating the data. Objects are instances of specific classes in the way in which whole numbers are instances of a data type called integer. Certain methods are designated as class methods and are independent of any specific instance. The Math class and its class methods, for example, Math.floor(value) will be used in the sample applications in this chapter and several others. Some languages do everything with classes and objects, some use global procedures and some do both. EXAMPLE: The application using random processing will use the built-in class method Math.random(). The application using the time-of-day will use the Date object and the getHours method.

3 Description: accessing built-in facilities Computer languages have built-in features including basic mathematical functions and other facilities. To indicate the variety but also the similarity in the features, here are some examples. TECHNICAL NOTES: Some languages require programmers to take explicit steps to incorporate the built-in facilities needed, perhaps providing a way of specifying a list of libraries during the compilation step or a later linking step or adding special statements, called header or include statements, in the program itself to specify what is required. To put it another way, these things are part of the language and you can get them whenever you want, but you may need to specify what you need. A variation of this is that putting one special type of statement at the start of your code means that the references in the program can be relatively simple. In Java, the start of a program file may include statements such as import java.lang.*; This tells the compiler (Java programs go through a translation process called compilation) that code in this file may make use of classes, methods and properties in the lang class of the java package using an abbreviated form of the name. For example, this means the code can use Math.PI instead of java.lang.Math.PI. It is possible to omit the import statement and use the long form. Python, a language used by itself or as the scripting language in conjunction with other software, also has an import construct. The following two lines would appear in a Python script to indicate that this script made use of other scripts: import Blender from Blender import NMesh

These specific statements (with, perhaps, some others) are necessary to use Python with Blender, an Open Source 3D modeling tool. While the term is the same and one can say the final results are similar, the import statement in Python essentially brings in the full text of the original documents to be interpreted and executed on the spot. Generally, these are statements that define procedures and variables and do not have immediate consequences, but it may be necessary to be aware of the distinction between establishing ways of reference versus actual inclusion into the file. The following is an example of what is required in C++. #include using namespace std;

This brings in a small file, called a header file, so that the compiler can properly check and translate the use of certain input/output commands. END OF TECHNICAL NOTES JavaScript is a small enough language so that all the built-in facilities are available without any explicit action. The Application section in this chapter will show the way to

4 include programmer code, perhaps your own code written previously, for use in a new document. The JavaScript mechanism is similar to Python: the old file is brought into the new document. Assuming any necessary steps are done to signal that the needed built-in or previously developed features will be used, your code can make use of the features in the statements in your program. There are three main formats:  The built-in feature can be invoked using a procedure call. In Chapter 1, you saw goToAndPlay(nextstep); This is referred to as a procedure call. Something is done! Some languages call these procedures that do not produce and return values subroutines.  The built-in feature is a procedure that returns a value. As stated previously, the term 'function' is sometimes reserved for this situation, but this is not the case in JavaScript, where function means a procedure with or without a returned value. Two examples of this were shown in Chapter 2 in combination dievalue = 1+ Math.floor(Math.random()*6); and will be used in later chapters to 'throw dice'. Formally speaking, the Math.random is an example of a class method of the built-in Math object. What it does is produce a value between zero and 1 that changes every time it is called. The opening and closing parentheses following it indicate that it is a function, but has no parameters. The Math.floor is another class method of the Math object. It does have an argument. This Math method produces the largest integer not bigger than its argument. You may think of it as rounding down or truncating a number. The value of Math.floor(1.34518) would be 1.

The application in Chapter 2 made use of a method for string objects. The code totals.substr(0,dp+3); performed a calculation on the string held in the variable totals. The calculation was to extract a portion of the string based on the two arguments.  Built-in features can be provided using data associated with objects, also called properties or attributes. Objects will be discussed further in later chapters. For example, in JavaScript, totals.length yields the length of the string totals. It should be noted that some languages will provide the way to determine the number of characters in a string as a function with an argument and not as a method: length(totals)

Another example of a property is the way JavaScript provides the value of pi, the

5 mathematical constant the expresses the ratio of the circumference of any circle to its diameter: Math.PI This is a class variable of the class Math. Again, later chapters will address objects and classes. Description: programmer-defined procedures Programming languages provide a way for you, the programmer, to make the same kinds of extensions to the base language as done by the developers of the language when constructing the built-in facilities. Assuming this is done, your code can contain calls to the procedures, functions, methods and properties. The 'assuming this is done' can be misleading. For example, if you decide to define a function that computes the value of a commission based on information on sales, you may work on the parts of the program that use this function before you actually write it. Two conditions must be met. The first is that eventually you do write the function definition or locate a copy of pre-existing code for the function definition. The second is that the language processor processes this definition before reaching the statements that make use of it. The function definition and the invocation of the function are distinct. A programmer-defined procedure is a set of statements. These statements perform a well-defined task that has meaning for the programmer. The procedure can make use of arguments: extra information to customize the procedure for the specific situation. The mathematical functions sine and absolute value were cited earlier in this section. Some languages refer to the extra information as arguments in the calling of the procedure and parameters when in the procedure. In this text, we take a more informal approach. The question for new programmers generally is why or when to define your own procedures, functions or classes. Unfortunately, the decision may not be clear cut. One reason is to avoid entering the same code two or more times. Another reason is to make the code easier to read. A related reason is to help in the creation process by dividing large tasks into smaller ones. If one program is very long, do look for ways to split it up into parts. REAL-LIFE NOTES: Analogies can be made to every day life concerning the definition of procedures. When you offer to give directions to someone, say to an office on campus or to the library in a particular town, you may ask the person, "do you know how to get to …." and, if they do, give the directions from that point. Your complete directions are: go to X and then do these several things to get to the final destination. If you are sharing a cooking recipe, you make use of what the listener already knows. If they know how to make pasta, you say "make pasta" and do not talk about boiling water. This gives you the opportunity to spend most of the time on describing your great sauce! Continuing with the cooking pasta example, there is an analogy to arguments. You can say "make the pasta using linguini and make it 'al dente'. In this case, the procedure is make pasta and two arguments are the type of pasta and a phrase indicating how hard or soft to make the final product. Other function calls could be make pasta linguini, soft make pasta orzo, soft

6 make pasta spaghetti, al dente The person giving the orders and the person hearing and acting on them need to agree on what the parameters are, for example, what al dente means. This is directly analogous to the situation in programming in which the calling statement and the procedure as defined must agree on the use of any arguments. END OF REAL-LIFE NOTES TIP: Most programming languages provide ways to build programs that make use of other programs you have written as well as the built-in programs. The benefit of this approach is not evident if you and only you create one and only one program. However, if you are working on a project involving other programmers, you create your own programs and then do what has to be done to include or establish references to the other people's work. If you are making several programs, you will appreciate the value of producing code, testing and making sure it works, and then re-using it again and again. Writing a program or procedure generally involves a format for the first or header line. This includes a specification of any inputs (arguments) required by the procedure. Some languages allow arguments to be optional, and, some of those provide a way to set a default value. The header line may indicate whether or not this is a procedure that returns a value so that it can be used in an expression. The format for procedure specifies some bracketing symbols or line indentation and formatting to demarcate the statements of the procedure. EXAMPLE: The examples will make use of programmer-defined procedures to make the determination of the background for the web page. Reading checks 1. Describe what is meant by a procedure in programming languages. 2. Describe the way Java, Python or C indicate that certain built-in procedures are to be used in the application. 3. What is the value of Math.floor(X) when X holds the value 21.42? 5.003? .3333?

Application In this section, we first revisit the sample programs used in previous chapters using the terminology of procedures, functions, and methods. You will see modifications of the Coffee Shop application that demonstrate function, function calls and the use of external scripts. Then you will create a new Webpage in which the background changes either randomly or based on the time of day.

Review of previous examples As has been indicated, the Flash example in Chapter 1 made use of built-in procedures:

stop(); goToAndPlay(nextstep); goToAndPlay(1);

7 These are global functions in Flash. They change the flow of control from frame to frame. The stop function does not take an argument; hence the empty parentheses. The goToAndPlay function does, namely the label for the frame that control is to go to in the Flash movie. In Chapter 2, the Document Object Model defining the interplay between JavaScript coding and the HTML document was used to extract and modify what was on the screen. The onSubmit attribute value for the

element was set to

return addup(); where addup was a function defined in the tag. TIP: The particular example of formatting money suggests another reason to separate this functionality from the rest of the application. Ignoring the issue that the text on the page is in English, this money function that formats for dollars-and-cents could be exchanged for one that does formatting for other currencies, such as euros or yen. See the exercises for a variation on this approach. You may choose to put all the JavaScript coding in one or more external files and have no internal scripting. Now it is time to go on to the implementation of the motivating examples for this chapter. Description of application You probably have visited a Web site with a changing background. The changes may be based on some condition or be totally random. The issue of randomness deserves attention. How, if everything is to be programmed and there are no little men with dice inside the computer, do you, the programmer, arrange for something to occur randomly? The answer is provided by built-in features available in most programming languages. They are called 'pseudo-random' because the way the language processor produces the random results is based on a fixed procedure. The developers of the language claim that the random facility produces numbers in a set range with equal probabilities and with no discernible pattern. The specific functions available for pseudo-random behavior do vary. Some produce integers within a specified range; others, such as that available in JavaScript, produce a number, a fraction, between zero and 1. With a value such as this and some mathematical manipulation, you can simulate random events. Plan of attack The background of a Web page can be set by the background attribute in the element. However, it is possible to change this in code using an assignment statement with the left hand side (the target) as follows: document.body.background = … The choice of what to assign will be made in the true and false clauses of an if statement. The condition for the if statement will involve a call to Math.random. The code with the if statement will be defined in a function and the function will be defined in the