JavaScript and OOP. Jerry Cain CS 106AJ November 15, 2017 slides courtesy of Eric Roberts

Similar documents
Programming for Mobile Computing

Classes and Objects. Kristen Nygaard ( ) Ole-Johan Dahl ( )

Section 2.3 Rational Numbers. A rational number is a number that may be written in the form a b. for any integer a and any nonzero integer b.

(3) Some memory that holds a value of a given type. (8) The basic unit of addressing in most computers.

Programming via Java Defining classes

CISC 3115 Modern Programming Techniques Spring 2018 Section TY3 Exam 2 Solutions

Smalltalk: developed at Xerox Palo Alto Research Center by the Learning Research Group in the 1970 s (Smalltalk-72, Smalltalk-76, Smalltalk-80)

Object-Oriented Technology. Rick Mercer

ITI Introduction to Computing II

Recitation #2 Abstract Data Types, Collection Classes, and Linked List

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

CSI33 Data Structures

Objects and Graphics

Chapter 7. Inheritance

Course materials Reges, Stuart, and Stepp, Martin. Building Java Programs: A Back to Basics Approach. 2d ed. (Boston: Addison-Wesley, 2011).

Expressions in JavaScript. Jerry Cain CS 106AJ October 2, 2017

ITI Introduction to Computing II

Object-Oriented Programming

Drawing Geometrical Objects. Graphic courtesy of Eric Roberts

CHAPTER 5 GENERAL OOP CONCEPTS

Chapter 13. Object Oriented Programming

Example: Fibonacci Numbers

A Different Content and Scope for School Arithmetic

CompuScholar, Inc. 9th - 12th grades

Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions. Grace Murray Hopper. Arithmetic Expressions.

Classes. Classes. Classes. Class Circle with methods. Class Circle with fields. Classes and Objects in Java. Introduce to classes and objects in Java.

Binary Representation. Jerry Cain CS 106AJ October 29, 2018 slides courtesy of Eric Roberts

CS 106X Lecture 26: Inheritance and Polymorphism in C++

TeenCoder : Java Programming (ISBN )


Programming Lecture 2. Programming by example (Chapter 2) Hello world Patterns Classes, objects Graphical programming

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

The Java language has a wide variety of modifiers, including the following:

Programming Lecture 6

ADTs & Classes. An introduction

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output?

Functions and Libraries Once upon a time...

CS313D: ADVANCED PROGRAMMING LANGUAGE

Class 22: Inheritance

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW

Object Oriented Programming. Week 1 Part 3 Writing Java with Eclipse and JUnit

Objects. Deian Stefan (Adopted from my & Edward Yang s CS242 slides)

CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Dan Grossman Winter 2013

Expressions, Statements, and Control Structures

CSC148 Intro. to Computer Science

Multiplying and Dividing Rational Expressions

CS 292 Software Development

CSE 341, Autumn 2015, Ruby Introduction Summary

Programming Abstractions

JavaScript Programs Once upon a time...

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Comp 249 Programming Methodology

Review sheet for Final Exam (List of objectives for this course)

CS1210 Lecture 28 Mar. 27, 2019

Skill 1: Multiplying Polynomials

Rational number operations can often be simplified by converting mixed numbers to improper fractions Add EXAMPLE:

CS111: PROGRAMMING LANGUAGE II

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

CS112 Lecture: Defining Instantiable Classes

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

Recursion 1. Recursion is the process of defining something in terms of itself.

Programming Languages and Techniques (CIS120)

Multiplying and Dividing Rational Expressions

Creating a new data type

Outline. Central concepts in OO languages Objects as activation records (Simula) Dynamically-typed object-oriented languages

CS 106B Lecture 27: Inheritance and Polymorphism in C++

Inheritance (IS A Relationship)

Rational numbers as decimals and as integer fractions

Object-Oriented Programming and Design

Programming Languages and Techniques (CIS120)

Classes and Methods לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Inheritance Motivation

CS112 Lecture: Working with Numbers

Ruby logistics. CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Ruby: Not our focus. Ruby: Our focus. A note on the homework

Warm Up Simplify each expression. Assume all variables are nonzero.

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

REVIEW. The C++ Programming Language. CS 151 Review #2

CSE341, Fall 2011, Lecture 12 Summary

C a; C b; C e; int c;

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

Programming I. Course 9 Introduction to programming

Reteaching. Comparing and Ordering Integers

Assignment 2 - Specifications and Modeling


Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

OBJECT ORIENTED SIMULATION LANGUAGE. OOSimL Reference Manual - Part 1

Sri Vidya College of Engineering & Technology

INHERITANCE. Spring 2019

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Recall. Key terms. Review. Encapsulation (by getters, setters, properties) OOP Features. CSC148 Intro. to Computer Science

Course Description. Learn To: : Intro to JAVA SE7 and Programming using JAVA SE7. Course Outline ::

Data Structures (list, dictionary, tuples, sets, strings)

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Week 3: Functions and Data

Exam Duration: 2hrs and 30min Software Design

