Programming Languages: Chapter 15: Object-Orientation: Message Passing and Dynamic Binding



Outline


Most central motif of OOP

A program is a collection of autonomous objects, maintaining their own state and behavior, which collaborate and communicate by passing messages to each other to solve a problem (so called anthropomorphic programming model [PLP2] p. 491)

C++ programs are not such: some OO code, some imperative code and as a result are difficult to understand, maintain, and extend.

OOP = objects interacting through dynamically bound messages, and inheritance.


What is an object?

(recall closures)
  • occupy space
  • can be addressed only using a defined interface
  • can be thought of as an abstraction of a computer


History of OOP

  • Simula-67 was the origin of the ideas of object-oriented programming
  • though the ideas blossomed through Smalltalk
  • object-oriented LISP: LOOPS, FLAVORS [PLP2] p. 518


Pure OOP

OOP = everything is an object + dynamic binding

Ada, Eiffel, and C++, (and Java to an extent) are wannabe OO languages.
  • these languages have imperative and object-oriented features
  • in pure OO languages everything is an object, including classes, primitives, operators, and so on


Basic characteristics of class definitions

  • private variables
  • member functions
  • friends are bad


Message to method binding

A question of whether a message should bind to
  • a method in the class to which the reference variable pointing to the receiver was declared to be an instance of (static binding), or
  • a method in the class to which the receiver is an instance of at run-time (dynamic binding).


Dynamic binding

  • in the context of OOP typically refers to the binding of methods to messages
  • methods varying dynamically entails much of the power of the OO approach
  • main source of power in an OO language
  • search for method (code body) to bind to a message starts from the class to which the receiver currently (i.e., at run-time) is an instance of, and and proceeds up the class inheritance hierarchy from there (static binding initiates the search from the class to which the reference variable pointing to the receiver was declared to be an instance of)
  • if no method found anywhere, a run-time error (method not found) is reported and this is typically the only error in a Smalltalk program ever detected and reported
  • example:
    Mammal m;
    Cow c;
    
    if (user input)
       m = new Cow;
    
       // if static binding used, run method in class Mammal bound to run message here
       // if dynamic binding used, run method in class Cow bound to run message here
       m.run
    else
       c = new Cow;
       c.run
    


Why dynamic binding?

  • ``to allow software systems to be more easily extended during both development and maintenance'' [COPL6] p. 461
  • allows dynamic polymorphism, consider sorting (written in a general way)
  • obviates need for abstract classes (e.g., Fruit class, peel method)
  • while other forms of dynamism in languages tend to be compromise efficiency in the run-time system, dynamic binding involves little overhead


Dynamic vs. static binding

  • advantages of each?
  • disadvantages of each?


Message to method binding in languages

  • Smalltalk
    • dynamic by default
    • by sending a message to super we can initiate the search (for the method to bind to the message) in the parent class of the class to which the sender belongs (i.e., like sending a message to self with a different entry point for the search (not quite static binding))
  • Java and Eiffel
    • dynamic by default
    • in Java, preface method with final qualifier to prevent any subclass from overriding it
    • in Eiffel, preface method with frozen qualifier to prevent any subclass from overriding it
  • C++
    • static by default (why?)
    • preface method with virtual qualifier for dynamic binding; the search for the method to bind to the message starts in the class which defines the method prefaced with the virtual qualifier and proceeds down the inheritance hierarchy from there to the class to which the receiver object belongs
  • Objective-C, Modula-3, Python, and Ruby use dynamic binding for all methods
  • Simula, C# and Ada 95 use static binding by default and support dynamic binding as an option


Dynamic binding ambiguity

Do not confuse dynamic binding of messages to methods with dynamic allocation and deallocations of objects.
  • Smalltalk: manual dynamic allocation, automatic deallocation
  • Java: manual dynamic allocation, automatic deallocation
  • C++: manual dynamic allocation, manual deallocation


Polymorphism in object-orientation

both serve different purposes and have different implementations [PLP2] p. 507
  • subtype polymorphism (through inheritance, dynamic binding, and dynamic method dispatch): ``the ability to use a derived class in a context that expects its base class'' [PLP2] p. 498
  • explicit parametric polymorphism (also referred to as generics) supports abstraction over unrelated types


Generics

