A WebBased Introduction to Programming Chapter 13 Program

A Web-Based Introduction to Programming Chapter 13 Program Modularity – Working with Functions and Objects Chapter 13

Intended Learning Outcomes Summarize the importance of modular approaches. Describe key characteristics of functions. Explain the purpose of arguments and parameter lists. Call a function using the function name and any arguments. Write code that receives a value returned by a function call. Find and use common pre-defined PHP functions Use the PHP die() or exit() function to end an application's execution • Create a new function and use this in a PHP application. • • Chapter 13

Intended Learning Outcomes • Create and save a library of useful functions. • Include and use a library of functions. OPTIONAL SECTION (OBJECT ORIENTED PROGRAMMING) • Summarize the general structure and purpose of an object. • Interpret a class definition for a simple object. • Create a simple object class. • Create and use instances of a simple object using the object's Application Programming Interface (API). • Explain common OOP terminology. . Chapter 13

Introduction • Modern software design focuses on code modularity: – Separate, functional code components to maximize reusability and minimize duplication. • Code modularity extends beyond individual applications to facilitate interoperability: – Communications between applications worldwide – Common code and interface standards Chapter 13

Working with Modules • Code should be developed in small modules that perform well-defined tasks. – Permits code to be used in multiple applications – Speeds up development and testing – Encourages collaboration, standards, resuability • Good programmers look for pre-existing code modules before writing their own code. Chapter 13

Working with Modules • Code modules are called functions, methods, sub-programs, sub-routines, or procedures. • We will use the term function. • Each function has a function name and contains code to perform a well-defined task. • What PHP functions have you already used? Chapter 13

Standard PHP Functions • You know these pre-defined PHP functions: pow(), pi(), round(), ceil(), floor(), and random() all perform mathematical operations fopen(), fclose(), feof(), fputs() and fgets() all process text files list(), explode(), trim(), strtoupper(), strtolower(), and number_format() all work with strings. • PHP provides more than 700 pre-defined functions! Chapter 13

Using Functions • To use a function you do not need to know how it actually works, you only need to know four things: 1. What is the name of the function? 2. What task does the function perform? 3. What input does the function need to perform its task (what arguments, if any, must you send to the function) 4. What output does the function generate (what type of value, if any, does the function return to your program when it completes its task)? Chapter 13

Example the pow() function • The function name is pow() • The purpose is to multiply a value by itself the number of times indicated by an exponent • The arguments are the base value and the exponent • The return value is the result of this operation. – For example, pow(2, 3) will return 8 • This is all you need to know in order to use the pow() function in your programs Chapter 13

Understanding Function Arguments • Many functions, including the pow() function, need to receive values in order to perform their task. • These values called function arguments. • Arguments are listed between the parentheses that follow the function name. • The pow() function requires two arguments, the base value followed by the exponent. • Multiple arguments must be listed in the correct order! Chapter 13

Understanding Function Arguments • Different functions require different numbers of arguments. – pi() does not require any arguments since it simply returns the value of PI (you must still supply the parentheses). – strtoupper() requires a single argument, for example strtoupper("London") – feof() takes a single argument, for example feof($some. File) – fopen() requires two arguments, for example fopen("textfile. txt", "r") – pow() requires two arguments, for example pow(3, 2) Chapter 13

Understanding Function Arguments • Some functions accept different numbers of arguments – A different version of the function is executed depending on the number of arguments that are sent. • An example is the round() function – To round off to a whole number, use one argument: round (14. 626) will return 15. – To round to a specific number of decimal places, use two arguments: round (14. 626, 2) will return 14. 63. Chapter 13

Receiving Values from a Function • Many functions are designed to return a value once they have completed their task. • The programs that calls the function will need code to handle the returned value. • Examples: $result = pow(7, 3); $next. Line = fgets($some. File); while (!feof($some. File)) print("<p>The square of 3 is ". pow(3, 2). "</p>"); Chapter 13

Using Existing Functions • It is efficient and practical to use existing functions whenever possible: Rapid application development (less to do) High quality (many functions are continuously improved) Reduced testing (functions have already been tested) Ease of maintenance (functions are maintained separately) – Avoids duplication of effort (why reinvent? ) – Self-documenting (function names describe their purpose) – Standardization (simplifies interoperability with other applications) – – Chapter 13