Mat 2170 Week 9. Spring Mat 2170 Week 9. Objects and Classes. Week 9. Review. Random. Overloading. Craps. Clients. Packages. Randomness.

2015 HSC Software Design and Development Marking Guidelines

1. Let n be a positive number. a. When we divide a decimal number, n, by 10, how are the numeral and the quotient related?

Transcription:

JavaScript and OOP Jerry Cain CS 106AJ November 15, 2017 slides courtesy of Eric Roberts

Once upon a time...

Object-Oriented Programming The most prestigious prize in computer science, the ACM Turing Award, was given in 2002 to two Norwegian computing pioneers, who jointly developed SIMULA in 1967, which was the first language to use the object-oriented paradigm. Kristen Nygaard In addition to his work in computer science, Kristen Nygaard also took an active role in making sure that computers served the interests of workers, not just their employers. In 1990, Nygaard s social activism was recognized in the form of the Norbert Wiener Award for Social and Professional Responsibility. Ole Johan Dahl

JavaScript and OOP

Review: Clients and Interfaces Libraries along with programming abstractions at many other levels can be viewed from two perspectives. Code that uses a library is called a client. The code for the library itself is called the implementation. The point at which the client and the implementation meet is called the interface, which serves as both a barrier and a communication channel: client implementation interface

David Parnas on Modular Development David Parnas is Professor of Computer Science at Limerick University in Ireland, where he directs the Software Quality Research Laboratory, and has also taught at universities in Germany, Canada, and the United States. Parnas's most influential contribution to software engineering is his groundbreaking 1972 paper "On the criteria to be used in decomposing systems into modules," which laid the foundation for modern structured programming. This paper appears in many anthologies and is available on the web at http://portal.acm.org/citation.cfm?id=361623

Information Hiding Our module structure is based on the decomposition criteria known as information hiding. According to this principle, system details that are likely to change independently should be the secrets of separate modules. David Parnas, Paul Clements, and David Weiss, The modular structure of complex systems, 1984 One of the central principles of modern software design is that each level of abstraction should hide as much complexity as possible from the layers that depend on it. This principle is called information hiding. When you use a function, for example, it is more important to know what the function does than to understand exactly how it works. The underlying details are of interest only to the programmer who implements the function. Clients who use that function as a tool can usually ignore the implementation altogether.

Thinking About Objects I need a bunch of GRects. GRect "graphics" class library location size GRect color GOval fill status GLine fill color GLabel. client abstraction boundary with thanks to Randall Munroe at xkcd.com "graphics" library GRect GOval GLine GLabel. implementation

Principles of Object-Oriented Design Object-oriented programming can be characterized by several important features. Informally, object-oriented programming differs from earlier programming paradigms in that it focuses attention on the data objects rather than the code. In practice, this idea of making objects the center of attention can be expressed as three principles: 1. 2. 3. Integration. Objects should combine the internal representation of the data with the operations that implement the necessary behavior into an integrated whole. Encapsulation. Insofar as possible, objects should restrict the client s access to the internal state, mediating all communication across the interface boundary through the use of methods. Inheritance. Objects should be able to inherit behavior from other, more general object classes.

Turning Points into Objects On Friday, Kat defined the following factory method to create a Point as an aggregate of an x and a y value: function Point(x, y) { if (x === undefined) { x = 0; y = 0; } return { x: x, y: y }; } The goal in the next few slides is to turn this aggregate into a data structure that more closely resembles an object in the sense that the term is used in object-oriented programming.

Adding Methods A method is a function that belongs to an object. Given that functions are first-class values in JavaScript, it is perfectly legal to assign a function to one of the fields in an aggregate. Those functions are then JavaScript methods and are invoked using the traditional receiver syntax for methods: object.name(arguments) Methods, however, are not very useful unless they can have access to the fields of the object to which they apply. JavaScript addresses this problem by defining a keyword this that automatically refers to the receiver for the current method call. Thus, in the earlier example, any references to this inside the method name refer to object. The next slide adds getx and gety methods to the Point class.

A Method-Based Definition of Point /* * Creates a new Point object. If this factory function is * called with no arguments, it creates a Point object at the * origin. This version of the Point factory defines the * getter methods getx and gety. */ function Point(x, y) { if (x === undefined) { x = 0; y = 0; } return { x: x, y: y, getx: function() { return this.x; }, gety: function() { return this.y; } }; }

Keeping Data Private Although the example on the previous slide supports the syntax of object-oriented programming by defining the getx and gety methods, it doesn t support the object-oriented principle of encapsulation because the x and y fields are visible to clients. To ensure that variables are completely private to the object in JavaScript, the best strategy is to ensure that those variables are part of the closure that defines the method and not define them as fields. The code that results from applying this strategy appears on the next slide. This approach has several advantages: The data values x and y are inaccessible to clients. The code is several lines shorter. The keyword this is no longer required.

