Announcements HW10 due November 27 Rainbow grades:

Slides:



Advertisements
Similar presentations
Programming Languages and Paradigms
Advertisements

Chapter 9 Subprograms Specification: name, signature, actions Signature: number and types of input arguments, number and types of output results –Book.
Chapter 12: Support for Object-Oriented Programming
Chapter 9 Subprograms Sections 1-5 and 9. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Introduction Two fundamental abstraction facilities.
Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve.
Road Map Introduction to object oriented programming. Classes
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
ISBN Chapter 9 Subprograms. Copyright © 2006 Addison-Wesley. All rights reserved.1-2 Introduction Two fundamental abstraction facilities.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Abstract Data Types and Encapsulation Concepts
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Programming Languages and Paradigms Object-Oriented Programming.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
1 Chapter 10: Data Abstraction and Object Orientation Aaron Bloomfield CS 415 Fall 2005.
Programming Languages and Design Lecture 7 Subroutines and Control Abstraction Instructor: Li Ma Department of Computer Science Texas Southern University,
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Object-Oriented Programming Chapter Chapter
(1) ICS 313: Programming Language Theory Chapter 12: Object Oriented Programming.
ISBN Object-Oriented Programming Chapter Chapter
Copyright © 2005 Elsevier Object-Oriented Programming Control or PROCESS abstraction is a very old idea (subroutines!), though few languages provide it.
1 Chapter 11 © 1998 by Addison Wesley Longman, Inc The Concept of Abstraction - The concept of abstraction is fundamental in programming - Nearly.
1 CS Programming Languages Class 22 November 14, 2000.
1 Copyright © 1998 by Addison Wesley Longman, Inc. Chapter 10 Abstraction - The concept of abstraction is fundamental in programming - Nearly all programming.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
C++ General Characteristics: - Mixed typing system - Constructors and destructors - Elaborate access controls to class entities.
ISBN Chapter 12 Support for Object-Oriented Programming.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
Memory Management.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Principles of programming languages 10: Object oriented languages
Chapter 9 Subprograms.
Data Types In Text: Chapter 6.
Copyright © Jim Fawcett Spring 2017
Object-Oriented Design
Abstract Data Types and Encapsulation Concepts
Support for Object-Oriented Programming
Support for Object-Oriented Programming
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
CS 326 Programming Languages, Concepts and Implementation
Principles of programming languages 4: Parameter passing, Scope rules
Review: Two Programming Paradigms
Object-Oriented Programming & Design Lecture 14 Martin van Bommel
11.1 The Concept of Abstraction
CSCI 3370: Principles of Programming Languages Chapter 9 Subprograms
Parametric Polymorphism and Java Generics
Abstract Data Types and Encapsulation Concepts
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Names, Binding, and Scope
Abstract Data Types and Encapsulation Concepts
Chap. 8 :: Subroutines and Control Abstraction
Chap. 8 :: Subroutines and Control Abstraction
Java Programming Language
CSC 533: Programming Languages Spring 2015
Subprograms In Text: Chapter 9.
Parameter Passing Actual vs formal parameters
Support for Object-Oriented Programming
Names and Binding In Text: Chapter 5.
Announcements Quiz 5 HW6 due October 23
Overview of C++ Polymorphism
Java Programming Language
Lecture 10 Concepts of Programming Languages
CSC 533: Programming Languages Spring 2018
CSC 533: Programming Languages Spring 2019
11.1 The Concept of Abstraction
Chapter 11 Abstraction - The concept of abstraction is fundamental in
Presentation transcript:

Announcements HW10 due November 27 Rainbow grades: Exam 1-2 Quiz 1-6 If you have any questions/concerns, let us know ASAP Now grading: HW9 and Quiz 7 Fall 18 CSCI 4430, A Milanova

Last Class Type equivalence Type in C Primitive types Composite types Records (Structs) Variants (Unions) Arrays Pointers Fall 18 CSCI 4430, A Milanova

Today’s Lecture Outline Control Abstraction Parameter Passing Mechanisms Call by value Call by reference Call by value-result Call by name Call by sharing Fall 18 CSCI 4430, A Milanova

Control Abstraction and Parameter Passing Read: Scott, Chapter 9.1-9.3 (lecture notes cover mostly 9.3)

Abstraction Abstraction: hiding unnecessary low-level detail Data abstraction: types Type integer is an abstraction Type struct Person is an abstraction Control abstraction: subroutines A subroutine abstracts away an algorithm A subroutine provides an interface: name, argument types, return type: e.g., int binarySearch(int a[], int v) Classes/objects in OO, Abstract Data Types (ADTs) are a higher level of abstraction Fall 18 CSCI 4430, A Milanova