``In a nutshell, generics exist for the purpose of abstracting over unrelated types, something that inheritance does not support (NB: the type inference system of ML and related languages does suffice to abstract over unrelated types; ML does not require generics. On the other hand, while ML provides Euclid-like module types, it does not provide inheritance, and thus cannot be considered an object-oriented language.)'' [PLP2] p. 507
  • in Java, ``single copy of the code can generally be shared by every instance of a generic'' [PLP2] p. 507
  • in C++ achieved by the compiler generating ``multiple copies of the polymorphic code, one specialized for each needed concrete type'' [PLP2] p. 507


Abstract classes

  • a abstract method has no body (definition)
    • sometimes called a pure virtual method, especially in the context of C++
    • provides a hook for dynamic binding
  • any class which has an abstract method is an abstract class
  • an interface is a class with no fields or concrete methods (i.e., only abstract methods)


Reflection

  • the process of reasoning about and/or acting upon oneself
  • a way to inspect or modify a program while it is running
  • two aspects
    • introspection (or read-only reflection): the ability for a program to observe and therefore reason about its own state
    • intercession: the ability for a program to modify its own execution state or alter its own interpretation or meaning
  • Java supports read-only reflection (e.g., which methods does this class have?)


Smalltalk

  • developed at XEROX PARC in early 1970's by Alan Kay and colleagues as an environment to teach programming to children
  • influenced by both Simula and LISP
  • Smalltalk-72, Smalltalk-76, Smalltalk-80 (simply referred to as Smalltalk)
  • in Smalltalk, everything is an object (not so in C++ or Java)
    • even a class is an object
    • for instance, class FinancialHistory is the only object of class Meta-FinancialHistory
  • each object is an abstraction of a computer
  • was the first pure object-oriented language
    • it is completely consistent with the OO paradigm
    • Ruby is also pure
    • Java is almost pure
  • adopts an anthropomorphic programming model [PLP2] p. 491 (i.e., the only way to affect computation is to pass messages to objects which then execute code (a method) in response to the message)
  • not just a language, a complete software development environment
  • requires a mouse which was developed at PARC for this
  • uses a simple, uniform model of the world akin to LISP
  • uses a simple uniform syntax, again, akin to LISP
  • uniformity and simplicity: everything is an object
  • typeless (akin to LISP): any name can be bound to any object; class membership is the only typing
  • supports dynamic polymorphism (i.e., code is associated with no particular type)
  • automatic garbage collection
  • only reference variables which are implicitly dereferenced
  • only supports single inheritance
  • strongly typed (akin to ML and Haskell), but at runtime
  • dynamic nature
    • typeless language (akin to LISP)
    • dynamic binding
    • supports dynamic polymorphism
    • supports reflection: ability to inspect and modify a program while it is running!
  • contributions:
    • a new paradigm (not just a new language)
    • influential in personal computing revolution and windowing systems
  • inspired and pioneered
    • the object-oriented paradigm,
    • the idea of personal computing, and
    • windowing systems and GUI's (mouse)


Smalltalk syntax

  • class names must begin with an UPPER CASE letter and method names begin with a lower case letter; convention in C++ and Java, but not enforced
  • be careful to distinguish between
    • Object: root class (capital O)
    • object: just some object
  • period (.) is the statement separator
  • up arrow is return (typed ^); if omitted, then current object returned
  • left arrow (←) is assignment (typed _)
  • text between single quotes is treated as a string
  • text between double quotes are considered comments
  • local variables introduced with pipe symbols (e.g., | temp |)
  • blocks: [ ... ] can be thought of as a closure and call-by-name parameter; allows Smalltalk to handle control in a purely OO fashion


Smalltalk messages

  • sometimes called selectors
  • messages are written in postfix form
  • a colon precedes the argument to a message
  • (courtesy [PLPP] pp. 447-448)
  • unary
               // C++
               q.front()
    
               "Smalltalk"
               q front
          
  • keyword
               // C++
               q.enqueue(x)
    
               "Smalltalk"
               q enqueue: x
       
               // C++
               table.insert(anItem, anIndex)
    
               "Smalltalk"
               table insert: anItem at: anIndex
          
  • binary: 2 + 3
  • in this manner Smalltalk programs read like English


Purity in Smalltalk

  • 2+3 is not an expression!
  • 2+3 is the message + sent to object 2 with argument object 3, requesting that it add 3 to itself and return the result (the object 5)
  • for loop is an object


Objects in Smalltalk

  • allocated from the heap
  • deallocation is implicit using garbage collection akin to LISP


Simple examples

    1 to: 5 do: [:i | (Transcript show: 'Hello World') cr]
    
    dialog _ FillInTheBlank request: 'How may I help you, Larry?'
    