An Encapsulated Point Class /* * Creates a new Point object. If this factory function is * called with no arguments, it creates a Point object at the * origin. This version of the Point factory ensures that the * data fields are in the function closure, which makes them * inaccessible outside the function, even though they are * available to the getter methods getx and gety. */ function Point(x, y) { if (x === undefined) { x = 0; y = 0; } return { getx: function() { return x; }, gety: function() { return y; } }; }

Converting Objects to Strings JavaScript makes it possible for implementers to define how objects of a particular class are displayed by console.log or how they combine with strings through concatenation. When JavaScript needs to convert an object to a string, it checks to see whether that object defines a tostring method. The tostring method takes no arguments and returns a string that represents the desired textual appearance of the value. The code on the next slide adds a tostring method to the Point class.

Adding a tostring Function /* * Creates a new Point object. If this factory function is * called with no arguments, it creates a Point object at the * origin. This version of the Point factory ensures that the * data fields are in the function closure, which makes them * inaccessible outside the function, even though they are * available to the getter methods getx and gety. This version * also exports a tostring method. */ function Point(x, y) { if (x === undefined) { x = 0; y = 0; } return { getx: function() { return x; }, gety: function() { return y; }, tostring: function () { return "(" + x + ", " + y + ")"; } }; }

Rational Numbers In her introduction of aggregates last Friday, Kat might have offered the example of rational numbers, which are a single unit with a numerator and a denominator. To get a sense of how rational numbers might in some cases be preferable to the numeric approximations that JavaScript uses, try to predict the output of the following program: function FractionSum() { let a = 1/2; let b = 1/3; let c = 1/6; let sum = a + b + c; console.log("1/2 + 1/3 + 1/6 = " + sum); } JavaScript Console 1/2 + 1/3 + 1/6 = 0.9999999999999999

JavaScript Numbers Are Approximations The reason that the program on the previous slide produces a surprising answer is that most fractions do not have a precise binary representation but are instead stored as approximations. For example, the fractions 1/3 and 1/6 cannot be represented exactly. When you add these together with 1/2, the result is not the expected value. By contrast, arithmetic with rational numbers is exact. Rational numbers support the standard arithmetic operations: Addition: a b + c d = ad + bc bd Multiplication: a c x b d = ac bd Subtraction: a b c d = ad bc bd Division: a. b c d = ad bc

Implementing the Rational Class The next two slides show the code for the Rational class along with some brief annotations. As you read through the code, the following features are worth special attention: The factory method takes one, two, or three parameters. Calling Rational with no arguments returns the rational equivalent of 0, calling it with one argument creates an integer, and calling it with two arguments creates a fraction. The constructor makes sure that the number is reduced to lowest terms. Moreover, since these values never change once a Rational is created, this property will remain in force. Operations are specified using the receiver syntax. When you apply an operator to two Rational values, one of the operands is the receiver and the other is passed as an argument, as in r1.add(r2)

The Rational Class /* * This class represents a rational number, which is defined as * the quotient of two integers. */ function Rational(x, y) { if (x === undefined) x = 0; if (y === undefined) y = 1; let g = gcd(math.abs(x), Math.abs(y)); let num = x / g; let den = Math.abs(y) / g; if (y < 0) num = -num; The factory method looks for missing arguments and assigns default values. It then calls gcd to reduce the fraction to lowest terms. Finally, it makes sure that the denominator is positive. } return {... see object definition on next slide... }; /* Include definition of gcd from Chapter 4 */

The Rational Class /* return { * This getnum: class function() represents { a return rational num; number, }, which is defined as getden: function() { return den; }, * the quotient of two integers. add: function(r) { */ return Rational(num * r.getden() + r.getnum() * den, den * r.getden()); function Rational(x, }, y) { if sub: (x === function(r) undefined) { x = 0; if (y === undefined) return Rational(num y = 1; * r.getden() - r.getnum() * den, let g = gcd(math.abs(x), Math.abs(y)); den * r.getden()); let num }, = x / g; let mul: den function(r) = Math.abs(y) { / g; if (y < 0) return num = -num; Rational(num * r.getnum(), den * r.getden()); }, return div: { function(r) {... see object return definition Rational(num next slide...* r.getden(), den * r.getnum()); }; }, } tostring: function() { if (den === 1) return "" + num; return num + "/" + den; } };

Rational Numbers Are Exact Here is the same program using the Rational class. function RationalSum() { let a = Rational(1, 2); let b = Rational(1, 3); let c = Rational(1, 6); let sum = a.add(b).add(c); console.log("1/2 + 1/3 + 1/6 = " + sum); } 1/2 + 1/3 + 1/6 = 1 JavaScript Console

Inheritance Object-oriented languages allow one class to inherit behavior from another. For example, classes like GRect and GOval inherit behavior from GObject. The simplest way to implement inheritance in JavaScript is to have the factory method for the subclass call the factory method for the superclass and then add fields to the result. This model is illustrated in the text using the Employee class and the subclasses HourlyEmployee, SalariedEmployee, and CommissionedEmployee. None of the assignments or section problems require you to implement inheritance, and the topic will not appear on the final exam. It's mentioned here because it's a hallmark feature of advanced OOP, and will be reintroduced in CS106B.

The End