Subroutines Other terms: procedures and functions Modularize program structure Argument: information passed from the caller to the callee (also called actual parameter or actual argument) Parameter: local variable in the callee, whose value is received from the caller (also called formal parameter) Fall 18 CSCI 4430, A Milanova/BG Ryder

Parameter Passing Mechanisms How does the caller pass information to the callee? Call by value C, Pascal, Ada, Algol68 Call by reference Fortran, C++, Pascal var params, sometimes Cobol Call by value-result (copy-in/copy-out) Ada Call by name (outmoded) Algol60 Discussion applies to value model for variables

Parameter Passing Modes Most languages use a single parameter passing rule E.g., Fortran, C Other languages allow different modes, in other words, programmer can choose different parameter passing rules in different contexts E.g., C++ has two parameter passing mechanisms, Pascal too Fall 18 CSCI 4430, A Milanova/BG Ryder

Call by Value Value of argument is copied into parameter location m,n : integer; procedure R(k,j : integer) begin k := k+1; j := j+2; end R; … m := 5; n := 3; R(m,n); write m,n; By Value: k j 5 3 6 5 Output: 5 3

Call by Reference m,n : integer; procedure R(k,j : integer) begin Argument is an l-value; l-value is passed to the parameter m,n : integer; procedure R(k,j : integer) begin k := k+1; j := j+2; end R; … m := 5; n := 3; R(m,n); write m,n; Value update happens in storage of caller, while callee is executing k,m j,n 5 3 6 5 Output: 6 5

Call by Value vs. Call by Reference Advantage: safe Disadvantage: inefficient Call by reference Advantage: more efficient Disadvantage: potentially unsafe due to aliasing Aliasing (memory aliasing) occurs when two or more different names refer to the same memory location E.g., m in main, and k in R are aliases for the same memory location during the call to R Advantages The argument is protected from changes in callee Disadvantages Copying of values takes execution time and space, and can be a problem for large, aggregate values

Aliasing: Call by Reference y: integer; procedure P(x: integer) begin x := x + 1; x := x + y; end P; … y := 2; P(y); write y; During the call, x and y are two different names for the same location! x -->y x,y 2 3 6 Output: 6 Fall 18 CSCI 4430, A Milanova/BG Ryder

No Aliasing: Call by Value y: integer; procedure P(x: integer) begin x := x + 1; x := x + y; end P; … y := 2; P(y); write y; 3 x 2 5 y 2 Output: 2 Fall 18 CSCI 4430, A Milanova/BG Ryder

More Aliasing with Call by Reference j,k,m : integer; procedure Q(a,b : integer) begin b := 3; a := m * a; end Q; ... s1: Q(m, k); s2: Q(j, j); Global-formal aliases: <m,a> <k,b> associations during call to Q at s1 Formal-formal aliases: <a,b> during call at s2 Fall 18 CSCI 4430, A Milanova/BG Ryder

Questions Aliasing is an important concept in programming Can you think of other examples of aliasing? Why memory aliasing is considered dangerous? Can you think of other ways for creating memory aliasing? Fall 18 CSCI 4430, A Milanova/BG Ryder

Memory Aliasing is Dangerous One part of the program can modify a location through one alias, breaking invariants/expectations of other parts that use different aliases to the same location In general, we cannot know whether x->f and y->f are aliases to the same location We “err” on the safe side Aliasing makes reasoning about code hard Aliasing prevents compiler optimization

Readonly Parameters What are some defenses against unwanted modification through aliases? const parameters are an important paradigm in C/C++ log(const huge_struct &r) { … } … log(my_huge_struct); Fall 18 CSCI 4430, A Milanova/BG Ryder