Researching Available Functions • To view a list of the pre-defined PHP functions: http: //www. php. net/quickref. php • Or by category: http: //www. w 3 schools. com/php/default. asp • Many other useful functions are available elsewhere: – – Ask other programmers Search the Web Looking through programming books Purchase function libraries • Be careful regarding possible copyright restrictions. Chapter 13

Creating Your Own Functions • You often need to develop functions of your own. • It is useful to develop functions in groups that are related by some general purpose. • As an example, we will developing some functions for use with our temperature conversion applications. • Let's start with a function to convert Celsius to Fahrenheit. Chapter 13

to. Fahrenheit() Function • This function must receive a single argument (a Celsius temperature), and must return a Fahrenheit temperature. Here is the code: function to. Fahrenheit ($celsius) { $fahrenheit = (9 / 5) * $celsius + 32; return $fahrenheit; } Chapter 13

to. Fahrenheit() Function • The function definition begins with a heading: – function to. Fahrenheit ($celsius) • The heading consists of: – The word function – The name that we wish to give the function (to. Fahrenheit) – A pair of parentheses containing a list of variables that will receive the arguments sent to the function. – The "receiving variables" are known as the function's parameters. – This function has one parameter - $celsius Chapter 13

Sending Arguments to Function Parameters • to. Fahrenheit () has one parameter ($celsius) • The function will receive any value sent as an argument in the $celsius parameter. • Examples: to. Fahrenheit (20) (The argument 20 will be received and stored in $celsius) to. Fahrenheit ($some. Temperature) (The value stored in $some. Temperature will be received and stored in $celsius) Chapter 13

The Body of the Function • The function body: – Follows the function heading and is enclosed within a pair of {} braces – Contains the code needed to perform the function's task. – Can contain any number of programming structures (sequential, selection or loop statements, or even calls to other functions). – Will process whatever values are sent to the parameters, according to how these parameters are used in the code – Uses a return statement to return a value to the calling program • Chapter 13

The Body of to. Fahrenheit() • to. Fahrenheit() contains two statements: $fahrenheit = (9 / 5) * $celsius + 32; – The first statement uses the value received by the parameter $celsius to calculate the Fahrenheit and assign the result to the variable $fahrenheit return $fahrenheit; – The second statement returns the value stored in $fahrenheit to the program that called the function • If you do not include a return statement, the function will not return a value. Chapter 13

The Body of to. Fahrenheit() • Note that the body of to. Fahrenheit() could be simplified to a single statement, with no need for the $fahrenheit variable: function to. Fahrenheit ($celsius) { return (9 / 5) * $celsius + 32; } Chapter 13

Code for to. Celsius() • to. Celsius() is designed to receive a Fahrenheit temperature, convert to Celsius, and return the result: function to. Celsius($fahrenheit) { $celsius= ($fahrenheit - 32) / (9 / 5); return $celsius; } Chapter 13

Functions that Return Strings • These functions return the actual formulas as strings: function str. Fahrenheit. Formula () { return "Fahrenheit = (9 / 5) * Celsius + 32"; } function str. Celsius. Formula () { return "Celsius = Fahrenheit - 32) / (9 / 5)"; } Chapter 13

A Windchill Function function get. Windchill ($fahrenheit, $wind. Speed. MPH) { $windchill = 35. 74 + (0. 6215 * $fahrenheit) (35. 75 * pow($wind. Speed. MPH, 0. 16)) + (0. 4275 * $fahrenheit * pow ($wind. Speed. MPH, 0. 16)); return $windchill; } • Note the two parameters, separated by commas. The arguments must be sent in the correct order. Chapter 13

A Library of Functions • In order for functions to be generally used, they must be stored in a file separate from any particular application. • This file can then be included in any application that requires the use of the functions. • Files of related functions are often known as function libraries. • We have created a small library of five temperature functions. • We will store them in a file named inc. Temp. Functions. php (A file of functions can have any name – inc helps to indicate that this file is intended for inclusion in other programs) Chapter 13

Code for inc. Temp. Functions. php • Note that this file contains only a list of functions. It is not a working application. <? php function to. Fahrenheit ($celsius) { $fahrenheit = (9 / 5) * $celsius + 32; return $fahrenheit; } // The other functions should be listed here. . ? > Chapter 13