Developing a Smalltalk program

  • involves extending or modifying the existing class hierarchy
  • can modify the existing class hierarchy (no need to always subclass)
    • increment
    • decrement
  • all user-defined classes are automatically placed into this
  • the root class is called Object
  • life begins at class Object


OOP in Smalltalk

  • class: superclass, instance variables, and methods
  • no privacy control (simplistic/purity) of instance variables or methods, instance variables can only be accessed through methods (i.e., all instance variables private, all methods public)
  • self is the receiver (akin to this in C++ or Java)
  • super is the immediate super class


Use of super for defining new

  • new is a class method
  • classes are objects of a metaclass class (which implements new)
  • new
    ^super new setInitialBalance: 0
  • initialize: amount
    ^super new setInitialBalance: amount


if statement

  • written in postfix form
  • concept of a block
    • statically scoped closures
    • similar to lambda expressions in LISP
  • for instance, (Smalltalk heart) ifTrue: [car honk] (expression is an object) [BIST]
  • value message (evaluates a block)


Applications of Smalltalk

  • simulation
  • research


Comparison of Smalltalk, Java, and C++

What can be done in pure OO languages, such as Smalltalk, which cannot be done with impure OO languages, such as C++ or Java?

conceptSmalltalkJavaC++
purityyesalmostno
dynamic bindingdefaultdefaultas an option
polymorphismsubtypesubtypeparametric
stand alone classnoyesyes
multiple inheritancenonoyes
implicit dereferencingyesyesno
manual dynamic allocationyesyesyes
automatic garbage collectionyesyesno
reflectionyesyesno


Inheritance

  • Simula, Smalltalk, Objective-C, Modula-3, Ada, Oberon support only single inheritance
  • C++, CLOS, and Python support multiple inheritance
  • `Java, C#, and Ruby provide a limited mix-in form of multiple inheritance, in which only one parent class is permitted to have fields' and the other is an interface [PLP2] p. 511

For a laundry list of impurities in C++, see [PLP2] p 512.


Working with Squeak

  • demo of environment
  • local image of everything in your own directory


Basic interaction

  • Workspace window
  • Transcript window
  • System browser


Communicating between windows

  • Transcript show: 'hello'
  • Transcript show: cr
  • 2+3 arithmetic expressions really involve objects communicating through messages
  • browsing through existing classes in the System Browser


Other things to know about Squeak

  • saving and loading classes
  • a convenient way to access all of your code, from which you can copy and paste it to a file, from which you can print it
  • to dump your code to an HTML file, click printOut


Fun stuff

  • morph is the root of all graphical objects in Smalltalk
  • destroying the Energizer bunny - bunny destroy


A sample workspace

    Transcript open.
    
    Transcript show: 'hello'
    
    3 + 4 7
    
    1 to: 5 do: [:i | (Transcript show: 'Hello World') cr]
    
    prompt _ FillInTheBlank request: 'How may I help you, Linus?'
    
    N _ 6
    
    N class.
    
    <class name> selectors
    
    <class name> superclass.
    <class name> allSubclasses.
    
    <class name> withAllSubclasses.
    <class name> withAllSuperclasses.
    
    N decrement 6
    
    N _ Dictionary new.
    
    N inspect. "reflection"
    
    N at: '4:30' put: 'cps343'
    
    N at: '5:55' put: 'cps445'
    
    N _ 90.
    
    N inspect. 
    
    Object withAllSubclasses do: 
    
        [:clas | clas selectors do:
    	
             [:sel | 
    	         (sel asLowercase includesSubString: 'random')
    	 
    	          ifTrue: [
    		            Transcript show: clas name.
    		            Transcript show: ' '.
    		            Transcript show: sel.
    		            Transcript cr]]].
    
    Morph new openInWorld.
    


References

    [BIST] T. Budd. A Brief Introduction to Smalltalk. ACM SIGPLAN Notices, 28(3), 367-368, 1993.
    [COPL6] R.W. Sebesta. Concepts of Programming Languages. Addison-Wesley, Boston, MA, Sixth edition, 2003.
    [PLP2] M.L. Scott. Programming Language Pragmatics. Morgan Kaufmann, Amsterdam, Second edition, 2006.
    [PLPP] K.C. Louden. Programming Languages: Principles and Practice. Brooks/Cole, Pacific Grove, CA, Second edition, 2002.
    [QTOL] G. Korienek, T. Wrensch, D. Dechow. Squeak: A Quick Trip To ObjectLand.. Addison-Wesley, Boston, MA, 2002.

Return Home