Introduction Summary References
CONTAINER CLASSES
Muhammad Adil Raja
Roaming Researchers, Inc.
cbna
April 21, 2015
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
OUTLINE I
INTRODUCTION
SUMMARY
REFERENCES
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
INTRODUCTION
We will examine how object-oriented programming
techniques can be applied to the problem of creating
container, or collection classes.
Containers in Dynamically Typed Languages.
The Tension between Reuse and Strong Typing.
Object Oriented Solutions.
Substitution and Downcasting.
Substitution and Overriding.
Templates.
Collection Traversals.
Iterators.
Visitors.
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
CONTAINERS IN DYNAMICALLY TYPED LANGUAGES
Collection classes are simple to write in dynamically typed
languages, Since all variables are polymorphic.
Contains simply hold values in variables (which can hold
anything), and when they are removed from the container
they can be assigned to any variable.
Dynamically typed languages have historically come with a
rich set of container classes in their standard library.
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
TENSION BETWEEN STRONG TYPING AND REUSE
The situation is very different when we move to statically
typed languages.
There, the strong typing can get in the way of software
reuse.
THE TENSION
lstsetlanguage=C++
type
Link = Record
value : integer
nextelement : ^ Link
end ;
What happens when we need a linked list of doubles? or of
a user defined type?
The strong typing is getting in the way of software reuse.
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
CAN OO TECHNIQUES SOLVE THIS?
Can we bring any of the OO techniques (subsitution,
polymorphism) into the solution of this problem? We
examine three techniques:
Using Substitution and Downcasting.
Using Substitution and Overriding.
Using Templates (or Generics).
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
USING SUBSTITUTION AND DOWNCASTING
In Java and other languages, (almost) all values can be
stored in a variable of type Object.
Therefore, we write containers that store Object values.
Problem. Requires a cast when a value is removed from
the container.
SUBSTITUTION
Vector aVector = new Vector ( ) ;
Cat Felice = new Cat ( ) ;
aVector . addElement ( Felice ) ;
. . .
/ / cast used to convert Object value to Cat
Cat animal = ( Cat ) aVector . elementAt ( 0 ) ;
Worse problem, typing errors are detected when a value is
removed from the collection, not when it is inserted.
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
HETEROGENEOUS COLLECTIONS
Because any value can be stored in an Object, this allows
heterogeneous collections; although the actual type must
be checked when a value is removed:
EXAMPLE
Stack stk = new Stack ( ) ;
stk . addElement (new Cat ( ) ) ;
stk . addElement (new Dog ( ) ) ;
/ / . . . adding more values
/ / now do something with Cat values
i f ( stk . peek ( ) instanceof Cat ) {
/ / do conversion to Cat
Cat aCat = ( Cat ) stk . pop ( ) ;
/ / . . also do something with cat values
/ / now do something with Dog values
} else i f ( stk . peek ( ) instanceof Dog) {
/ / do conversion to Dog
Dog aDog = (Dog) stk . pop ( ) ;
/ / . . do something with Dog value
}
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
USING CLASSES AS OBJECTS TO DO TYPE CHECKING
In languages in which classes are objects, and have the
ability to tell if an object is an instance, the container can
hold the class object that represents its type:
EXAMPLE
var
stack : TStack ;
aCat : TCat ;
aDog : TDog ;
begin
/ / create a stack that can hold only TCat values
stack := TStack . Create ( TCat ) ;
stack . push ( aCat ) ; / / ok
stack . push (aDog ) ; / / w i l l raise exception
. . .
end
Allows typing errors to be caught on insertion, but uses more
space and time.
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
STRONG PRIMITIVE VALUES
In some languages (Java, Delphi) primitive types are not
objects.
These values cannot be stored using this scheme.
Thus, languages introduce wrapper classes that do
nothing but hold a primitive value.
EXAMPLE
Vector aVector = new Vector ( ) ;
aVector . add (new Integer ( 1 7 ) ) ; / / wrap up p r i m i t i v e i n t as Integer
. . .
Integer a = aVector . elementAt ( 1 ) ;
int x = a . intValue ( ) ; / / must subsequently be unwrapped
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
USING SUBSTITUTION AND OVERRIDING
In certain situations we can eliminate the downcast,
replacing it with overriding.
This only works, however, if you can predict ahead of time
what operations you want to do on a collection.
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
AN EXAMPLE, JAVA WINDOW EVENTS
A good example is the way that window events are handled
in Java.
Each window maintains a list of listeners, each listener
must implement a fixed interface (WindowListener).
EXAMPLE
public class CloseQuit extends WindowAdapter {
/ / execute when the user c l i c k s in the close box
public void windowClosing ( WindowEvent e ) {
System . e x i t ( 0 ) ; / / h a l t the program
}
}
When an event occurs the window simply runs down the list of
listener, invoking the appropriate method in each. No
downcasting required.
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
A THIRD ALTERNATIVE – GENERICS
CODE
template <class T> class L i s t {
public :
void addElement (T newValue ) ;
T firstElement ( ) ;
private :
Link ∗ f i r s t L i n k ;
private class Link { / / nested class
public :
T value ;
Link ∗ nextLink ;
Link (T v , Link ∗ n ) : value ( v ) , nextLink ( n ) { }
} ;
} ;
Allow for both strong typing and reuse.
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
COLLECTION TRAVERSAL
Here is another difficult problem.
How do you allow access to elements of a collection
without exposing the internal structure?
Consider the conventional solution:
EXAMPLE
var
aList : L i s t ; (∗ the l i s t being manipulated ∗)
p : Link ; (∗ a pointer for the loop ∗)
begin
. . .
p := aList . f i r s t L i n k ;
while ( p <> n i l ) do begin
w r i t e l n ( p . value ) ;
p := p ^ . nextElement ;
end ;
Needed to expose the link type, and the field nextElement.
Can we avoid this problem?
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
There are two common solutions:
Create an iterator; an object that facilitates access to
elements and enumeration over the collection.
The vistor. Bundle the action to be performed as an object,
and pass it to the collection.
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
ITERATOR
An iterator is an object that has two major responsibilities:
Provide access to the current element.
Provide a way to move to the next element.
Different languages use different interfaces, but the basic
idea is the same.
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
AN ENUMERATION LOOP IN JAVA
EXAMPLE
/ / create the i t e r a t o r object
Enumeration e = aList . elements ( ) ;
/ / then do the loop
while ( e . hasMoreElements ( ) ) {
Object obj = e . nextElement ( ) ;
/ / . . . do something with obj
}
Interface consists of two methods, hasMoreElements and
nextElement.
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
AN ITERATION LOOP IN C++
EXAMPLE
/ / create s t a r t i n g and stopping i t e r a t o r s
l i s t : : i t e r a t o r s t a r t = aList . begin ( ) ;
l i s t : : i t e r a t o r stop = aList . end ( ) ;
/ / then do the loop
for ( ; s t a r t != stop ; s t a r t ++ ) {
s t r i n g value = ∗ s t a r t ; / / get the value
/ / . . . do something with the value
}
Interface consists of three operations; comparison, increment,
and dereference.
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
ITERATORS AND ENCAPSULATION
Note that the iterator must almost always have detailed
knowledge of the internal data structure.
Wasn’t our goal to hide these details?
Not exactly.
The iterator is usually developed by the same programmer
creating the data structure.
It can share detailed knowledge with the data structure.
And using the iterator does not require any knowledge of
how the iterator is implemented.
Often friends (in C++) or nested classes (in Java) can be
used to help the iterator share information with the
container.
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
ALTERNATIVE, THE VISITOR
An alternative to iterators is the idea of a visitor.
Requires the ability to bundle the action to be performed
into an object, and hand it to the collection.
This is most common technique used in Smalltalk.
aList do: [:x | (’element is’ + x) print ].
The block is passed as argument to the list, which turns
around and executes the block on each element.
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
THE VISITOR IN C++ IN THE STL
EXAMPLE
class printingObject {
public :
void operator ( ) ( int x )
{
cout << " value i s " << x << endl ;
}
} ;
printingObject p r i n t e r ; / / create an instance of the function object
for_each ( aList . begin ( ) , aList . end ( ) , p r i n t e r ) ;
The function for_each passes the object to element element in
the collection.
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
SUMMARY
Collection Classes are easy to write in dynamically typed
languages.
In statically typed languages, there is a conflict between
reuse and strong typing.
Three approaches to overcoming this include.
Using substitution and downcasting.
Using substitution and overriding.
Using generics.
A related problem, looping over elements.
The iterator solution.
The visitor solution.
Container Classes Roaming Researchers, Inc. cbna
Introduction Summary References
REFERENCES
Images and content for developing these slides have been
taken from the follwoing book with the permission of the
author.
An Introduction to Object Oriented Programming, Timothy
Budd.
This presentation is developed with Beamer:
Szeged, dove.
Container Classes Roaming Researchers, Inc. cbna