Including Functions from External Files • In PHP, one way to include code from external files is by issuing an include() statement: include ("inc. Temp. Functions. php"); • The content of the file is added to the existing code at the location of the include() statement. • The code in the included files can be referenced by any statements that follow this location. • The include() statement must appear before any code that references the code in the included file. Chapter 13

temp. Converter 5. php (page 1 of 2) <? php include ("inc. Temp. Functions. php"); print("<h 1>Temperature Conversions</h 1>"); print("<p>NOTE: These conversions use the formula: <br />". str. Fahrenheit. Formula(). "</p>"); print ("<table border = "1"> "); print ("<tr><td><strong>Degrees C</strong></td> <td><strong>Degrees F</strong></td></tr>"); Chapter 13

temp. Converter 5. php (page 2 of 2) for ($celsius = 0; $celsius <= 100; $celsius = $celsius + 10 ) { $fahrenheit = to. Fahrenheit($celsius); print("<tr><td align = "center">$celsius</td> <td align = "center">$fahrenheit</td></tr>"); } print ("</table>"); ? > Chapter 13

Using Functions in Multiple Programs • Consider this requirement for another temperaturerelated application: calc. Wind. Chill requirements: Write an application that asks the user for the current temperature (in degrees Celsius) and the wind speed (mile per hour). The program should then display the wind chill for these conditions (also in degrees Celsius). Chapter 13

Code for calc. Windchill. html <h 1>WIND CHILL CALCULATOR</h 1> <form action ="calc. Windchill. php" method = "post" > <table><tr><td>Enter a temperature in degrees Celsius: </td> <td><input type = "text" size = "10" name = "celsius" /></td></tr> <tr><td>Enter a wind speed in mile per hour: </td> <td><input type = "text" size = "10" name = "windspeed" /></td></tr> </table> <input type ="submit" value ="Display temperature" /> </form> Chapter 13

Code for calc. Windchill. php <? php ? > include ("inc. Temp. Functions. php"); $celsius = $_POST['celsius']; $windspeed = $_POST['windspeed']; $fahrenheit = to. Fahrenheit($celsius); $windchill. F = get. Windchill ($fahrenheit, $windspeed ); $windchill. C = to. Celsius($windchill. F); print ("Temperature (Celsius): $celsius<br />"); print ("Wind. Speed (miles per hour): $windspeed<br />"); print ("Windchill (Celsius): ". number_format($windchill. C, 2). "<br />"); Chapter 13

Sample Interaction: calc. Windchill Chapter 13

Different Programming Approaches • Do you see the value of developing libraries of useful functions? • Some programmers spend most of their time developing general purpose code libraries. – Key to success is thinking generally: what might any application need from this library? • Other programmers develop applications that use function libraries to help meet requirements. – Key to success is thinking specifically: what exactly does this application need? Chapter 13

Think Beyond Specific Applications • Modular programming changes the way that we think about software design. • Start to think beyond specific applications. • How can you design and develop general purpose code that can be used for different purposes by different programs? • Consider the general-purpose file processing functions in inc. Numeric. File. Functions. php. This file is in your samples folder. . Chapter 13

inc. Numeric. File. Functions. php print. Data() outputs the numbers contained in a file. get. Total() totals the numbers contained in a file. get. Count() counts the numbers contained in a file. get. Average() calculates the average of the numbers contained in a file. • get. Highest() finds the highest value of the numbers contained in a file. • get. Lowest() finds the lowest value of the numbers contained in a file. • • Chapter 13

More About Include Files • Include files can be used to add any text to a PHP file, not just libraries of functions. For example: – Create an include file with associative arrays containing useful lookups (for example standard error messages, or a lookup of company information). Now include this file in any application that needs the lookups. – Many pages on a Web site often contain the same <head> information, or the same menus, or other design features. Code that is common to multiple pages can be stored in include files and included in the instructions for each page to avoid duplication and simplify updates. Chapter 13

AN INTRODUCTION TO OBJECT ORIENTED PROGRAMMING Chapter 13

