Presentation is loading. Please wait.

Presentation is loading. Please wait.

Announcements HW10 due November 27 Rainbow grades:

Similar presentations


Presentation on theme: "Announcements HW10 due November 27 Rainbow grades:"— Presentation transcript:

1 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

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

3 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

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

5 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

6 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

7 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

8 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

9 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

10 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 6 5 Output: 6 5

11 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

12 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

13 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

14 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

15 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

16 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

17 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

18 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

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

20 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

21 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

22 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

23 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

24 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[ ] 3 Fall 18 CSCI 4430, A Milanova/BG Ryder

25 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

26 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

27 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

28 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

29 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

30 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

31 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

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

33 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

34 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.

35 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

36 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

37 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

38 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

39 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

40 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

41 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

42 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

43 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

44 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

45 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

46 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

47 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; }

48 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

49 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

50 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)

51 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

52 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

53 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!

54 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

55 Happy Thanksgiving! Fall 18 CSCI 4430, A Milanova

56


Download ppt "Announcements HW10 due November 27 Rainbow grades:"

Similar presentations


Ads by Google