Readonly Parameters const can be tricky… log(const huge_struct * r) { r->f = 0; // NOT OK } vs. log(huge_struct * const r) { r->f = 0; // OK Fall 18 CSCI 4430, A Milanova

Readonly Parameters class C { int f; public: int get() const { return f; } int set(int g) { f = g; } }; Fall 18 CSCI 4430, A Milanova

More on Call by Reference What happens when someone uses an expression argument for a call-by-reference parameter? (2*x)? In general, languages that implement call by reference, disallow arguments from being expressions as above. In other words, an argument passed by reference should be something that has an address (an l-value), it cannot be the result of an arithmetic operation or any other value without an address. However, some languages (e.g., Fortran) allow this. They write the expression in a temporary, and pass the address of the temporary to the callee. Fall 18 CSCI 4430, A Milanova/BG Ryder

Call by Value-Result Argument is copied in into the parameter at entry, parameter is copied out into the argument at exit m,n : integer; procedure R(k,j : integer) begin k := k+1; j := j+2; end R; … m := 5; n := 3; R(m,n); write m,n; By Value-Result k j 5 3 6 5 Output: 6 5

Call by Value-Result c : array [1..10] of integer; m,n : integer; procedure R(k,j : integer) begin k := k+1; j := j+2; end R; /* set c[i] = i */ m := 2; R(m, c[m]); write c[1], c[2], …, c[10]; k j 2 2 3 4 What element of c has its value changed? c[2]? c[3]? There can be variations in the implementation. Are parameters copied out from left to right, or from right to left? Are the l-values of the arguments evaluated only once, at procedure entry, or are they re-evaluated at procedure exit? One possible implementation is to copy arguments from left to right and reevaluate the l-value at exit. This will produce m = 3, and c[3] = 4. 2. Another possible implementation is to copy from left-to-right but use the l-value at procedure entry. I.e., m gets 3 and c[2], which was the address of the second actual argument at entry, gets 4. 3. Another is to use copy from right-to-left. Then c[2] gets 4 and m gets 3. Fall 18 CSCI 4430, A Milanova/BG Ryder

Exercise Write a program that produces different result when the parameter passing mechanism is call by reference and when it is call by value-result Fall 18 CSCI 4430, A Milanova/BG Ryder

Call by Name An expression argument is not evaluated at call. It is evaluated within the callee, if needed. c : array [1..10] of integer; m : integer; procedure R(k,j : integer) begin k := k+1; j := j+2; end R; /* set c[i] to i */ m := 2; R(m, c[m]); write m,c[m] m := m + 1 c[m] := c[m] + 2 m c[ ] 2 1 2 3 4 5 6 7 8 9 10 3 1 2 5 4 5 6 7 8 9 10 Fall 18 CSCI 4430, A Milanova/BG Ryder

Call by Name Call by name (Algol 60) Case1: Argument is a variable Same as call by reference Case2: Argument is an expression E.g., expressions c[m], f(x,y), x+z, etc. Evaluation of the argument is deferred until needed Argument is evaluated in the caller’s environment – the expression goes with a THUNK (a closure!) which carries the necessary environment Generally inefficient Difficult to implement Fall 18 CSCI 4430, A Milanova/BG Ryder

Call by Name vs. Call by Value Recall reduction strategies in the -calculus What reduction strategy corresponds to call by name? Normal order reduction What reduction strategy corresponds to call by value? Applicative order reduction Fall 18 CSCI 4430, A Milanova/BG Ryder

Reference Model for Variables So far, discussion applied to the value model for variables What is the parameter passing mechanism in languages that use the reference model for variables? Neither call by value, nor call by reference make sense for languages with the reference model Call by sharing: argument reference (address) is copied into parameter. Argument and parameter references refer to the same object Fall 18 CSCI 4430, A Milanova/BG Ryder

Reference Model for Variables How does call by sharing relate to call by value? Similarities? Differences? How does call by sharing relate to call by reference? Fall 18 CSCI 4430, A Milanova/BG Ryder

Immutability Immutability is a “defense” against unwanted mutation due to sharing In Scheme, methods are pure In Python, there are immutable datatypes In Java, not much… There is no const-like construct to protect the referenced object final disallows re-assignment of a variable final Point p = new Point(); p = q; // NOT OK p.x = 0; r.y = 0; // ALL OK

Immutability Software engineering principles that help protect against unwanted mutation due to “sharing” Avoid representation exposure (rep exposure) Design immutable ADTs Write specifications that emphasize immutable parameters E.g., modifies: none

Exercise Construct a program which prints different result when parameter passing mechanism is Call by value Call by reference Call by value-result Call by name Fall 18 CSCI 4430, A Milanova/BG Ryder

Object-Oriented Programming Languages Read: Scott, Chapter 10.1-10.4 Read the chapter, it is an interesting exploration of design and implementation of many object-oriented languages and their precursors.

Lecture Outline Object-oriented programming Encapsulation and inheritance Initialization and finalization Subtyping and dynamic method binding Polymorphism Fall 18 CSCI 4430, A Milanova/BG Ryder

Benefits of Object Orientation Abstraction Classes bridge the gap between concepts in the application domain and software E.g., domain concept of Customer maps to class Customer Encapsulation Classes provide interface but hide data Easier to understand and use Can be changed internally with minimal impact Reuse Inheritance and composition provide mechanisms for reuse Extensibility There is somewhat of a disagreement in the Programming Languages community as to what is an “object oriented language”. The most widely accepted definition is that “languages and techniques based on classes and instances of these classes” are said to be object-oriented.

Encapsulation and Inheritance Access control modifiers – public, private, and others What portion of the class is visible to users ? Public, protected or private visibility Java: Has package as default; protected is slightly different from C++ C++: Has friend classes and functions Smalltalk and Python: all members are public With inheritance What control does the superclass have over its fields and methods? There are different choices C++: a subclass can restrict visibility of superclass members C#, Java: a subclass can neither increase nor restrict visibility of superclass members In Java protected means that the member is visible to all subclasses AND to all classes in the same package as the current class. Fall 18 CSCI 4430, A Milanova/BG Ryder

Initialization and Finalization Reference model for variables used in Java, Smalltalk, Python Every variable is a reference to an object Explicit object creation: foo b = new foo(); Value model for variables used in C++, Modula-3, Ada-95 A variable can have a value that is an object Object creation can be implicit: e.g. foo b; How are objects destroyed? Fall 18 CSCI 4430, A Milanova/BG Ryder

Question Consider the following code: A a; // a is a local variable of type A a.m(); // We call method m on a What happens in C++? What happens in Java? This is valid syntax for both C++ and Java. It will compile in C++ and in Java (strictly, it won’t compile in Java but let’s assume there is no Definite Assignment Check). In C++, a is a location that stores a value; the value happens to be an object. In C++, the object A gets created and initialized implicitly, on the STACK. C++ insists that an appropriate constructor is called on any such object. Thus (assuming that A::A() exists in A), the object A is created and initialized, on the stack, and the call to m() proceeds as expected. In Java, a is simply a reference, an address. By default, this address is null. When the runtime tries to call a.m() this triggers a NullPointerException. Java requires an explicit creation, i.e., we need to say A a = new A(). The A object is created on the HEAP. Note that if a is a local variable, newer versions of the Java compiler do the “Definite Assignment Check” and compilation fails. a can be a uninitialized field, which will trigger the NullPointerException. Fall 18 CSCI 4430, A Milanova/BG Ryder

More on implicit creation in C++ C++ requires that an appropriate constructor is called for every object implicitly created on the stack, e.g., A a; What happens here: foo a; Compiler calls zero-argument constructor foo::foo() What happens here: foo a(10, ‘x’); Calls foo::foo(int, char) Fall 18 CSCI 4430, A Milanova/BG Ryder

More on implicit creation in C++ What happens here: foo a; foo c = a; Calls foo::foo() at foo a; calls copy constructor foo::foo(foo&) at foo c = a; = operator here stands for initialization, not assignment! Fall 18 CSCI 4430, A Milanova/BG Ryder

More on implicit creation in C++ What happens here: foo a, c; // declaration c = a; // assignment Calls foo::foo() twice at foo a, c; calls assignment operator foo::operator=(foo&) at c = a; = operator here stands for assignment! Fall 18 CSCI 4430, A Milanova/BG Ryder

Lecture Outline Object Oriented programming Encapsulation and inheritance Initialization and finalization Subtyping and dynamic method binding Polymorphism Fall 18 CSCI 4430, A Milanova/BG Ryder

Subtyping and Dynamic Method Binding Subtyping and subtype polymorphism – the ability to use a subclass where a superclass is expected Thus, dynamic method binding Advantages? Disadvantages? C++: static binding is default, dynamic binding is specified with keyword virtual Java: dynamic binding is default, static binding is specified with final What is dynamic method binding (also known as dynamic dispatch)? The ability of an object to invoke a new, refined method, even in a context, where an earlier version is expected. E.g., B is a subclass of A and both A and B define m(). We can use a B object where an A object is expected: A a; … a.m() // If a binds to a B object, then B’s m() will be called. Fall 18 CSCI 4430, A Milanova/BG Ryder

Benefits of Subtype Polymorphism Covered extensively in Principles of Software  Enables extensibility and reuse E.g., we can extend a type hierarchy with no modification to the client of hierarchy Reuse through inheritance or composition Subtype polymorphism enables the Open/closed principle (credited to Bertrand Meyer) Software entities (classes, modules) should be open for extension but closed for modification Fall 18 CSCI 4430, A Milanova/BG Ryder

Benefits of Subtype Polymorphism “Science” of software design teaches Design Patterns Design patterns promote design for extensibility and reuse Nearly all design patterns make use of subtype polymorphism! Design Pattern is informally, a “best practice” design solution to a commonly occurring design problem/situation. Fall 18 CSCI 4430, A Milanova/BG Ryder

Lecture Outline Object-oriented programming Encapsulation and inheritance Initialization and finalization Subtyping and dynamic method binding Polymorphism Fall 18 CSCI 4430, A Milanova/BG Ryder

Polymorphism, more generally Subtype polymorphism What we just discussed… Code can use a subclass B where a superclass A is expected Standard in object-oriented languages Parametric polymorphism Code takes a type as parameter Explicit parametric polymorphism Implicit parametric polymorphism Standard in functional programming languages Ad-hoc polymorphism (overloading) There is considerable debate in the programming languages community as to whether a language should implement subtype polymorphism, parametric polymorphism or both. Fall 18 CSCI 4430, A Milanova/BG Ryder

Explicit Parametric Polymorphism Occurs in Ada, Clu, C++, Java, Haskell (type classes) There is an explicit type parameter Explicit parametric polymorphism is also known as genericity e.g. in C++: template<class V> class list_node { list_node<V>* prev; … } In templated classes list_node and list V is the explicit type parameter. template<class V> class list { list_node<V> header; … }

Explicit Parametric Polymorphism Usually (but not always!) implemented by creating multiple copies of the generic code, one for each concrete type typedef list_node<int> int_list_node; typedef list<int> int_list; Object-oriented languages usually provide both subtype polymorphism and explicit parametric polymorphism, which is referred to as generics Fall 18 CSCI 4430, A Milanova/BG Ryder

Explicit Parametric Polymorphism Generics are tricky… Consider this C++ code (uses the STL): Compiler produces around 2K of text of error messages, referring to code in the STL The problem here is that the STL’s sort requires a RandomAccessIterator, while the list container provides only a Bidirectional Iterator list<int> l; sort(l.begin(), l.end()); Example from generic-programming.org template <class RandomAccessIterator> void sort (RandomAccessIterator first, RandomAccessIterator last); Fall 18 CSCI 4430, A Milanova/BG Ryder

In Java, Bounded Types Restrict Instantiations by Client Generic code can perform operations permitted by the bound class MyList1<E extends Object> { void m(E arg) { arg.intValue();//compile-time error; Object //does not have intValue() } class MyList2<E extends Number> { arg.intValue();//OK. Number has intValue() This is in contrast with C++. In C++, generic code can call operations on parameter type. If instantiated with “wrong type”, C++ template spits tons of errors. Java allows bounded types and compile time type-checking, which clearly points to the programmer where the error is. Fall 18 CSCI 4430, A Milanova (modified from example by Michael Ernst)

In Haskell, Type Predicates Restrict Instantiation of Generic Functions sum :: (Num a) => a -> List a -> a sum n Nil = n sum n (Cons x xs) = sum (n+x) xs a is an explicit type parameter (Num a) is a predicate in type definition (Num a) constrains the types we can instantiate a generic function with Fall 18 CSCI 4430, A Milanova

Implicit Parametric Polymorphism Occurs in Scheme, Python and others There is no explicit type parameter, yet the code works on many different types! Usually, there is a single copy of the code, and all type checking is delayed until runtime If the arguments are of type as expected by the code, code works If not, code issues a type error at runtime Fall 18 CSCI 4430, A Milanova/BG Ryder

Implicit Parametric Polymorphism twice in Scheme: (define (twice f x) (f (f x))) (twice (lambda (x) (+ 1 x)) 1) yields ? (twice (lambda (x) (cons ‘a x)) ‘(b c)) yields ? (twice 2 3) yields ? map, foldl, length are all implicitly parametric (twice (lambda (x) (+ 1 x)) 1) yields 3 (twice (lambda (x) (cons ‘a x)) ‘(b c)) yields (a a b c) (twice 2 3) yields an error because 2 is not a function!

Implicit Parametric Polymorphism def intersect(seq1, seq2): res = [ ] for x in seq1: if x in seq2: res.append(x) return res As long as arguments for seq1 and seq2 are of iterable type, intersect works Fall 18 CSCI 4430, A Milanova/BG Ryder

Happy Thanksgiving! Fall 18 CSCI 4430, A Milanova