Object Oriented Programming • Object Oriented Programming (OOP) takes modular design a step further. • OOP requires developers to define a comprehensive set of functions to operate on a set of related data values (called attributes) such as employee information, or student scores, or rainfall data. • In OOP terminology, modules are usually referred to as methods. Since PHP uses the word function, we will use that term here. • We will only introduce general OOP concepts. Chapter 13

Object Oriented Programming • The combination of a set of data with the functions needed to operate on this data constitutes an object. • To work with the data associated with an object you must use the functions provided for this purpose. • These functions provide a standard Application Programming Interface (API) to the data. • The use of a standard API promotes consistency, enables rapid development, ensures compatibility, reduces duplication, increases security, and minimizes errors. Chapter 13

OOP Example: a Wage Object • Assume that the data related to an employee's weekly wage consists of four values (attributes): – – the employee's ID number of tax exemptions hours worked hourly wage • The API will include all of the functions (methods) needed to perform operations on this data. • Together, the definition of the object's attributes and methods constitute an object class. Chapter 13

Defining a Wage Object (page 1 of 3) • Data for the Wage object class: emp. ID: the employee's ID num. Exemptions: the number of Federal tax exemptions hours. Worked: the hours worked this week hourly. Wage: the hourly wage Chapter 13

Defining a Wage Object (page 2 of 3) • API for the Wage object class. These methods (or functions) can be used to operate on the data: Wage(): used to construct a unique instance (covered later) get. ID(): used to obtain the employee ID set. ID(): used to change the employee ID get. Num. Exemptions(): used to obtain the number of exemptions set. Num. Exemptions(): used to change the number of exemptions Chapter 13

Defining a Wage Object (page 3 of 3) get. Hours. Worked(): used to obtain the hours worked by the employee set. Hours. Worked (): used to change the hours worked by the employee get. Hourly. Wage(): used to obtain the employee's hourly wage set. Hourly. Wage(): used to change the employee's hourly wage get. Gross. Wage(): used to obtain the employee's gross weekly wage get. Fed. Withholding: used to obtain the employee's federal taxes get. Net. Wage(): used to obtain the employee's net weekly wage Chapter 13

Coding a Wage Object • Review the code in inc. Wage. Object. php – This can be found in your textbook and in the samples folder • The Wage object is defined as a class. • The object class definitions incorporate some new operators and syntax. Chapter 13

Coding a Wage Object in PHP • The class heading contains the word class followed by the name of the class. • The content of the class definition is enclosed in {} braces. • The class variables are listed outside the class functions. • The word var is used to identify each class variable. Chapter 13

Coding a Wage Object in PHP • The class functions (methods) provide the interface between the data and programs that use the object. • Most class functions perform a simple operation: – get. Hours. Worked() simply returns the value stored in the $hours. Worked variable to the program that requests it – set. Hours. Worked() receives a value from an application and stores this in the $hours. Worked variable. • The words get and set are often used to indicate these operations on the class data. Chapter 13

Coding a Wage Object in PHP • The class functions use an unfamiliar syntax to refer to the class variables: – $this->hours. Worked is used within a function to refer to the $hours. Worked variable created at the class level. – This ensures that the class variable is not confused with a variable inside the function that may have the same name. – For example the set. Hours. Worked() function contains a parameter named $hours. Worked. – $this->hours. Worked = $hours. Worked; specifies that the class variable $hours. Worked is to receive a value from the parameter $hours. Worked. Chapter 13

Creating and Using Wage Objects in an Application • To actually use the Wage class to process employee wages in an application a programmer must: – Know the name of the class and what functions are available to work with the data that the class provides – Create instances of the Wage object as needed, one for each employee that his or her application must process. Each Wage instance contains a set of class data (ID, hours worked, hourly wage, number of exemptions). • How does a programmer create an instance of a Wage object? Chapter 13

Creating and Using Wage Objects in an Application • A new instance is created by using the new operator to call the object's constructor method. • This constructor method has the same name as the class itself, for example Wage(). • The constructor method creates a copy of the object. • Here is how a program might create new instances for two employees: $emp 1 = new Wage(); $emp 2 = new Wage(); Chapter 13