Container Classes

  • 1.
    Introduction Summary References CONTAINERCLASSES Muhammad Adil Raja Roaming Researchers, Inc. cbna April 21, 2015 Container Classes Roaming Researchers, Inc. cbna
  • 2.
    Introduction Summary References OUTLINEI INTRODUCTION SUMMARY REFERENCES Container Classes Roaming Researchers, Inc. cbna
  • 3.
    Introduction Summary References INTRODUCTION Wewill examine how object-oriented programming techniques can be applied to the problem of creating container, or collection classes. Containers in Dynamically Typed Languages. The Tension between Reuse and Strong Typing. Object Oriented Solutions. Substitution and Downcasting. Substitution and Overriding. Templates. Collection Traversals. Iterators. Visitors. Container Classes Roaming Researchers, Inc. cbna
  • 4.
    Introduction Summary References CONTAINERSIN DYNAMICALLY TYPED LANGUAGES Collection classes are simple to write in dynamically typed languages, Since all variables are polymorphic. Contains simply hold values in variables (which can hold anything), and when they are removed from the container they can be assigned to any variable. Dynamically typed languages have historically come with a rich set of container classes in their standard library. Container Classes Roaming Researchers, Inc. cbna
  • 5.
    Introduction Summary References TENSIONBETWEEN STRONG TYPING AND REUSE The situation is very different when we move to statically typed languages. There, the strong typing can get in the way of software reuse. THE TENSION lstsetlanguage=C++ type Link = Record value : integer nextelement : ^ Link end ; What happens when we need a linked list of doubles? or of a user defined type? The strong typing is getting in the way of software reuse. Container Classes Roaming Researchers, Inc. cbna
  • 6.
    Introduction Summary References CANOO TECHNIQUES SOLVE THIS? Can we bring any of the OO techniques (subsitution, polymorphism) into the solution of this problem? We examine three techniques: Using Substitution and Downcasting. Using Substitution and Overriding. Using Templates (or Generics). Container Classes Roaming Researchers, Inc. cbna
  • 7.
    Introduction Summary References USINGSUBSTITUTION AND DOWNCASTING In Java and other languages, (almost) all values can be stored in a variable of type Object. Therefore, we write containers that store Object values. Problem. Requires a cast when a value is removed from the container. SUBSTITUTION Vector aVector = new Vector ( ) ; Cat Felice = new Cat ( ) ; aVector . addElement ( Felice ) ; . . . / / cast used to convert Object value to Cat Cat animal = ( Cat ) aVector . elementAt ( 0 ) ; Worse problem, typing errors are detected when a value is removed from the collection, not when it is inserted. Container Classes Roaming Researchers, Inc. cbna
  • 8.
    Introduction Summary References HETEROGENEOUSCOLLECTIONS Because any value can be stored in an Object, this allows heterogeneous collections; although the actual type must be checked when a value is removed: EXAMPLE Stack stk = new Stack ( ) ; stk . addElement (new Cat ( ) ) ; stk . addElement (new Dog ( ) ) ; / / . . . adding more values / / now do something with Cat values i f ( stk . peek ( ) instanceof Cat ) { / / do conversion to Cat Cat aCat = ( Cat ) stk . pop ( ) ; / / . . also do something with cat values / / now do something with Dog values } else i f ( stk . peek ( ) instanceof Dog) { / / do conversion to Dog Dog aDog = (Dog) stk . pop ( ) ; / / . . do something with Dog value } Container Classes Roaming Researchers, Inc. cbna
  • 9.
    Introduction Summary References USINGCLASSES AS OBJECTS TO DO TYPE CHECKING In languages in which classes are objects, and have the ability to tell if an object is an instance, the container can hold the class object that represents its type: EXAMPLE var stack : TStack ; aCat : TCat ; aDog : TDog ; begin / / create a stack that can hold only TCat values stack := TStack . Create ( TCat ) ; stack . push ( aCat ) ; / / ok stack . push (aDog ) ; / / w i l l raise exception . . . end Allows typing errors to be caught on insertion, but uses more space and time. Container Classes Roaming Researchers, Inc. cbna
  • 10.
    Introduction Summary References STRONGPRIMITIVE VALUES In some languages (Java, Delphi) primitive types are not objects. These values cannot be stored using this scheme. Thus, languages introduce wrapper classes that do nothing but hold a primitive value. EXAMPLE Vector aVector = new Vector ( ) ; aVector . add (new Integer ( 1 7 ) ) ; / / wrap up p r i m i t i v e i n t as Integer . . . Integer a = aVector . elementAt ( 1 ) ; int x = a . intValue ( ) ; / / must subsequently be unwrapped Container Classes Roaming Researchers, Inc. cbna
  • 11.
    Introduction Summary References USINGSUBSTITUTION AND OVERRIDING In certain situations we can eliminate the downcast, replacing it with overriding. This only works, however, if you can predict ahead of time what operations you want to do on a collection. Container Classes Roaming Researchers, Inc. cbna
  • 12.
    Introduction Summary References ANEXAMPLE, JAVA WINDOW EVENTS A good example is the way that window events are handled in Java. Each window maintains a list of listeners, each listener must implement a fixed interface (WindowListener). EXAMPLE public class CloseQuit extends WindowAdapter { / / execute when the user c l i c k s in the close box public void windowClosing ( WindowEvent e ) { System . e x i t ( 0 ) ; / / h a l t the program } } When an event occurs the window simply runs down the list of listener, invoking the appropriate method in each. No downcasting required. Container Classes Roaming Researchers, Inc. cbna
  • 13.
    Introduction Summary References ATHIRD ALTERNATIVE – GENERICS CODE template <class T> class L i s t { public : void addElement (T newValue ) ; T firstElement ( ) ; private : Link ∗ f i r s t L i n k ; private class Link { / / nested class public : T value ; Link ∗ nextLink ; Link (T v , Link ∗ n ) : value ( v ) , nextLink ( n ) { } } ; } ; Allow for both strong typing and reuse. Container Classes Roaming Researchers, Inc. cbna
  • 14.
    Introduction Summary References COLLECTIONTRAVERSAL Here is another difficult problem. How do you allow access to elements of a collection without exposing the internal structure? Consider the conventional solution: EXAMPLE var aList : L i s t ; (∗ the l i s t being manipulated ∗) p : Link ; (∗ a pointer for the loop ∗) begin . . . p := aList . f i r s t L i n k ; while ( p <> n i l ) do begin w r i t e l n ( p . value ) ; p := p ^ . nextElement ; end ; Needed to expose the link type, and the field nextElement. Can we avoid this problem? Container Classes Roaming Researchers, Inc. cbna
  • 15.
    Introduction Summary References Thereare two common solutions: Create an iterator; an object that facilitates access to elements and enumeration over the collection. The vistor. Bundle the action to be performed as an object, and pass it to the collection. Container Classes Roaming Researchers, Inc. cbna
  • 16.
    Introduction Summary References ITERATOR Aniterator is an object that has two major responsibilities: Provide access to the current element. Provide a way to move to the next element. Different languages use different interfaces, but the basic idea is the same. Container Classes Roaming Researchers, Inc. cbna
  • 17.
    Introduction Summary References ANENUMERATION LOOP IN JAVA EXAMPLE / / create the i t e r a t o r object Enumeration e = aList . elements ( ) ; / / then do the loop while ( e . hasMoreElements ( ) ) { Object obj = e . nextElement ( ) ; / / . . . do something with obj } Interface consists of two methods, hasMoreElements and nextElement. Container Classes Roaming Researchers, Inc. cbna
  • 18.
    Introduction Summary References ANITERATION LOOP IN C++ EXAMPLE / / create s t a r t i n g and stopping i t e r a t o r s l i s t : : i t e r a t o r s t a r t = aList . begin ( ) ; l i s t : : i t e r a t o r stop = aList . end ( ) ; / / then do the loop for ( ; s t a r t != stop ; s t a r t ++ ) { s t r i n g value = ∗ s t a r t ; / / get the value / / . . . do something with the value } Interface consists of three operations; comparison, increment, and dereference. Container Classes Roaming Researchers, Inc. cbna
  • 19.
    Introduction Summary References ITERATORSAND ENCAPSULATION Note that the iterator must almost always have detailed knowledge of the internal data structure. Wasn’t our goal to hide these details? Not exactly. The iterator is usually developed by the same programmer creating the data structure. It can share detailed knowledge with the data structure. And using the iterator does not require any knowledge of how the iterator is implemented. Often friends (in C++) or nested classes (in Java) can be used to help the iterator share information with the container. Container Classes Roaming Researchers, Inc. cbna
  • 20.
    Introduction Summary References ALTERNATIVE,THE VISITOR An alternative to iterators is the idea of a visitor. Requires the ability to bundle the action to be performed into an object, and hand it to the collection. This is most common technique used in Smalltalk. aList do: [:x | (’element is’ + x) print ]. The block is passed as argument to the list, which turns around and executes the block on each element. Container Classes Roaming Researchers, Inc. cbna
  • 21.
    Introduction Summary References THEVISITOR IN C++ IN THE STL EXAMPLE class printingObject { public : void operator ( ) ( int x ) { cout << " value i s " << x << endl ; } } ; printingObject p r i n t e r ; / / create an instance of the function object for_each ( aList . begin ( ) , aList . end ( ) , p r i n t e r ) ; The function for_each passes the object to element element in the collection. Container Classes Roaming Researchers, Inc. cbna
  • 22.
    Introduction Summary References SUMMARY CollectionClasses are easy to write in dynamically typed languages. In statically typed languages, there is a conflict between reuse and strong typing. Three approaches to overcoming this include. Using substitution and downcasting. Using substitution and overriding. Using generics. A related problem, looping over elements. The iterator solution. The visitor solution. Container Classes Roaming Researchers, Inc. cbna
  • 23.
    Introduction Summary References REFERENCES Imagesand content for developing these slides have been taken from the follwoing book with the permission of the author. An Introduction to Object Oriented Programming, Timothy Budd. This presentation is developed with Beamer: Szeged, dove. Container Classes Roaming Researchers, Inc. cbna