1 / 78

M150: Data, Computing and information

M150: Data, Computing and information. Outline Unit nine. What’s next. Review questions. Your questions. 1- Unit nine : Managing complexity through modularity. Separate code modules. Function libraries. Programming with function libraries. Objects in JavaScript.

gjarrell
Download Presentation

M150: Data, Computing and information

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. M150: Data, Computing and information Outline Unit nine. What’s next. Review questions. Your questions.

  2. 1- Unit nine : Managing complexity through modularity Separate code modules. Function libraries. Programming with function libraries. Objects in JavaScript.

  3. 1- Unit nine : Separate code modules Old programming practice was based on writing programs as a single very big monolithic code file. Disadvantages: Very much time consuming. Risk of loosing the string of logical thinking while writing. Very error prone. Difficult to debug, modify, and update. Inability to distribute tasks among several programmers. 3

  4. 1- Unit nine : Separate code modules Structuring a program into several code modules in several files helps overcome these problems. A module is a piece of code concerned with a specific task to perform. Being written as a stand alone file, a module can be reused and reintegrated into other programs. Improvement and update of a module will create new versions that can easily replace older ones in programs. 4

  5. 1- Unit nine : Function libraries Code reusability consists of writing a piece of code once for solving a problem and then save it for solving later similar problems. Copy/Paste the wanted function code from the old program into the new one is an option, but not the optimal one. Better solution is to collect and save reusable functions into files called function libraries. The libraries are imported into the new code when functions are needed. If you import a library into your program, it is as if you copy/pasted all its functions into your code or had to rewrite them all. 5

  6. 1- Unit nine : How to import a function library Suppose we have a function library called drawingLibrary.js (the extension .js stands for java script file). To import this library into our code we need a special version of the SCRIPT tags as follows: <SCRIPT SRC = drawingLibrary.js> </SCRIPT> Note that NOTHING should be written between these tags, our code and the call for functions from this library will be written in a separate pair of SCRIPT tags. 6

  7. 1- Unit nine : How to import a function library Note the following example: <SCRIPT SRC = drawingLibrary.js> </SCRIPT> <SCRIPT LANGUAGE =“JavaScript”> drawSquare(‘red’, 5); </SCRIPT> 7

  8. 1- Unit nine : Library documentation A function library is intended to be used as a black box, you know the input, you know the output, no need to understand the code in between. HOWEVER in order to properly use a function library, you should be aware of the following things: What are the functions inside the library. What does each function do. What are their parameters. What do they give in return. 8

  9. 1- Unit nine : Library documentation Such details are known as documentation provided with each library by means of Specifications for each function, they are written as comments. Here are the specifications for the function drawSquare called previously in an example : function drawSquare(colour, indent) /*************************************************************/ /* Function draws a square, 10 stars wide and 10 stars high. */ /* The function takes two arguments: */ /* colour - a string that specifies the colour of the rectangle. */ /* indent - a whole number which specifies the number of spaces the */ /* square is indented from the left-hand side of the page. */ /* Function returns no value. */ /*************************************************************/ 9

  10. 1- Unit nine : Programming with function libraries Manipulating the Date object using the dateLibrary.js provided with the course CD. 10

  11. 1- Unit nine : How to import a function library Already familiar with JavaScript objects such as Array, Document, etc… Date is a JavaScript object that follows the same rules of creation. The Array object has a related function length() which is called using a dot notation. Date also has related functions for further manipulations. 11

  12. 1- Unit nine : How to import a function library var today = new Date(); Creates a new instance of type Date and stores it in the variable today. This instance has the following properties : year, month, day of the month, hour, minute, second, millisecond. Date() is referred to as a constructor function note it has the same name as the object. When it is called without parameters, Date() reads the computer’s internal clock setting, and initializes the properties of the newly created instance to the read values. 12

  13. 1- Unit nine : How to import a function library A Date object can also be created for a specific date (past or future). Example : All the arguments are optional except year and month, if not filled, JavaScript sets them to 0. 13

  14. 1- Unit nine : How to import a function library Rules: The year is written with 4 digits. Months are numbered from 0 till 11, so 0 is January, 1 is February, etc… The 24h clock system is adopted so 1 pm is referred to as 13. The name of the day of the week cannot be set as a parameter since it follows the prefixed rules of the Gregorian calendar. 14

  15. 1- Unit nine : How to import a function library Two notations can be used to create and initialize a Date object instance, using multiple arguments or a single argument: var myDate = new Date(2004, 4, 3, 11, 45, 21); Or var myDate = new Date(‘May 3 2004 11:45:21’); 15

  16. 1- Unit nine : How to import a function library Several methods are associated with the Date object to retrieve properties, example: getFullYear() → Returns a 4 digit number indicating the year getMonth() → Returns the month a number from 0 to 11 getDate() → Returns the day of the month a number from 1 to 31 getDay() → Returns the week day from 0 (Sunday) to 6 (Saturday) getHours() → Returns the hour a number from 0 to 23 getMinutes() → Returns the minutes a number from 0 to 59 getSeconds() → Returns the seconds a number from 0 to 59 16

  17. 1- Unit nine : How to import a function library Several methods are associated with the Date object to set properties, example: setFullYear(year) → Sets the year of the Date object (4 digit number) setMonth(month) → Sets the month of the Date object (0 to 11) setDate(day) → Sets the day of the month of the Date object (1 to 31) setHours(hour) → Sets the hour in the Date object (0 to 23) setMinutes(minute) → Sets the minute in the Date object (0 to 59) setSeconds(second) → Sets the second in the Date object (0 to 59) 17

  18. 1- Unit nine : Activity 4.1 18

  19. 1- Unit nine : Activity 4.1 Solution <SCRIPT SRC=dateLibrary.js> </SCRIPT> <SCRIPT> /****************************************************************/ /* Program to prompt the user for the year, month and day of their birth */ /* and prints out the day of the week on which they were born. */ /****************************************************************/ var day; var month; var year; var birthDay; year = parseFloat(window.prompt('Enter a year as a four digit number', '')); month = parseFloat(window.prompt('Enter a month number from 1 to 12', '')); month = month - 1; day = parseFloat(window.prompt('Enter a day as a number from 1 to 31', '')); birthDay = new Date(year, month, day); document.write('You were born on a ' + dayName(birthDay)); </SCRIPT> Importing the function library Separate SCRIPT tags for the code Subtracting 1 from the month entered by the user dayName is a function from the dateLibrary if given a parameter of type Date returns the name of the week day property 19

  20. 1- Unit nine : Activity 4.2 20

  21. 1- Unit nine : Activity 4.2 Solution <SCRIPT SRC=dateLibrary.js> </SCRIPT> <SCRIPT> /* Program to calculate and write out the user's age to the nearest day */ var day; var month; var year; var birthDay; var today; year = parseFloat (window.prompt('Enter year as a four-digit number','')); month = parseFloat (window.prompt('Enter month as a number from 1 to 12','')) -1; day = parseFloat (window.prompt('Enter day as a number from 1 to 31','')); birthDay = new Date(year,month,day); today = new Date(); document.write('You are ' + differenceInYears(today,birthDay)+ ' years old.‘ + ‘<BR>’); document.write('Which means that you have been on this Earth for '+ differenceInDays(today, birthDay) + ' days.‘ + ‘<BR>’); document.write('Have you used your time wisely?') </SCRIPT> Importing the function library Separate SCRIPT tags for the code Subtracting 1 from the month entered by the user differenceinYears is a function from the dateLibrary if given 2 Date parameters returns the difference between their year properties differenceinDays is a function from the dateLibrary if given 2 Date parameters returns the difference between their number of days 21

  22. 1- Unit nine : Activity 4.3 22

  23. 1- Unit nine : Activity 4.3 (continued) 23

  24. 1- Unit nine : Activity 4.3 Solution <SCRIPT SRC=dateLibrary.js> </SCRIPT> <SCRIPT> /* Program to display a calendar for a given year */ var year = parseFloat(window.prompt('Enter year','')); var date = new Date(year, 0); for (var month = 0; month < 12; month = month + 1) { date.setMonth(month); // update the month displayMonth(date); // display the calendar for that month } </SCRIPT> Importing the function library Separate SCRIPT tags for the code The year is the value entered by the user, and the month 0 is the month of January for loop to go through all 12 months Updates the month property of the object instance displayMonth is a function from the dateLibrary if given a Date object as a parameter displays a formatted calendar for its month property 24

  25. 1- Unit nine : Extending a function library Being useful to prompt to user to enter a year, a month, and a day, why not add it as a function to the dateLibrary.js instead of having to write it entirely over and over again? How do we do that? 25

  26. 1- Unit nine : Extending a function library Adding a function to a Library is not only adding lines of code. Others may find use of such a function, so appropriate specification needs to be provided along with the lines of code. Note that the function must be written in a way that minimizes the errors of usage, all user exceptions must be taken into consideration and must be overcome while programming. 26

  27. 1- Unit nine : Exercise 4.2 Write a specification for the function, which we will call promptForDate(), in the style of those you have already seen in drawingLibrary.js and dateLibrary.js. 27

  28. 1- Unit nine : Exercise 4.2 Solution function promptForDate() /*************************************************************/ /* Function takes no arguments. Prompts user for: */ /* a year number from 1900 to 3000 */ /* a month number from 1 to 12 */ /* a day number from 1 to 31 */ /* Returns a Date object with the given year, month, and day */ /*************************************************************/ 28

  29. 1- Unit nine : Activity 4.5 29

  30. 1- Unit nine : Activity 4.5 Solution function promptForDate() { var dayNumber; var monthNumber; var yearNumber; yearNumber = parseFloat(window.prompt('Enter year number from 1900 to 3000','')); while (yearNumber < 1900 || yearNumber > 3000) { yearNumber = parseFloat(window.prompt('Enter year number from 1900 to 3000','')); }; monthNumber = parseFloat(window.prompt('Enter month number from 1 to 12','')); while (monthNumber < 1 || monthNumber > 12) { monthNumber = parseFloat(window.prompt('Enter month number from 1 to 12','')) ; }; dayNumber = parseFloat(window.prompt('Enter day number from 1 to 31','')); while (dayNumber < 1 || dayNumber > 31) { dayNumber = parseFloat(window.prompt('Enter day number from 1 to 31','')); }; return new Date(yearNumber, monthNumber - 1, dayNumber); } Asking the user to enter the year As long as the user enters an invalid year number Asking the user to enter the year AGAIN Asking the user to enter the month As long as the user enters an invalid month number Asking the user to enter the day As long as the user enters an invalid day number Returning the required Date object 30

  31. 1- Unit nine : Activity 4.6 • Something is missing. • The previously written function contains a major flaw. • It is true that it verifies if the user enters a valid year, month, and day. • But it doesn’t verify if the day is valid relatively to the month!!! • Not all months have 31 days!!! • February has only 28 or 29 days depending whether or not it is a leap year, and June has always 30 days. 31

  32. 1- Unit nine : Activity 4.6 • Repeat the first two steps exactly as in Activity 4.5. • Before prompting the user to enter a day number: • Create a Date object with the year and the month like so: • var aDate = new Date(yearNumber, monthNumber - 1); • Once this is done, use a function from dateLibrary.js that when given a Date object as a parameter returns the number of days in that date’s month, store the returned value in a variable called days. • Then change the code, and instead of prompting the user to enter a day number from 1 to 31, you will prompt him to enter a day number from 1 to days. 32

  33. 1- Unit nine : Activity 4.6 Solution • Just before prompting the user to enter a day number: • aDate = new Date(yearNumber, monthNumber -1); • days = noOfDaysInMonth(aDate); • dayNumber = parseFloat(window.prompt('Enter day number from 1 to ' + days,'')); • while (dayNumber < 1 || dayNumber > days) • { • dayNumber = parseFloat(window.prompt('Enter day number from 1 to ' + days,'')); • }; • return new Date(yearNumber, monthNumber -1, dayNumber); Create a Date object with the prompted year and month noOfDaysInMonth is a function from the dateLibrary if given a Date object as a parameter returns the number of days in its month property Using the number of days associated with the chosen month instead of 31 33

  34. 1- Unit nine : Creating a function library • You have learned how to import and use a library function. • Creating one is not difficult : • Functions are written as lines of code in a text file. • The text file is saved with the extension .js if the functions are written in JavaScript. • Remember that no function library is complete without proper documentation, each function needs to be commented since you will not be the only users of this library. 34

  35. 1- Unit nine : The scope of variables • Where a variable is declared in JavaScript determines where it can be accessed. • The scope of a variable is the extent of the access to it. • If a variable is declared using var in your JavaScript code OUTSIDE a function, then it is called a global variable, it is known to all the functions in the code, and they all can have access to it. 35

  36. 1- Unit nine : Activity 4.7 • Take a look at the following piece of code, the variable declared as var a, is a global variable: • <SCRIPT LANGUAGE = "JavaScript"> • var a; • a = 'dog'; • document.write('Before calling scopeTest(), the value of a is '+ a + '<BR>'); • scopeTest(); • document.write('After calling scopeTest(), the value of a is '+ a + '<BR>'); • function scopeTest() • { • a = 'cat'; • document.write('Inside the function, the value of a is '+ a + '<BR>'); • } • </SCRIPT> 36

  37. 1- Unit nine : Activity 4.7 • The variable a is initially assigned a value, 'dog', in the first line of code in the main program. • After this value has been displayed, the function scopeTest() is called. • This function assigns a new value, 'cat' to a, and displays this value. • Finally, control returns to the main program, which displays the current value of a. As the output demonstrates, this value is 'cat', demonstrating that the variable has retained the value it was assigned during execution of the function scopeTest(). 37

  38. 1- Unit nine : Activity 4.7 • When a variable is global and a function alters its value, the new value will stick to the variable even after the function finishes executing. 38

  39. 1- Unit nine : Activity 4.8 • Lets modify the previous code, we will leave the first var a as a global variable but we will declare another variable var a but this time inside the function scopeTest2(). • <SCRIPT LANGUAGE = "JavaScript"> • var a; • a = 'dog'; • document.write('Before calling scopeTest(), the value of a is '+ a + '<BR>'); • scopeTest(); • document.write('After calling scopeTest(), the value of a is '+ a + '<BR>'); • function scopeTest2() • { • var a; • a = 'cat'; • document.write('Inside the function, the value of a is '+ a + '<BR>'); • } • </SCRIPT> 39

  40. 1- Unit nine : Activity 4.8 • The variable a is initially assigned a value, 'dog', in the first line of code in the main program. • After this value has been displayed, the function scopeTest() is called. • This function declares a new variable a and assigns, 'cat' to a, and displays this value. • Finally, control returns to the main program, which displays the value of the initial variable a this value is ‘dog‘. 40

  41. 1- Unit nine : Activity 4.8 • So what really happened? • The variable a declared in the function scopeTest2() is a different variable, even though it has the same name. • This variable is only accessible to code statements within the function. • Once the function has finished executing, the JavaScript system will once more understand a as referring to the variable with global scope. • The variables declared in a function are said to be local to that function and are out of scope outside the body of the function. • In other words, any variable born inside a function will die once the function finishes executing. 41

  42. 1- Unit nine : Careful notice • Avoid using the same name for different variables. • Never use a variable without declaring it first using the keyword var. • Always declare the variables you need at the top of your program or your function. • Always keep track of how the value of a global variable varies throughout your code. 42

  43. 1- Unit nine : Data types • A data type defines a collection of values along with the operations that can be performed on these values. • 1, 27, 56, and 34 belong to the number data type, 34 is a particular instance of this data type, allowable operations on this data type are +, -, *, /, etc… • True and False are the only instances of the Boolean data type, allowable operations are &&, ||, etc… • These data types are primitive data types since they are not made out of other data types. 43

  44. 1- Unit nine : Objects in JavaScript • Object types are a different type of data, an instance of such a type is called an object. • We already used several instances of object types in previous programs such as Array, String, and Date. • Objects are like containers that hold multiple values of different data types, these are called properties. 44

  45. 1- Unit nine : Categories of objects • In JavaScript there are three categories of objects: • Native objects that are already defined in the language such as Array, String, and Date. • Host objects that are supplied by the browser (ex: Netscape and Internet Explorer) such as Document and Window. • User-Defined objects are types defined by you as a programmer. 45

  46. 1- Unit nine : Objects in JavaScript • An object defines a collection of properties and methods: • Properties are the variables that can be either primitive data types or object data types. • Methods are functions that act on an object’s properties and collectively implement the objects behaviour. 46

  47. 1- Unit nine : Creating new object types • In order to create a new object type, we use a constructor function that has the same name as the object. • If we wish to create a Student object with two properties name and courseCode, we will need something that looks like this: • function Student(aName,aCourse) • { • //object properties • this.name = aName; • this.courseCode = aCourse; • } • Note that the constructor function is like any other function except that its name starts with a capital letter. 47

  48. 1- Unit nine : Creating new object types • name and courseCode are the object’s properties. • The properties are the object’s variables, we didn’t need the keyword var to create these variables. • The this reserved word will specify the scope of the variables. • The this keyword refers to the instance of the object that has just been created using the new keyword. • When using this.name tells JavaScript to give the object referenced by this a property called name. • When the constructor function is called with the parameter value in aName the assignment statement will cause this.name to reference the value of the argument. 48

  49. 1- Unit nine : Creating new object types • Using the constructor function that we previously defined we wish to create a student StudentA with the name ‘Joe’ and the courseCode ‘M150’, and another student StudentB with the name ‘Jill’ and the courseCode ‘M225’. var StudentA = new Student(‘Joe’, ‘M150’); var StudentB = new Student(‘Jill’, ‘M225’); 49

  50. 1- Unit nine : Activity 5.1 • In this activity you are going to create a Student object, and then change the values of the name and courseCode properties. Here is what to do. • Open the file Activity_9.5.1 in a text editor. You will notice that the file has a constructor function for Student objects already defined. • Add code to create a student with the name 'Lindsey' and the course code 'M150' and assign the object to a variable named someStudent. • Using document.write(), add code to display the new Student object’s name and courseCode properties. • Next change the value of the student’s name property to 'Sarah' and change the value of the courseCode property to 'M256'. • Using document.write(), add code to display the new Student object’s name and courseCode properties to verify that the properties have been changed. 50

More Related