Container Classes

23
Introduction Summary References C ONTAINER C LASSES Muhammad Adil Raja Roaming Researchers, Inc. cbna April 21, 2015 Container Classes Roaming Researchers, Inc. cbna

Transcript of Container Classes

Page 1: Container Classes

Introduction Summary References

CONTAINER CLASSES

Muhammad Adil Raja

Roaming Researchers, Inc.

cbna

April 21, 2015

Container Classes Roaming Researchers, Inc. cbna

Page 2: Container Classes

Introduction Summary References

OUTLINE I

INTRODUCTION

SUMMARY

REFERENCES

Container Classes Roaming Researchers, Inc. cbna

Page 3: Container Classes

Introduction Summary References

INTRODUCTION

I We will examine how object-oriented programmingtechniques can be applied to the problem of creatingcontainer, or collection classes.

I Containers in Dynamically Typed Languages.I The Tension between Reuse and Strong Typing.I Object Oriented Solutions.

I Substitution and Downcasting.I Substitution and Overriding.I Templates.

I Collection Traversals.I Iterators.I Visitors.

Container Classes Roaming Researchers, Inc. cbna

Page 4: Container Classes

Introduction Summary References

CONTAINERS IN DYNAMICALLY TYPED LANGUAGES

I Collection classes are simple to write in dynamically typedlanguages, Since all variables are polymorphic.

I Contains simply hold values in variables (which can holdanything), and when they are removed from the containerthey can be assigned to any variable.

I Dynamically typed languages have historically come with arich set of container classes in their standard library.

Container Classes Roaming Researchers, Inc. cbna

Page 5: Container Classes

Introduction Summary References

TENSION BETWEEN STRONG TYPING AND REUSE

I The situation is very different when we move to staticallytyped languages.

I There, the strong typing can get in the way of softwarereuse.

THE TENSIONlstsetlanguage=C++

typeLink = Record

value : i n t e g e rnextelement : ^ L ink

end ;

I What happens when we need a linked list of doubles? or ofa user defined type?

I The strong typing is getting in the way of software reuse.

Container Classes Roaming Researchers, Inc. cbna

Page 6: Container Classes

Introduction Summary References

CAN OO TECHNIQUES SOLVE THIS?

I Can we bring any of the OO techniques (subsitution,polymorphism) into the solution of this problem? Weexamine three techniques:

I Using Substitution and Downcasting.I Using Substitution and Overriding.I Using Templates (or Generics).

Container Classes Roaming Researchers, Inc. cbna

Page 7: Container Classes

Introduction Summary References

USING SUBSTITUTION AND DOWNCASTING

I In Java and other languages, (almost) all values can bestored in a variable of type Object.

I Therefore, we write containers that store Object values.I Problem. Requires a cast when a value is removed from

the container.

SUBSTITUTION

Vector aVector = new Vector ( ) ;Cat Fe l i ce = new Cat ( ) ;aVector . addElement ( Fe l i ce ) ;

. . ./ / cast used to conver t Object value to Cat

Cat animal = ( Cat ) aVector . elementAt ( 0 ) ;

Worse problem, typing errors are detected when a value isremoved from the collection, not when it is inserted.

Container Classes Roaming Researchers, Inc. cbna

Page 8: Container Classes

Introduction Summary References

HETEROGENEOUS COLLECTIONS

I Because any value can be stored in an Object, this allowsheterogeneous collections; although the actual type mustbe checked when a value is removed:

EXAMPLE

Stack s tk = new Stack ( ) ;s t k . addElement (new Cat ( ) ) ;s t k . addElement (new Dog ( ) ) ;

/ / . . . adding more values/ / now do something wi th Cat values

i f ( s t k . peek ( ) instanceof Cat ) {/ / do convers ion to Cat

Cat aCat = ( Cat ) s t k . pop ( ) ;/ / . . a lso do something wi th cat values/ / now do something wi th Dog values

} else i f ( s t k . peek ( ) instanceof Dog) {/ / do convers ion to Dog

Dog aDog = (Dog) s tk . pop ( ) ;/ / . . do something wi th Dog value

}

Container Classes Roaming Researchers, Inc. cbna

Page 9: Container Classes

Introduction Summary References

USING CLASSES AS OBJECTS TO DO TYPE CHECKINGI In languages in which classes are objects, and have the

ability to tell if an object is an instance, the container canhold the class object that represents its type:

EXAMPLE

varstack : TStack ;aCat : TCat ;aDog : TDog ;

begin/ / c reate a stack t h a t can hold only TCat values

stack := TStack . Create ( TCat ) ;s tack . push ( aCat ) ; / / okstack . push (aDog ) ; / / w i l l r a i se except ion. . .

end

Allows typing errors to be caught on insertion, but uses morespace and time.

Container Classes Roaming Researchers, Inc. cbna

Page 10: Container Classes

Introduction Summary References

STRONG PRIMITIVE VALUES

I In some languages (Java, Delphi) primitive types are notobjects.

I These values cannot be stored using this scheme.I Thus, languages introduce wrapper classes that do

nothing but hold a primitive value.

EXAMPLE

Vector aVector = new Vector ( ) ;aVector . add (new I n t ege r ( 1 7 ) ) ; / / wrap up p r i m i t i v e i n t as In tege r. . .I n t ege r a = aVector . elementAt ( 1 ) ;i n t x = a . i n tVa lue ( ) ; / / must subsequent ly be unwrapped

Container Classes Roaming Researchers, Inc. cbna

Page 11: Container Classes

Introduction Summary References

USING SUBSTITUTION AND OVERRIDING

I In certain situations we can eliminate the downcast,replacing it with overriding.