Creating and Using Wage Objects in an Application • The statement $emp 1 = new Wage() creates a new instance of a Wage object and assigns this to $emp 1. • The new operator ensures that the instance is unique and contains its own set of data. • $emp 1 and $emp 2 contain unique Wage objects. Each contains four class variables to hold data for a particular employee. • We can use any of the class functions to operate on the data contained in each instance… Chapter 13

Creating and Using Wage Objects in an Application • Now that the $emp 1 instance has been created, we can set the ID, hours worked and hourly wage of this employee as follows: $emp 1 ->set. ID("111 -22 -3333"); $emp 1 ->set. Hours. Worked(40); $emp 1 ->set. Hourly. Wage(10. 00); $emp 1 ->set. Num. Exemptions(2); • In PHP we use the -> operator to associate a function from the object class with an instance of the class. Chapter 13

Creating and Using Wage Objects in an Application • To use get. Gross. Wage() in the Wage class to obtain the gross wage of the $emp 1 instance and assign this to a variable named $emp 1 Gross. Wage: $emp 1 Gross. Wage = $emp 1 ->get. Gross. Wage(); • To use get. Net. Wage() in the Wage class to obtain the net wage of the $emp 1 instance and assign this to a variable named $emp 1 Net. Wage: $emp 1 Net. Wage = $emp 1 ->get. Net. Wage(); Chapter 13

A Complete Wage Application • Once an object has been defined, our applications can create any number of instances by declaring instance variables of the class. We can then apply any function defined in the API to work with these instances as needed to meet requirements. • wage 11. php includes inc. Wage. Object. php and creates two instances of the Wage object class in order to demonstrate the use of objects in a working application. Chapter 13

More About Constructor Methods • The Wage class includes a method named Wage(). • This method has the same name as the class itself and is called a constructor. • Constructors can only be used with the new operator to create a new instance of an object, for example: $emp 1 = new Wage(); • Any code inside the constructor is executed at the time that the instance is created. For example the constructor might be coded to set the class variables to default values. Our Wage() method has no code. Chapter 13

Working with Objects • Object oriented programming consists of two quite distinct development stages: – The object class is defined. The designers think beyond specific applications and focus on all possible uses – Programmers create instances of the class for use within their own applications. Often these programmers have no involvement in the development of the object class. • Object-oriented programmers work with many different kinds of objects within a single application. Chapter 13

OOP Terms and Concepts • Object oriented design prevents programmers and applications from accessing data directly. The API: – provides increased security – reduces coding errors – promotes standards • In OOP, the data in an object class is encapsulated by the methods: the API hides the data, protecting it from inappropriate or incorrect use. – A successful API must therefore provide a comprehensive range of functions for working with the data. Chapter 13

OOP Terms and Concepts • The terms class variables and class methods describe the components of an object class. • Class variables are variously termed class attributes or fields or properties. • The class variables and methods together constitute the members of the class. • Each class is designed for a specific type of object. • Collections of related classes are often stored together in packages. • Chapter 13

OOP Terms and Concepts • A key concept of OOP is an object hierarchy: – The class variables and functions of one object class (the parent) are inherited by another object class (the child). – The child class can extend the parent class by adding class variables and functions to achieve a more specific purpose. – For example an Employee class contains data and functions common to all employees. A Salaried. Employee class can inherit these and provide additional data and functions appropriate only for salaried employees. – Inheritance provides a powerful design structure for OOP and minimizes code duplication. Chapter 13

OOP Terms and Concepts • Another important feature of OOP is polymorphism. – In general usage, polymorphic means many shaped. – In OOP, polymorphism allows applications to determine the specific type of object within an object hierarchy at the time the application is running. For example an application might decide whether an employee should be handled as a salaried employee or an hourly employee. – This type of dynamic decision-making provides great flexibility for software designers, and reduces code duplication. Chapter 13

OOP Languages • Object Oriented languages, such as Java, are designed so that all application development is derived from objects. – OOP languages provide large numbers of standard object classes that programmers can use to develop applications quickly and easily. – Java provides a rich set of standard object classes for developing graphical user interfaces quickly and easily. Chapter 13

This is Only an Introduction! Don't be too concerned if this brief introduction to OOP is a little abstract or overwhelming! The topic is introduced here as a preview of an important subject that you will meet again if you take additional programming courses. . Chapter 13

Chapter 13
- Slides: 64