620 likes | 631 Views
Unit 9 : Managing Complexity Through Modularity. Sunday, March 01, 2009 Presented by Mais M. Fatayer. 1. Introduction. In M150 Part one, you have been introduced to using functions to structure your programs and to facilitate the reuse of the code you had written. In this unit.
E N D
Unit 9 : Managing Complexity Through Modularity Sunday, March 01, 2009 Presented by Mais M. Fatayer
1. Introduction • In M150 Part one, you have been introduced to using functions to structure your programs and to facilitate the reuse of the code you had written.
In this unit • the advantages of structuring large complex programs into separate code modules; • the benefits of black box programming and the importance of documentation; • how to import a function library into a JavaScript program and select and use suitable functions to solve simple programming tasks; • how to create a fully documented function library; • the scoping rules that apply to variables and function names; • how to use objects in JavaScript; • to understand and describe the differences between object types and primitive types; • how to create new object types.
Main Program: Session #5 Statistical Information unsigned int index; int count=0; int max =0; for(index=0; index<choice; index++) { if(nums[index]==nums[index+1]) count++; else { if(count>max) max=count; count=0; } } count=0; for(index=0; index<choice; index++) { if(nums[index]==nums[index+1]) count++; else { if(count==max)cout<<"Mode(s):\t" <<nums[index]<<"\n"; count=0; } unsigned int y = 0; for(double x = 0; choice > y; y++) //y is the # that cycles through the array { x += nums[y]; //adds everything to x } double n = 0; //use long hold = 0; long other = 0; double holder = 0; //use double m = 0; //use if (choice % 2) //If number is odd means the middle number is median` { n = (choice/2); //finds the very middle number n += .5; //it will return a #.5 so we add another .5 to counter that hold = static_cast<int>(n); // we convert #.0 to just # holder = nums[hold]; //holder = the # stored at nums[hold] } else { hold = (choice/2); //if choice is even then hold is equal to the higher middle # other = (hold - 1);//other is the lower middle number n = nums[hold]; //assign the value in hold to n m = nums[other];//asign the value in other to m holder = ((n+m)/2);//find the average of the 2 middle numbers } return holder; //return the average monolithic is difficult to read or modify.. I need a better way to write my code.
Breaking down a program in to series of manageable subtasks to avoid unnecessarily repeating the same code in one program Main Program: Session #5 Statistical Information Median Mean Standard Deviation double median(double* nums, unsigned int choice){ double n = 0; //use long hold = 0; long other = 0; double holder = 0; //use double m = 0; //use if (choice % 2) //If number is odd means the middle number is median { n = (choice/2); //finds the very middle number n += .5; //it will return a #.5 so we add another .5 to counter that hold = static_cast<int>(n); // we convert #.0 to just # holder = nums[hold]; //holder = the # stored at nums[hold] } else { hold = (choice/2); //if choice is even then hold is equal to the higher middle # other = (hold - 1);//other is the lower middle number n = nums[hold]; //assign the value in hold to n m = nums[other];//asign the value in other to m holder = ((n+m)/2);//find the average of the 2 middle numbers } return holder; //return the average} double avg(double* nums, unsigned int choice){ unsigned int y = 0; for(double x = 0; choice > y; y++) //y is the # that cycles through the array { x += nums[y]; //adds everything to x }return(x/choice); //divides it by how many numbers they entered} T-Test Mod chart
Modules and modular programming • simplest concept of a module is an identifiable piece of program code that implements a particular task . • A Module has a name by which it can be identified and so used. • A module can be one of a number of identifiable ‘chunks’ within a single file, or it may be a separate file. • This description originally made the term ‘module’ synonymous with language-specific terms such as subroutine, function and procedure.
2. Separate Code Modules • JavaScript you learned to construct a program from a number of separate files, each containing JavaScript code. • A main program file can indicate that it wants to use JavaScript code from an external file by the simple inclusion of a line of HTML naming that file. • By convention an extension of .js (short for JavaScript) is used as a suffix to the name of such an external file. • The most common type of .js file is a function library which is a file containing a collection of related functions. • See example
What else.. • (.js files) can also be used to hold the code needed to implement new types of objects.
SAQ 2.1 • Name two types of module that can be implemented using .js files. • Answer to SAQ 2.1 Function libraries and object types.
SAQ 2.2 • Give at least three advantages of using modules. • Answer to SAQ 2.2 • Different aspects of a programming problem may be developed separately. • Locating and isolating problems is much easier than would be the case with a monolithic program in a single file. • It allows many people to work on the same project, so shortening development time. • Modules can be reused. • Modules can be considered as replaceable components which can be easily replaced by improved versions without affecting or making changes to other parts of the program.
3. Function Libraries • Now we will discuss some of the features of function libraries and their use in JavaScript.
Write once , use many times… • When you develop a solution for doing something in any programming language you should keep in mind that you may encounter similar problem in future. • Do you think that a simple copy and paste the required function from the old program into the new one is a the idea of reuse? • A far better solution is to collect reusable functions into files which can then be imported into programs as and when needed. • Such a file is called a function library and it is an example of a module.
Documentation ( Black Box Programming ) • To make it possible for other programmers to use your function ,you need to document it precisely. You need to specify: • The name of the function; drawSquare • What arguments must be passed to the function and what type of value each must be; (colour,indent) • What the function does; • The value returned, if any, and what it represents. /*****************************************************************/ /* 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 rectangle is indented from the left-hand side of the page. */ /* Function returns no value. */ /*****************************************************************/ Draw Square()
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.
4. Programming with function libraries • Manipulating the Date object using the dateLibrary.js provided with the course CD. • As you are 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.
Creating an object of type Date var today = new Date(); Explain the above code? 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. Nice to know 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.
More on Dates 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.
Rules on using Date() 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.
Create and Initialize a Date 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’);
Date Methods 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
Date Methods ( cont.) 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)
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
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?
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.
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.
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 */ /*************************************************************/
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
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.
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.
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
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.
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.
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>
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().
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.
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 scopeTest() { a = 'cat'; document.write('Inside the function, the value of a is '+ a + '<BR>'); } </SCRIPT> <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>
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‘.
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.
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.
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.
5. 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.
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.
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.
Creating new object types • In order to create a new object type, we use a constructorfunction 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.
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.
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’);
Homework 1 • Solve activity 5.1 and 5.2 pages 46 and 47 • Bring the answers next session “ printed”
How is data stored in memory • In the case of primitive data types, the memory location holds the data value. This is known as value semantics. • Each primitive type has a fixed size and, as primitive data types are single data values, it tends to be small. • JavaScript allocates an eight-byte block of memory for the storage of any primitive value.