I This only works, however, if you can predict ahead of timewhat operations you want to do on a collection.

Container Classes Roaming Researchers, Inc. cbna

Page 12: Container Classes

Introduction Summary References

AN EXAMPLE, JAVA WINDOW EVENTS

I A good example is the way that window events are handledin Java.

I Each window maintains a list of listeners, each listenermust implement a fixed interface (WindowListener).

EXAMPLE

public class CloseQuit extends WindowAdapter {/ / execute when the user c l i c k s i n the c lose 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 oflistener, invoking the appropriate method in each. Nodowncasting required.

Container Classes Roaming Researchers, Inc. cbna

Page 13: Container Classes

Introduction Summary References

A THIRD ALTERNATIVE – GENERICS

CODE

template <class T> class L i s t {public :

void addElement (T newValue ) ;T f i r s t E l e m e n t ( ) ;

private :L ink ∗ f i r s t L i n k ;

private class Link { / / nested c lasspublic :

T value ;L ink ∗ nextL ink ;

L ink (T v , L ink ∗ n ) : value ( v ) , nex tL ink ( n ) { }} ;

} ;

Allow for both strong typing and reuse.

Container Classes Roaming Researchers, Inc. cbna

Page 14: Container Classes

Introduction Summary References

COLLECTION TRAVERSALI Here is another difficult problem.I How do you allow access to elements of a collection

without exposing the internal structure?I Consider the conventional solution:

EXAMPLE

vara L i s t : L i s t ; (∗ the l i s t being manipulated ∗)p : L ink ; (∗ a p o i n t e r for the loop ∗)

begin. . .p := a L i s t . 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 ;

I Needed to expose the link type, and the field nextElement.I Can we avoid this problem?

Container Classes Roaming Researchers, Inc. cbna

Page 15: Container Classes

Introduction Summary References

There are two common solutions:I Create an iterator; an object that facilitates access to

elements and enumeration over the collection.I The vistor. Bundle the action to be performed as an object,

and pass it to the collection.

Container Classes Roaming Researchers, Inc. cbna

Page 16: Container Classes

Introduction Summary References

ITERATOR

I An iterator is an object that has two major responsibilities:I Provide access to the current element.I Provide a way to move to the next element.I Different languages use different interfaces, but the basic

idea is the same.

Container Classes Roaming Researchers, Inc. cbna

Page 17: Container Classes

Introduction Summary References

AN ENUMERATION LOOP IN JAVA

EXAMPLE

/ / c rea te the i t e r a t o r ob jec tEnumeration e = a L i s t . elements ( ) ;

/ / then do the loopwhile ( e . hasMoreElements ( ) ) {

Object ob j = e . nextElement ( ) ;/ / . . . do something wi th ob j

}

Interface consists of two methods, hasMoreElements andnextElement.

Container Classes Roaming Researchers, Inc. cbna

Page 18: Container Classes

Introduction Summary References

AN ITERATION LOOP IN C++

EXAMPLE

/ / c rea te s t a r t i n g and stopping i t e r a t o r sl i s t : : i t e r a t o r s t a r t = a L i s t . begin ( ) ;l i s t : : i t e r a t o r stop = a L i s t . end ( ) ;

/ / then do the loopfor ( ; 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 wi th the value

}

Interface consists of three operations; comparison, increment,and dereference.

Container Classes Roaming Researchers, Inc. cbna

Page 19: Container Classes

Introduction Summary References

ITERATORS AND ENCAPSULATION

I Note that the iterator must almost always have detailedknowledge of the internal data structure.

I Wasn’t our goal to hide these details?I Not exactly.I The iterator is usually developed by the same programmer

creating the data structure.I It can share detailed knowledge with the data structure.I And using the iterator does not require any knowledge of

how the iterator is implemented.I Often friends (in C++) or nested classes (in Java) can be

used to help the iterator share information with thecontainer.

Container Classes Roaming Researchers, Inc. cbna

Page 20: Container Classes

Introduction Summary References

ALTERNATIVE, THE VISITOR

I An alternative to iterators is the idea of a visitor.I Requires the ability to bundle the action to be performed

into an object, and hand it to the collection.I This is most common technique used in Smalltalk.I aList do: [:x | (’element is’ + x) print ].I 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

Page 21: Container Classes

Introduction Summary References

THE VISITOR IN C++ IN THE STL

EXAMPLE

class p r i n t i n g O b j e c t {public :

void operator ( ) ( i n t x ){

cout << " value i s " << x << endl ;}

} ;

p r i n t i n g O b j e c t p r i n t e r ; / / c reate an ins tance of the f u n c t i o n ob jec t

for_each ( a L i s t . begin ( ) , a L i s t . end ( ) , p r i n t e r ) ;

The function for_each passes the object to element element inthe collection.

Container Classes Roaming Researchers, Inc. cbna

Page 22: Container Classes

Introduction Summary References

SUMMARY

I Collection Classes are easy to write in dynamically typedlanguages.

I In statically typed languages, there is a conflict betweenreuse and strong typing.

I Three approaches to overcoming this include.I Using substitution and downcasting.I Using substitution and overriding.I Using generics.I A related problem, looping over elements.I The iterator solution.I The visitor solution.

Container Classes Roaming Researchers, Inc. cbna

Page 23: Container Classes

Introduction Summary References

REFERENCES

I Images and content for developing these slides have beentaken from the follwoing book with the permission of theauthor.

I An Introduction to Object Oriented Programming, TimothyBudd.

I This presentation is developed with Beamer:I Szeged, dove.

Container Classes Roaming Researchers, Inc. cbna