
























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

























Standard Description: This summary covers roughly the same material as lecture and section. It can help to read about the material in a narrative style and to have the material for an entire unit of the course in a single document, especially when reviewing the material later. Please report errors in these notes, even typos. This summary is not a sufficient substitute for attending class, reading the associated code, etc.
OOP Versus Functional Decomposition................................ 1
Extending the Code With New Operations or Variants...................... 5
Binary Methods With Functional Decomposition.......................... 7
Binary Methods in OOP: Double Dispatch.............................. 8
Multimethods................................................ 11
Multiple Inheritance............................................ 12
Mixins..................................................... 13
Java/C#-Style Interfaces......................................... 16
Abstract Methods.............................................. 17
Introduction to Subtyping........................................ 17
A Made-Up Language of Records.................................... 18
Wanting Subtyping............................................. 19
The Subtyping Relation.......................................... 19
Depth Subtyping: A Bad Idea With Mutation........................... 20
The Problem With Java/C# Array Subtyping........................... 22
Function Subtyping............................................. 23
Subtyping for OOP............................................. 25
Covariant self/this............................................. 26
Generics Versus Subtyping........................................ 27
Bounded Polymorphism.......................................... 29
Optional: Additional Java-Specific Bounded Polymorphism................... 30
We can compare procedural (functional) decomposition and object-oriented decomposition using the classic example of implementing operations for a small expression language. In functional programming, we typically break programs down into functions that perform some operation. In OOP, we typically break programs down into classes that give behavior to some kind of data.
We show that the two approaches largely lay out the same ideas in exactly opposite ways, and which way is “better” is either a matter of taste or depends on how software might be changed or extended in the future. We then consider how both approaches deal with operations over multiple arguments, which in many object-oriented languages requires a technique called double (multiple) dispatch in order to stick with an object-oriented style.
The Basic Set-Up
The following problem is the canonical example of a common programming pattern, and, not coincidentally, is a problem we have already considered a couple times in the course. Suppose we have:
This problem leads to a conceptual matrix (two-dimensional grid) with one entry for each combination of variant and operation:
eval toString hasZero Int Add Negate
No matter what programming language you use or how you approach solving this programming problem, you need to indicate what the proper behavior is for each entry in the grid. Certain approaches or languages might make it easier to specify defaults, but you are still deciding something for every entry.
The Functional Approach
In functional languages, the standard style is to do the following:
Note this approach is really just procedural decomposition: breaking the problem down into procedures corresponding to each operation.
This ML code shows the approach for our example: Notice how we define all the kinds of data in one place and then the nine entries in the table are implemented “by column” with one function for each column:
exception BadResult of string
datatype exp = Int of int | Negate of exp | Add of exp * exp
fun eval e = case e of
end def toString @i.to_s end def hasZero i== end end class Negate < Exp attr_reader :e def initialize e @e = e end def eval Int.new(-e.eval.i) # error if e.eval has no i method (not an Int) end def toString "-(" + e.toString + ")" end def hasZero e.hasZero end end class Add < Exp attr_reader :e1, :e def initialize(e1,e2) @e1 = e @e2 = e end def eval Int.new(e1.eval.i + e2.eval.i) # error if e1.eval or e2.eval have no i method end def toString "(" + e1.toString + " + " + e2.toString + ")" end def hasZero e1.hasZero || e2.hasZero end end
The Punch-Line
So we have seen that functional decomposition breaks programs down into functions that perform some operation and object-oriented decomposition breaks programs down into classes that give behavior to some kind of data. These are so exactly opposite that they are the same — just deciding whether to lay out our program “by column” or “by row.” Understanding this symmetry is invaluable in conceptualizing software or deciding how to decompose a problem. Moreover, various software tools and IDEs can help you view a program in a different way than the source code is decomposed. For example, a tool for an OOP language that shows you all methods foo that override some superclass’ foo is showing you a column even though the code is organized by rows.
So, which is better? It is often a matter of personal preference whether it seems “more natural” to lay out
the concepts by row or by column, so you are entitled to your opinion. What opinion is most common can depend on what the software is about. For our expression problem, the functional approach is probably more popular: it is “more natural” to have the cases for eval together rather than the operations for Negate together. For problems like implementing graphical user interfaces, the object-oriented approach is probably more popular: it is “more natural” to have the operations for a kind of data (like a MenuBar) together (such as backgroundColor, height, and doIfMouseIsClicked rather than have the cases for doIfMouseIsClicked together (for MenuBar, TextBox, SliderBar, etc.). The choice can also depend on what programming language you are using, how useful libraries are organized, etc.
The choice between “rows” and “columns” becomes less subjective if we later extend our program by adding new data variants or new operations.
Consider the functional approach. Adding a new operation is easy: we can implement a new function without editing any existing code. For example, this function creates a new expression that evaluates to the same result as its argument but has no negative constants:
fun noNegConstants e = case e of Int i => if i < 0 then Negate (Int(~i)) else e | Negate e1 => Negate(noNegConstants e1) | Add(e1,e2) => Add(noNegConstants e1, noNegConstants e2)
On the other hand, adding a new data variant, such as Mult of exp * exp is less pleasant. We need to go back and change all our functions to add a new case. In a statically typed language, we do get some help: after adding the Mult constructor, if our original code did not use wildcard patterns, then the type-checker will give a non-exhaustive pattern-match warning everywhere we need to add a case for Mult.
Again the object-oriented approach is exactly the opposite. Adding a new variant is easy: we can implement a new subclass without editing any existing code. For example, this Ruby class adds multiplication expressions to our language:
class Mult < Exp attr_reader :e1, :e def initialize(e1,e2) @e1 = e @e2 = e end def eval Int.new(e1.eval.i * e2.eval.i) # error if e1.eval or e2.eval has no i method end def toString "(" + e1.toString + " * " + e2.toString + ")" end def hasZero e1.hasZero || e2.hasZero end end
On the other hand, adding a new operation, such as noNegConstants, is less pleasant. We need to go back
(without breaking extensions). In fact, languages often provide constructs exactly to prevent extensibility. ML’s modules can hide datatypes, which prevents defining new operations over them outside the module. Java’s final modifier on a class prevents subclasses.
The operations we have considered so far used only one value of a type with multiple data variants: eval, toString, hasZero, and noNegConstants all operated on one expression. When we have operations that take two (binary) or more (n-ary) variants as arguments, we often have many more cases. With functional decomposition all these cases are still covered together in a function. As seen below, the OOP approach is more cumbersome.
For sake of example, suppose we add string values and rational-number values to our expression language. Further suppose we change the meaning of Add expressions to the following:
So it is an error to have a subexpression of Negate or Mult evaluate to a String or Rational, but the subexpressions of Add can be any kind of value in our language: int, string, or rational.
The interesting change to the SML code is in the Add case of eval. We now have to consider 9 (i.e., 3 ∗ 3) subcases, one for each combination of values produced by evaluating the subexpressions. To make this explicit and more like the object-oriented version considered below, we can move these cases out into a helper function add_values as follows:
fun eval e = case e of ... | Add(e1,e2) => add_values (eval e1, eval e2) ...
fun add_values (v1,v2) = case (v1,v2) of (Int i, Int j) => Int (i+j) | (Int i, String s) => String(Int.toString i ^ s) | (Int i, Rational(j,k)) => Rational(ik+j,k) | (String s, Int i) => String(s ^ Int.toString i) ( not commutative ) | (String s1, String s2) => String(s1 ^ s2) | (String s, Rational(i,j)) => String(s ^ Int.toString i ^ "/" ^ Int.toString j) | (Rational _, Int _) => add_values(v2,v1) ( commutative: avoid duplication ) | (Rational(i,j), String s) => String(Int.toString i ^ "/" ^ Int.toString j ^ s) | (Rational(a,b), Rational(c,d)) => Rational(ad+bc,bd) | _ => raise BadResult "non-values passed to add_values"
Notice add_values is defining all 9 entries in this 2-D grid for how to add values in our language — a different kind of matrix than we considered previously because the rows and columns are variants.
Int String Rational Int String Rational
While the number of cases may be large, that is inherent to the problem. If many cases work the same way, we can use wildcard patterns and/or helper functions to avoid redundancy. One common source of redundancy is commutativity, i.e., the order of values not mattering. In the example above, there is only one such case: adding a rational and an int is the same as adding an int and a rational. Notice how we exploit this redundancy by having one case use the other with the call add_values(v2,v1).
We now turn to supporting the same enhancement of strings, rationals, and enhanced evaluation rules for Add in an OOP style. Because Ruby has built-in classes called String and Rational, we will extend our code with classes named MyString and MyRational, but obviously that is not the important point. The first step is to add these classes and have them implement all the existing methods, just like we did when we added Mult previously. Then that “just” leaves revising the eval method of the Add class, which previously assumed the recursive results would be instances of Int and therefore have a getter method i:
def eval Int.new(e1.eval.i + e2.eval.i) # error if e1.eval or e2.eval have no i method end
Now we could instead replace this method body with code like our add_values helper function in ML, but helper functions like this are not OOP style. Instead, we expect add_values to be a method in the classes that represent values in our language: An Int, MyRational, or MyString should “know how to add itself to another value.” So in Add, we write:
def eval e1.eval.add_values e2.eval end
This is a good start and now obligates us to have add_values methods in the classes Int, MyRational, and MyString. By putting add_values methods in the Int, MyString, and MyRational classes, we nicely divide our work into three pieces using dynamic dispatch depending on the class of the object that e1.eval returns, i.e., the receiver of the add_values call in the eval method in Add. But then each of these three needs to handle three of the nine cases, based on the class of the second argument. One approach would be to, in these methods, abandon object-oriented style (!) and use run-time tests of the classes to include the three cases. The Ruby code would look like this:
class Int ... def add_values v if v.is_a? Int ... elsif v.is_a? MyRational ... else
end def addRational v # second dispatch: v is MyRational MyRational.new(v.i+v.ji,v.j) end end class MyString ... # other methods not related to add_values def add_values v # first dispatch v.addString self end def addInt v # second dispatch: v is Int MyString.new(v.i.to_s + s) end def addString v # second dispatch: v is MyString MyString.new(v.s + s) end def addRational v # second dispatch: v is MyRational MyString.new(v.i.to_s + "/" + v.j.to_s + s) end end class MyRational ... # other methods not related to add_values def add_values v # first dispatch v.addRational self end def addInt v # second dispatch v.addRational self # reuse computation of commutative operation end def addString v # second dispatch: v is MyString MyString.new(v.s + i.to_s + "/" + j.to_s) end def addRational v # second dispatch: v is MyRational a,b,c,d = i,j,v.i,v.j MyRational.new(ad+bc,bd) end end
Before understanding how all the method calls work, notice that we do now have our 9 cases for addition in 9 different methods:
As we might expect in OOP, our 9 cases are “spread out” compared to in the ML code. Now we need to understand how dynamic dispatch is picking the correct code in all 9 cases. Starting with the eval method in Add, we have e1.eval.add_values e2.eval. There are 3 add_values methods and dynamic dispatch will pick one based on the class of the value returned by e1.eval. This the “first dispatch.” Suppose e1.eval is an Int. Then the next call will be v.addInt self where self is e1.eval and v is e2.eval. Thanks again to dynamic dispatch, the method looked up for addInt will be the right case of the 9. This is the “second dispatch.” All the other cases work analogously.
Understanding double dispatch can be a mind-bending exercise that re-enforces how dynamic dispatch works, the key thing that separates OOP from other programming. It is not necessarily intuitive, but it what one must do in Ruby/Java to support binary operations like our addition in an OOP style.
Notes:
It is not true that all OOP languages require the cumbersome double-dispatch pattern to implement bi- nary operations in a full OOP style. Languages with multimethods, also known as multiple dispatch, provide more intuitive solutions. In such languages, the classes Int, MyString, and MyRational could each define three methods all named add_values (so there would be nine total methods in the program named add_values). Each add_values method would indicate the class it expects for its argument. Then e1.eval.add_values e2.eval would pick the right one of the 9 by, at run-time, considering the class of the result of e1.eval and the class of the result of e2.eval.
This is a powerful and different semantics than we have studied for OOP. In our study of Ruby (and Java/C#/C++ work the same way), the method-lookup rules involve the run-time class of the receiver (the object whose method we are calling), not the run-time class of the argument(s). Multiple dispatch is “even more dynamic dispatch” by considering the class of multiple objects and using all that information to choose what method to call.
Without multiple inheritance, you end up copying code in these examples. For example, ColorPoint3D can subclass Point3D and copy code from ColorPoint or it can subclass ColorPoint and copy code from Point3D.
If we have multiple inheritance, we have to decide what it means. Naively we might say that the new class has all the methods of all the superclasses (and fields too in languages where fields are part of class definitions). However, if two of the immediate superclasses have the same fields or methods, what does that mean? Does it matter if the fields or methods are inherited from the same common ancestor? Let us explain these issues in more detail before returning to our examples.
With single inheritance, the class hierarchy — all the classes in a program and what extends what — forms a tree, where A extends B means A is a child of B in the tree. With multiple inheritance, the class hierarchy may not be a tree. Hence it can have “diamonds” — four classes where one is a (not necessarily immediate) subclass of two others that have a common (not necessarily immediate) superclass. By “immediate” we mean directly extends (child-parent relationship) whereas we could say “transitive” for the more general ancestor-descendant relationship.
With multiple superclasses, we may have conflicts for the fields / methods inherited from the different classes. The draw method for ArtistCowboy objects is an obvious example where we would like somehow to have both methods in the subclass, or potentially to override one or both of them. At the very least we need expressions using super to indicate which superclass is intended. But this is not necessarily the only conflict. Suppose the Person class has a pocket field that artists and cowboys use for different things. Then perhaps an ArtistCowboy should have two pockets, even though the creation of the notion of pocket was in the common ancestor Person.
But if you look at our ColorPoint3D example, you would reach the opposite conclusion. Here both Point3D and ColorPoint inherit the notion of x and y from a common ancestor, but we certainly do not want a ColorPoint3D to have two x methods or two @x fields.
These issues are some of the reasons language with multiple inheritance (most well-known is C++) need fairly complicated rules for how subclassing, method lookup, and field access work. For example, C++ has (at least) two different forms of creating a subclass. One always makes copies of all fields from all superclasses. The other makes only one copy of fields that were initially declared by the same common ancestor. (This solution would not work well in Ruby because instance variables are not part of class definitions.)
Ruby has mixins, which are somewhere between multiple inheritance (see above) and interfaces (see below). They provide actual code to classes that include them, but they are not classes themselves, so you cannot create instances of them. Ruby did not invent mixins. Its standard-library makes good use of them, though. A near-synonym for mixins is traits, but we will stick with what Ruby calls mixins.
To define a Ruby mixin, we use the keyword module instead of class. (Modules do a bit more than just serve as mixins, hence the strange word choice.) For example, here is a mixin for adding color methods to a class:
module Color attr_accessor :color def darken self.color = "dark " + self.color end end
This mixin defines three methods, color, color=, and darken. A class definition can include these methods by using the include keyword and the name of the mixin. For example:
class ColorPt < Pt include Color end
This defines a subclass of Pt that also has the three methods defined by Color. Such classes can have other methods defined/overridden too; here we just chose not to add anything additional. This is not necessarily good style for a couple reasons. First, our initialize (inherited from Pt) does not create the @color field, so we are relying on clients to call color= before they call color or they will get nil back. So overriding initialize is probably a good idea. Second, mixins that use instance variables are stylistically questionable. As you might expect in Ruby, the instance variables they use will be part of the object the mixin is included in. So if there is a name conflict with some intended-to-be separate instance variable defined by the class (or another mixin), the two separate pieces of code will mutate the same data. After all, mixins are “very simple” — they just define a collection of methods that can be included in a class.
Now that we have mixins, we also have to reconsider our method lookup rules. We have to choose something and this is what Ruby chooses: If obj is an instance of class C and we send message m to obj,
Many of the elegant uses of mixins do the following strange-sounding thing: They define methods that call other methods on self that are not defined by the mixin. Instead the mixin assumes that all classes that include the mixin define this method. For example, consider this mixin that lets us “double” instances of any class that has + defined:
module Doubler def double self + self # uses self’s + message, not defined in Doubler end end
If we include Doubler in some class C and call double on an instance of the class, we will call the + method on the instance, getting an error if it is not defined. But if + is defined, everything works out. So now we can easily get the convenience of doubling just by defining + and including the Doubler mixin. For example:
class AnotherPt attr_accessor :x, :y include Doubler def + other # add two points ans = AnotherPt.new ans.x = self.x + other.x
class MyRange include Enumerable def initialize(low,high) @low = low @high = high end def each i=@low while i <= @high yield i i=i+ end end end
Now we can write code like MyRange.new(4,8).inject {|x,y| x+y} or MyRange.new(5,12).count {|i| i.odd?}. Note that the map method in Enumerable always returns an instance of Array. After all, it does not “know how” to produce an instance of any class, but it does know how to produce an array containing one element for everything produced by each. We could define it in the Enumerable mixin like this:
def map arr = [] each {|x| arr.push x } arr end
Mixins are not as powerful as multiple inheritance because we have to decide upfront what to make a class and what to make a mixin. Given Artist and Cowboy classes, we still have no natural way to make an ArtistCowboy. And it is unclear which of Artist or Cowboy or both we might want to define in terms of a mixin.
In Java or C#, a class can have only one immediate superclass but it can implement any number of interfaces. An interface is just a list of methods and each method’s argument types and return type. A class type- checks only if it actually provides (directly or via inheritance) all the methods of all the interfaces it claims to implement. An interface is a type, so if a class C implements interface I, then we can pass an instance of C to a method expecting an argument of type I, for example. Interfaces are closer to the idea of “duck typing” than just using classes as types (in Java and C# every class is also a type), but a class has some interface type only if the class definition explicitly says it implements the interface. We discuss more about OOP type-checking later in this unit.
Because interfaces do not actually define methods — they only name them and give them types — none of the problems discussed above about multiple inheritance arise. If two interfaces have a method-name conflict, it does not matter — a class can still implement them both. If two interfaces disagree on a method’s type, then no class can possibly implement them both but the type-checker will catch that. Because interfaces do not define methods, they cannot be used like mixins.
In a dynamically typed language, there is really little reason to have interfaces.^2 We can already pass any
(^2) Probably the only use would be to change the meaning of Ruby’s is a? to incorporate interfaces, but we can more directly just use reflection to find out an object’s methods.
object to any method and call any method on any object. It is up to us to keep track “in our head” (preferably in comments as necessary) what objects can respond to what messages. The essence of dynamic typing is not writing down this stuff.
Bottom line: Implementing interfaces does not inherit code; it is purely related to type-checking in statically typed languages like Java and C#. It makes the type systems in these languages more flexible. So Ruby does not need interfaces.
Often a class definition has methods that call other methods that are not actually defined in the class. It would be an error to create instances of such a class and use the methods such that “method missing” errors occur. So why define such a class? Because the entire point of the class is to be subclassed and have different subclasses define the missing methods in different ways, relying on dynamic dispatch for the code in the superclass to call the code in the subclass. This much works just fine in Ruby — you can have comments indicating that certain classes are there only for the purpose of subclassing.
The situation is more interesting in statically typed languages. In these languages, the purpose of type- checking is to prevent “method missing” errors, so when using this technique we need to indicate that instances of the superclass must not be created. In Java/C# such classes are called “abstract classes.” We also need to give the type of any methods that (non-abstract) subclasses must provide. These are “abstract methods.” Thanks to subtyping in these languages, we can have expressions with the type of the superclass and know that at run-time the object will actually be one of the subclasses. Furthermore, type-checking ensures the object’s class has implemented all the abstract methods, so it is safe to call these methods. In C++, abstract methods are called “pure virtual methods” and serve much the same purpose.
There is an interesting parallel between abstract methods and higher-order functions. In both cases, the language supports a programming pattern where some code is passed other code in a flexible and reusable way. In OOP, different subclasses can implement an abstract method in different ways and code in the superclass, via dynamic dispatch, can then uses these different implementations. With higher-order functions, if a function takes another function as an argument, different callers can provide different implementations that are then used in the function body.
Languages with abstract methods and multiple inheritance (e.g., C++) do not need interfaces. Instead we can just use classes that have nothing but abstract (pure virtual) methods in them like they are interfaces and have classes implementing these “interfaces” just subclass the classes. This subclassing is not inheriting any code exactly because abstract methods do not define methods. With multiple inheritance, we are not “wasting” our one superclass with this pattern.
We previously studied static types for functional programs, in particular ML’s type system. ML uses its type system to prevent errors like treating a number as a function. A key source of expressiveness in ML’s type system (not rejecting too many programs that do nothing wrong and programmers are likely to write) is parametric polymorphism, also known as generics.
So we should also study static types for object-oriented programs, such as those found in Java. If everything is an object (which is less true in Java than in Ruby), then the main thing we would want our type system to prevent is “method missing” errors, i.e., sending a message to an object that has no method for that message. If objects have fields accessible from outside the object (e.g., in Java), then we also want to prevent
Assuming the “regular” typing rules for other expressions like variables, functions, arithmetic, and function calls, an example like this will type-check as we would expect:
fun distToOrigin (p:{x:real,y:real}) = Math.sqrt(p.xp.x + p.yp.y)
val pythag : {x:real,y:real} = {x=3.0, y=4.0} val five : real = distToOrigin(pythag)
In particular, the function distToOrigin has type {x : real, y : real} -> real, where we write func- tion types with the same syntax as in ML. The call distToOrigin(pythag) passes an argument of the right type, so the call type-checks and the result of the call expression is the return type real.
This type system does what it is intended to do: No program that type-checks would, when evaluated, try to look up a field in a record that does not have that field.
With our typing rules so far, this program would not type-check:
fun distToOrigin (p:{x:real,y:real}) = Math.sqrt(p.xp.x + p.yp.y)
val c : {x:real,y:real,color:string} = {x=3.0, y=4.0, color="green"} val five : real = distToOrigin(c)
In the call distToOrigin(c), the type of the argument is {x:real,y:real,color:string} and the type the function expects is {x:real,y:real}, breaking the typing rule that functions must be called with the type of argument they expect. Yet the program above is safe: running it would not lead to accessing a field that does not exist.
A natural idea is to make our type system more lenient as follows: If some expression has a record type {f1:t1, ..., fn:tn}, then let the expression also have a type where some of the fields are removed. Then our example will type-check: Since the expression c has type {x:real,y:real,color:string}, it can also have type {x:real,y:real}, which allows the call to type-check. Notice we could also use c as an argument to a function of type {color:string}->int, for example.
Letting an expression that has one type also have another type that has less information is the idea of subtyping. (It may seem backwards that the subtype has more information, but that is how it works. A less-backwards way of thinking about it is that there are “fewer ” values of the subtype than of the supertype because values of the subtype have more obligations, e.g., having more fields.)
We will now add subtyping to our made-up language, in a way that will not require us to change any of our existing typing rules. For example, we will leave the function-call rule the same, still requiring that the type
of the actual argument equal the type of the function parameter in the function definition. To do this, we will add two things to our type system:
So now we just need to give rules for t1 <: t2, i.e., when is one type a subtype of another. This approach is good language engineering — we have separated the idea of subtyping into a single binary relation that we can define separately from the rest of the type system.
A common misconception is that if we are defining our own language, then we can make the typing and subtyping rules whatever we want. That is only true if we forget that our type system is allegedly preventing something from happening when programs run. If our goal is (still) to prevent field-missing errors, then we cannot add any subtyping rules that would cause us to stop meeting our goal. This is what people mean when they say, “Subtyping is not a matter of opinion.”
For subtyping, the key guiding principle is substitutability: If we allow t1 <: t2, then any value of type t must be able to be used in every way a t2 can be. For records, that means t1 should have all the fields that t2 has and with the same types.
Some Good Subtyping Rules
Without further ado, we can now give four subtyping rules that we can add to our language to accept more programs without breaking the type system. The first two are specific to records and the next two, while perhaps seeming unnecessary, do no harm and are common in any language with subtyping because they combine well with other rules:
Notice that width subtyping lets us forget fields, permutation subtyping lets us reorder fields (e.g., so we can pass a {x:real,y:real} in place of a {y:real,x:real}) and transitivity with those rules lets us do both (e.g., so we can pass a {x:real,foo:string,y:real} in place of a {y:real,x:real}).
Our subtyping rules so far let us drop fields or reorder them, but there is no way for a supertype to have a field with a different type than in the subtype. For example, consider this example, which passes a “sphere” to a function expecting a “circle.” Notice that circles and spheres have a center field that itself holds a record.
fun circleY (c:{center:{x:real,y:real}, r:real}) = c.center.y