Full text
Bridging the Gap Between Design and Implementation of Comp onent Libraries Jordi Marco and Xavier Franch Dept. Llenguatges i Sistemes Informatics, Universitat Politecnica de Catalunya, c/ Jordi Girona 1{3 (Campus Nord, C6) E{08034 Barcelona, (Catalunya, Spain) f jmarco,franch g @lsi.upc.es Abstract. Ob ject{oriented design is usually driven by three main reusability principles: step{by{step design, design for reuse and design with reuse. However, these principles are just partially applied to the subsequent ob ject{oriented implementation, often due to eciency constraints, yielding to a gap b etween design and implementation. In this pap er weprovide a solution for bridging this gap for a concrete framework, the one of designing and implementing container{li ke comp onent libraries, such as STL, Bo o ch Comp onents, etc. Our approach is based on a new design pattern together with its corresp onding implementation . The prop osal enhances the same principles that drive the design pro cess: step{ by{step implementation (adding just what is needed in every step), implementation with reuse (comp onent implementations are reused while library implementation progresses and comp onent hierarchies grow) and implementation for reuse (intermediate comp onent implementations can b e reused in many dierentpoints of the hierarchy). We use our approach in two dierent manners: for building a brand{new container{like comp onent library, and for reengineering an existing one, Bo o chComponents in Ada95. 1 Motivation Since McIlroy prop osed in 1969 the notion of software catalogue McI69], comp onent{based software development (CBSD) has b ecome without any doubt one of the most imp ortant software development paradigms. The key p oint b ehind this paradigm is the pro cess of reusing comp onents from standard software catalogues. Comp onent reuse provides manyadvantages, remarkably software production hastening, software qualityimprovementand software maintenance cost decrease. One of the most valuable contributions in CBSD is ob ject{oriented (OO) technology. Basic concepts such as inheritance, p olymorphism and dynamic binding, and others built on top of them, such as design patterns GHJ+96], had a strong impact on this paradigm. In fact, as Meyer remarks Mey97], OO technology makes p ossible, for the rst time, the idea of turning academic McIlroy's vision of software developmentinto a comp onent{based industry b ecome real.
2 Unfortunately, despite of this ongoing success, wehave not still reached the ultimate McIlroy's goal: making software comp onents equivalent to other engineering comp onenttyp es, as chips, bricks and valves. One of the reasons b ehind this fact has to b e with the diculty of turning designs into implementations. The OO design pro cess is usually driven by three main reusability principles, namely step{by{step design, design for reuse and design with reuse. However, these principles are often just partially applied to the subsequent OO implementation. Therefore, a gap b etween design and implementation app ears with resp ect to these reusability principles. This fact holds even if advanced OO concepts such as design patterns are used during development: it is not enough to reuse design patterns, a go o d reuse p olicy must provide implementations of them. But weturn backtoMcIlroy's software catalogues, more sp ecically to the OO corresp onding notion of class comp onent library. Class comp onent libraries help to dismiss the gap mentioned ab ove b ecause classes implemented in the library come to light naturally when identifying classes in the new design. Hence, a go o d design and implementation of these library classes b ecome crucial to supp ort the reusability of the comp onents stored therein. But design and implementation of reusable, general{purp ose class libraries is a hard work, b ecause many criteria haveto be taken into account: { Adaptability. Design and implementation of general{purp ose libraries have to b e exible and extensible to allow the p ossibility to adapt them or to extend them to a particular context. { Reusability. General{purp ose libraries should deal with as many dierent contexts as p ossible. Therefore it is utterly imp ortantto avoid assumptions ab out (and dep endencies on) the context, which could limit the usabilityof the library and hence its applicability and eectiveness. { Functionality. The success of general{purp ose libraries dep ends on its ability to provide the most common functionalities in the domain in whichthey are dened. { Eciency. Classes in the library should incorp orate algorithms and features to fulll usual eciency requirements. Reconciling these criteria is a dicult task. At the design level, it is p ossible to dene a class hierarchy satisfying the rst three criteria. But when building its implementation, eciency requirements collide often with the others, making design decisions dicult to b e kept. This makes the gap b etween design and implementation to app ear again, now in the development of the library itself. Thus, reusability can b e damaged again, b oth when building the library (common functionalities are implemented more than once in dierent classes) and when using it (b ecause library adaptability, reusability or functionalitymay have b een partially sacriced). The gap maytake dierent forms in dierenttyp es of libraries. In this pap er we fo cus on a concrete category of libraries, the one of container{likecomponent libraries ( CLC{library for short). Containers are ob jects that store collections
3 of other ob jects dierenttyp es of containers may oer dierent functionalities, and their implementations (usually, more than one) will satisfy dierente- ciency requirements. Some representative CLC{libraries are the Standard Template Library (STL) MS96], the Library of EcientDatatyp es and Algorithms (LEDA) MN99] and Bo o ch Comp onents (BC) BV90,BWW99]. In these kind of libraries a well{established hierarchyofcomponents can b e found at the design level. Sometimes, this hierarchy app ears explicitly (for instance BC) and sometimes not (for instance, STL and LEDA). In anycase, the hierarchy has no subsequent implementation in these libraries, making thus the gap app ear again. Typically, three dierent situations exist: { The implementation of the intermediate levels of hierarchyonlyprovides interfaces, but not real implementations. In other words, the hierarchy implementation just preserves the layout. Co de reuse do es not takes place, but eciency is optimal, b ecause metho ds can use the private attributes of class implementation. { The intermediate levels simply disapp ear, mayb e b ecause it can b e argued that non{implemented interfaces are useless from an implementation p oint of view. Again, eciency is the main motivation b ehind this approach. Examples of these libraries are STL and LEDA. { The hierarchy is partially preserved in the implementation, with those mo d- ications required to supp ort co de reuse. This solution usually dismisses the level of adaptability and reusabilit y of the library. The Ada95 version of the BC is a representative library in this scenario. The purp ose of this work is bridging this gap b etween the design and the implementation of CLC{libraries. Our approach is based in the denition of a new design pattern, namely Shortcut , together with its corresp onding implementation. This pattern describ es and solves the problem of accessing ob jects stored in a container, in an abstract and ecientway. Most of the existing CLC{ libraries try to solve this problem by means of dierent ad{hoc , implementation{ dep endent prop osals. Instead, we use an implementation{free approach based on the use of shortcuts to implement a generic container in which the ob jects are really stored. Our approach yields to the same reusability principles in the implementation pro cess that we had in design: step{by{step implementation (co ding just what has b een intro duced or redened in every class), implementation with reuse (class{implementations are reused while the implementation stage progresses and class{hierarchies grow) and implementation for reuse (intermediate class implementations can b e reused in many dierent p oints of the hierarchy). Our prop osal is twofold in the sense that it can b e applied b oth for developing new CLC{libraries and for improving existing ones, b ecause the core data structures and algorithms can b e reused. In the case of reengineering an existing library, since the addition of shortcuts will not aect the former b ehaviour of the library, those running software applications that use the previous version of the library do es not need to b e mo died. We will show this p oint in a particular case, the Ada95 BC library.
4 The rest of the pap er is organized as follows. First, wemake a comparative analysis of the three CLC{libraries mentioned ab ove highlighting their b enets and drawbacks. Next, we prop ose a hierarchy and a design pattern aimed at solving these drawbacks. Last, we apply the design pattern to a particular case study, the Ada95 BC library. 2 Some Representative Implementations for CLCL In this section we analyse three of the most widely used CLC{libraries: the Standard Template Library (STL), the Bo o ch Comp onents (BC) and the Library of Ecient Data typ es and Algorithms (LEDA). For each of them we fo cus only on the containers subhierarchy (together with their capabilities, e.g. iterators). 2.1 The Standard Template Library STL is a comp onent library adopted by ANSI as a standard for C++. This library has b een an imp ortantcontribution to the programming metho dology. STL has not an explicit hierarchy, only the leaf classes exist, but there is an implicit hierarchy that can b e deduced from its organisation. STL is organised in six kinds of comp onents: containers, generic algorithms, iterators, function ob jects, adaptors and allo cators. We are going to analyse containers, iterators and containers adaptors comp onents. Containers are divided into two categories: sequence containers and sorted asso ciativecontainers. There are three dierent sequence containers abstractions: vectors, deques and lists with a single one implementation. Using the containers adaptors: stack, queue, and priority queue together with the sequence containers can b e obtained three dierent implementations for each one of these adaptors. Therefore, we can say that STL has six dierent sequence con tainers abstractions: vectors, deques, lists, stacks, queues, and priority queues, with one implementation of the rst three ones and three dierent implementations of the three last ones. The asso ciative containers category oers four dierentcontainers abstractions: sets, multisets, maps and multimaps each of them with just one implementation. All the containers provide: { Iterators. Iterators are ob jects that allowto navigate through all the ob jects stored in a container. Iterators are divided in ve categories: input iterators, ouput iterators, forward iterators, bidirectional iterators and random acces iterators among which there is the hierarchical relationship shown in Fig. 1. Only vectors and deques provide random access iterators the other containers provide just bidirectional ones. In STL, iterators mix two dierent capabilities, namely, the concept of iterator and the concept of lo cation of the ob jects stored in the container. This mixture of concerns provokes some drawbacks that we mention further on the pap er.
5 Input Output Forward Bidirec tional Random access ==, !=, ++ * (lookup) ==, !=, ++ * (lookup, modification) -- +=, -= +, - <, >, <=, >= Fig. 1. Hierarchy of the STL iterators { Insert op erations. There are a variety of insert op erations to insert one or more ob jects. The common one is the basic insert op eration which consists in inserting one ob ject this op eration returns an iterator that can b e used like a reference to the new ob ject. { Remove op erations. All the remove op erations use iterators to removethe ob ject b ound to them. The common one removes one ob ject using its iterator. { Mo dify op erations. In STL, the mo dication of an ob ject stored in a container has to b e made using iterators likepointers. The problem with this scheme is that iterators are not p ersistent, in other words an iterator could refer not to the original ob ject but to other one (typically when ob jects can b e reallo cated inside the structure or when they are removed) the problem is serious b ecause STL do es not provide any functionalitytocheckthis situation. { Ecient access op erations. In STL, ecient access to ob jects stored in a container is made by using iterators like p ointers. Therefore, the problem mentioned ab ove app ears again. This library have a lotofadvantages, mainly: { Oers a large amount of robust, ecient and well{designed comp onents with appropriate algorithms and data structures.
6 { The algorithms are structured indep endent, they work externally using the iterator common facility. { For many ecient data structures access by p osition is imp ortant. STL uses iterator concept to cast p ositions into an abstract form. { It is a standard library supp orted bydocumentation and b o oks. { It is freeware. The main drawbacks that present this library are: { Lackofinternal level of reusability. All the common capabilities havetobe implemented on each concrete class. { Eachcontainer abstraction (b esides the abstractions obtained using adaptors: queue, stack and priority queue) has just a single implementation. The implementation of List is a double linked list, the asso ciative sorted containers are implemented using a red{black tree, etc. This makes dicult the p ossibility of adapting the library for concrete prop osals (e.g. if a hashing map is needed to haveeven more ecient access bykey). { It is dicult to extend it. If wewanttoaddacontainer comp onent, it has to oer all the common capabilities but some of them restrict the p ossible implementations (e.g. we cannot add a new container whose ob jects change their p osition in the internal structure when a new ob ject is inserted) and others dicult to understand and implementing. { Non p ersistency of iterators. In some containers classes all the iterators are invalidated when we remove or insert an ob ject. And in the others an iterator could b e invalid if the ob ject that it referred has b een removed. { Lack of an op eration to kno w if an iterator is still valid or not. 2.2 The Booch Comp onents The Bo o chComponents was rst created for Ada 83 Bo o87] and reengineered rst for C++ BV90] and later on for Ada 95 BWW99]. We are going to analise in detail the Ada 95 version, which is later used in the pap er to show the feasibility of our approach. This version of the Bo o chcomponents is organised into three main sup er{ classes: Containers , Support and Graphs ,whichhave a common parent{class BC . The base class BC has no functionality at all, it only provides the denition of the common exceptions. The Containers category of classes provides a wide range of structural abstractions (lists, bags, sets, collections, etc.) using many widespread implementation techniques (chaining, hashing, search trees and so on). Figure 2 shows the main hierarchy of these comp onents their co de is available at BWW99]. The Containers class oers only the interface of the iterators. The structural abstraction classes oers the interface of these abstractions and, in an intent of reuse implementation, the implementation of the iterators, we can see later that this intentprovokes several drawbacks. Finally, in the leaf classes of the hierarchywe can nd the implementation of the concrete container. The unique common op eration of these containers is the add op eration. This library oers several advantages that makeit very useful, mainly:
7 B C G raph s C ontainer s L ist s S et s S tack s Q ueue s M ap s C ollection s B ag s T ree s R ing s B ounde d U nbounded D inami c S uppo rt B ounde d U nbounded D inami c N ode s Fig. 2. HierarchyoftheBooch comp onent classes (excerpt) { A large amount of robust and well{designed comp onents with appropriate algorithms and data structures. { It is a well{known library supp orted by do cumentation and b o oks. { It is freeware. { It has several and complete testing packages for its comp onents. The container category of this libray presents some drawbacks that decrease the p otential of reusability of this comp onent library. Most of the problems arise b ecause some parent{classes dep end on the concrete implementation of their children{classes. To make it clear, Fig. 3 shows a typical situation in this library,in which the BC.Containers.Bags class dep ends on the concrete form of its children classes Bounded , Unbounded and Dynamic , which are hashing tables. Notice that the typ e denition of Bag Iterator forces all the Bags children to b e implemented by means of a hashing table. This restriction interferes with the p ossibility of extending the class hierarchyorchanging the concrete form of one of its children. All these dep endencies exist b ecause iterators are strongly dep endent on the concrete container implementation. Similar dep endencies can b e also found b etween the classes Maps , Sets , Queues , etc., and their resp ective children. Therefore, to solve the problems we clearly need to make iterators indep endent of the sp ecic container. To sum up, the main problems in this library are: { The hierarchy is not robust enough with resp ect to changes in some of their comp onents: changes in a comp onent require the mo dication of other components. This is due to the implementation dep endency mentioned ab ove. For instance, changing the current hashing implementation of the BC.Containers.Bags.Bounded by an implementation (b ounded) with a binary search tree (for instance, b ecause elements must b e obtained in some order), requires changing the implementation of the typ e Bag Iterator (dened in the BC.Containers.Bags class) and the implementation of its op erations as well.
8 generic package BC.Containers.Bags is ... private type Bag is abstract new Container with null record ... type Bag Iterator (B : access Bag'Class) is new Actual Iterator (B) with record Bucket Index : Natural := 0 Index : Natural := 0 end record ... end BC.Containers.Bag Fig. 3. Extract of the generic package BC.Containers.Bags { Moreover, this hierarchy restricts to a single set of p ossible implementations for some of the dierent structure abstractions. This is a serious drawback b ecause some of the implementations provided therein can b e inef- cient in some contexts (wehave already mentioned ordered traversal of Bags ). For instance, it is not p ossible to have dierent implementations of the class BC.Containers.Bags.Bounded , b ecause it is not implementation{ indep endent, and hence it forces a concrete implementation strategy (hashing). This problem could b e solved adding another level in the hierarchy, making the class abstract and dening their concrete children. This is not p ossible without changing other parts of the hierarchy, b ecause of the implementation dep endency again. { Lowlevel of abstraction makes the usage of the implementation harder. This happ ens when dealing with iterators. The iterator typ e and its op erations are strongly dep endent on the concrete implementation of the underlying structure. As a consequence, for every concrete implementation of a children{ class a new Actual Iterator typ e must b e dened and its op erations must be overridden. This approach, which is dierent from many other libraries, prevents the easy usage of the iterator facility. { It is not only the lackof multiple implementations for comp onents that damages eciency, but also some of the iterator op erations have lineal cost in the worst case with resp ect to a certain parameter (although their amortised cost is constant). For instance, as shown in Fig. 4, the Reset op eration could have linear cost with resp ect to the Number of Buckets . A similar problem o ccurs in the Next op eration. { In many contexts in whichcomponents often encapsulate data structures, reusability can b e damaged due to eciency requirements: even if a component fulls a required functionality, the time complexity of its op erations may b e inadequate given the context in which it should b e integrated (either considering them individually or when combining them to build more complex comp onents). The access by means of the op erations oered bya
9 procedure Reset (It : in out Bag Iterator) is begin It.Index := 0 if Cardinality (It.B.all) = 0 then It.Bucket Index := 0 else It.Bucket Index := 1 while It.Bucket Index <= Number Of Buckets (It.B.all) loop if Length (It.B.all, It.Bucket Index) > 0 then It.Index := 1 exit end if It.Bucket Index := It.Bucket Index + 1 end loop end if end Reset Fig. 4. Reset op eration's co de of the generic package BC.Containers.Bags comp onentmay b e costly if the logical layout of the data structure is used if fast access is required, it b ecomes necessary to lo ok up the item using directly a reference to it. 2.3 The Library of EcientData typ es and Algorithms The Library of Ecient Data typ es and Algorithms (LEDA) is the result of a pro ject started in 1988. The goal of this pro ject was design a library of data typ es and algorithms, mainly, for combinatorial computing area where it is necessary the use of complex data typ es. The actual version of this library MN99]oers a large amount of data typ es and algorithms. From a container p oint of view LEDA oers the next generic (parameterised) data typ es: arrays with one and two dimensions, stacks, queues, b ounded stacks, b ounded queues, linear lists, single linked lists, sets, dictionaries, dictionaries with implementation parameter, sorted sequences, sorted sequences with implementation parameter, dictionary arrays, dictionary arrays with implementation parameter, hashing arrays and others variations ab ove containers. All the containers{likedatatyp es of this library provide: { Items. LEDA use an item concept that play the role of lo cations or p ositions in data structures to achieve ecient access to the ob jects therein. { Iteration macros. This macros can b e used similarly to the C++ for statement to iterate over the items of a container. Iteration macros havethe restriction that the ob ject corresp onding to the item can not b e mo died inside the b o dy of the lo op. { Insert op erations. These op erations return an item that can b e used in other op erations whichhave then constanttime.
16 3. Security . The access to the ob jects by means of shortcuts is safe b ecause meaningless access to them is avoided. In particular, the following situations are avoided: dangling shortcuts (references without b ound ob jects) or out{ of{date ones (shortcuts b ound to ob jects which are not the original ones). 4. Improving existing CLC{libraries . As the addition of shortcuts to a concrete container do es not mo dify its functional b ehaviour, preservation of b ehaviour supp orts b oth the reengineering pro cess of existing CLC{libraries and the use of the new version in running applications without any mo dication (and the old library can b e thus discarded). The preservation of b ehaviour is assured by incorp orating the concept of shortcut into the formal sp ecication of the container (see FM00] for more details). 5. External reusability . The children classes of Container inherit its denition of shortcuts and the corresp onding op erations. Therefore, the ob jects stored in the Container sp ecialisations can b e accessed by using either the op erations that characterise every particular typ e of container or the shortcut op erations. 6. Internal reusability . The CLC{library is develop ed following step{by{step design and implementation design and implementation for reuse and design and implementation with reuse. 7. Avoid commit iterations to a specic container implementation . Iterations are made over the Container base class and as a consequence we can iterate over a container without commiting to an sp ecic implementation 3 . Implementation The essential p oint consists in maintaining an ecient mapping from shortcuts to items in the Container base class. There are two basic dierent p ossibilities to implement this mapping dep ending on the underlying memory management scheme: 1. Using dynamic storage . In this case the Shortcut pattern is implemented with an smart pointer 4 Ede92] to a tuple whichcontains the ob ject and a deleted ag. On the other hand the Container base class is implemented with a double linked list of these tuples 5 . 2. Using an array . In this case the Shortcut pattern is implemented as an index to the array p osition. Then the Container base class is implemented as an array of tuples whichcontain the ob ject, a deleted ag, a reference counter(beingevery reference a shortcut) and two indexes to the next and previous tuples in the iterator ordering. As released shortcuts (the deleted array p ositions) must b e available somehowtoallow further reassignmentwe must link them to o. Additional index memb ers corresp onding to the p osition of the rst ob ject, the p osition of the last ob ject and the rst free p osition have to b e maintained in the Container base class. 3 Polymorphic iterators solve this problem to o, but they intro duce other drawbacks. 4 Being its main characteristic that the deletion of allo cated ob jects do es not take place until there are no shortcuts b ound to them. 5 In order to have ecient bidirectional iterators.
17 A particular issue has to b e taken into consideration. In order to get all the b en- ets that the Shortcut pattern oers we need some extra space. More precisely, b eing N the numb er of ob jects in the container, the total amount of extra space is: 2 N space (p ointer ) + N space (shortcut ) (we are assuming a p ointer{based implementation of shortcuts, whichisthe worst case concerning space eciency). The rst op erand comes from the double linked list and the second one from the shortcut stored in the implementation of a concrete abstraction. However,thiswaste of space will usually generate a later saving, when shortcuts substitute identiers (generally strings, which require more space than shortcuts) in references from other ob jects. The relationship between these two factors may b e formally established. Let N b e the total numb er of ob jects in the container and R the total number of references. Since generally, space (identier ) space (p ointer ) then 9 k 1 s.t. space (identier ) k space (p ointer ), and since space (shortcut ) = 2 space (p ointer ) (b ecause we use twopointers for assuring that a particular shortcut is b ound to a particular container) space is really saved when the relationship R space (identier ) 4 N space (p ointer ) holds, which is satised when the following relationship holds: R k 4 N: Sample co de We show here a C++ implementation of three participants in the pattern, Shortcut, Iterator and Container, together with the implementation of the Container Abstraction Map and a Concrete Array based Implementation of it. Wepresent an example of use, to o. The implementation of the pattern uses dynamic memory. The example of use illustrates how iterators are not b ound to a concrete implementation. 1. Implementation of the Shortcut class . This class is in the interface of Container. This is the reason for which itisnot presented as a template class. The No de and p ointer classes are not included. class Shortcut { protected: pointer<Node> ptr Container* ptrContainer friend class Container<Item>
18 friend class Iterator public: Shortcut() :ptrContainer(NULL){} Shortcut(const Shortcut& shortcut) :ptr(shortcut.ptr), ptrContainer(shortcut.ptrContainer){} const Item& ItemOf() { if (!Defined()) throw UndefinedShortcut return ptr.value().item } bool Defined() { if (ptr.IsNull()) return false if(ptr.value().deleted_flag) { ptr.SetNull() return false } return true } void operator =(const Shortcut &shortcut) { ptr = shortcut.ptr ptrContainer = shortcut.ptrContainer } ~Shortcut(){} protected: Shortcut (const Item& item) { ptr = pointer<Node>(Node()) ptr.value().item = item } } The implementation of this class is straightforward. It stores the Container along with a smart p ointer ptr to the container no de where is the item b ound to the shortcut. The Defined op eration returns true if there is a non deleted ob ject b ound to the shortcut and false otherwise. Notice, that the op eration ItemOf and Defined are not declared as const b ecause if the ob ject asso ciated to the shortcut is marked as deleted we set the p ointer as NULL to dismiss the numb er of references. We can observe that all the op erations are O (1) in the worst case. 2. Implementation of the Iterator class . This class is in the interface of Container to o. The iterator class is a sub class of a bidirectional iterator abstract class. class Iterator:public bidirectional_iterator<Item> { protected: pointer<Node> ptr Container<Item>* ptrContainer
19 public: Iterator() :ptrContainer(NULL){} Iterator(const Iterator& iterator) :ptr(iterator.ptr), ptrContainer(iterator.ptrContainer){} ~Iterator(){} virtual void BindToContainer(Container<Item>* C) { ptr = C->_container.value().next ptrContainer = C } virtual void First() { if(ptrContainer != NULL) ptr = ptrContainer->_container.value().next } virtual void Last() { if(ptrContainer != NULL) ptr = ptrContainer->_container.value().previous } virtual void Next() { if(!IsDone()) ptr = ptr.value().next } virtual void Previous() { if(!IsDone ()) ptr = ptr.value().previous } virtual const Item& CurrentItem() { if(IsDone()) throw IteratorIsDone return ptr.value().item } virtual bool IsDone() { if(ptrContainer == NULL) return true if(ptr.IsNull()) return true if(ptr.value().deleted_flag) { ptr.SetNull() return true } if(ptr == ptrContainer->_container) return true return false } virtual void operator =(const Iterator &iterator) { ptr = iterator.ptr ptrContainer = iterator.ptrContainer }
20 virtual Shortcut CurrentShortcut() { Shortcut sh if(IsDone()) throw IteratorIsDone sh.ptr = ptr sh.ptrContainer = ptrContainer return sh } } This class oers a new op eration CurrentShortcut that returs the Shortcut asso ciated to the CurrentItem . As in the case of the class shortcut, all the op erations have constant cost in the worst case. 3. Implementation of the class Container . The classes Shortcut and Iterator shown b efore are included in the public Container interface. template<class Item> class Container{ // Definition of the class Node. // ... class Iterator // It's necessary because the class // Shortcut declares it as friend public: // Definition of the class Shortcut // ... // Definition of the class Iterator // ... protected: friend class Iterator friend class Shortcut pointer<Node> _container unsigned long count public: Container() ~Container() virtual Shortcut Add(const Item &item) virtual void Delete(Shortcut &shortcut) virtual void Modify(Shortcut& shortcut, const Item& item) virtual unsigned long NItems() } Constructor and destructor op erations. template <class Item> Container<Item>::Container() :_container(Node()), count(0) { _container.value().n ext = _container _container.value().previous = _container } template <class Item>
21 Container<Item>::~Container() { pointer<Node>p,a a = _container.value().next while(a !=_container) { p = a.value().next a.value().deleted_flag = true a.value().next.SetNull() a.value().previous.SetNull() a=p } _container.value().deleted_flag = true _container.value().next.SetNull() _container.value().previous.SetNull() } Add adds the item in the container and return the shortcut that allows fast access to it. template <class Item> Container<Item>::Shortcut Container<Item>::Add(const Item &item) { Shortcut sh(item) _container.value().previous.value().next = sh.ptr sh.ptr.value().previous = _container.value().previous sh.ptr.value().next = _container _container.value().previous = sh.ptr count++ sh.ptrContainer = this return sh } Delete implements the deletion in a double link list. It marks as deleted the item asso ciated to the shortcut, if any, set as NULL the shortcut members ptr and ptrContainer , and the Node memb ers p ointers next and previous . template <class Item> void Container<Item>::Delete(Shortcut &shortcut) { if (shortcut.Defined()) { if(shortcut.ptrContainer != this) throw ShortcutIsNotBoundToThisContainer shortcut.ptr.value().deleted_flag= true shortcut.ptr.value().previous.value().next = shortcut.ptr.value().next shortcut.ptr.value().next.value().previous = shortcut.ptr.value().previous shortcut.ptr.value().next.SetNull() shortcut.ptr.value().previous.SetNull()
22 shortcut.ptr.SetNull() count-- } } Modify changes the item asso ciated to the shortcut, if any,by the new one. template <class Item> void Container<Item>::Modify(Shortcut& shortcut, const Item& item) { if(shortcut.Defined()) { if(shortcut.ptrContainer != this) throw ShortcutIsNotBoundToThisContainer shortcut.ptr.value().item = item } } NItems is straightforward. It returns the value of the internal counter. template <class Item> unsigned long Container<Item>::NItems() {return count} 4. Map Container Abstraction .Weshow here the interface and implemention of this class. This class denes the typ e of the ob jects to b e stored in its concrete sub classes (in this case pairs of Shortcuts) and denes a new compare class whichallows to compare keys with shortcuts (comparing the key with the key asso ciated to the shortcut). The implemen tation of this class uses the Template Metho d to implement its public interface. Therefore, its children classes havetoonlyimplement the op erations deferred in the implementation of this public interface (concrete op erations) which are dened in the protected part. On the other hand, this class provides an implementation of this protected interface that makes it a non{abstract class. template <class Key, class Value, class Less=less<Key>> class Map:public Container< KeyValue<Key,Value> > { protected: class ConLess { protected: Less _less public: ConLess(Less l):_less(l){} bool operator()(const Key& key, Shortcut& sh) { return _less(key,sh.ItemOf().key) } bool operator()(Shortcut& sh, const Key& key) { return _less(sh.ItemOf().key,key)
23 } } typedef Key ConKey typedef Shortcut ConValue typedef KeyValue<Shortcut,ConValue> ConItem Less less ConLess conless Iterator cache public: typedef KeyValue<Key,Value> Item Map():conless(less) {cache.BindToContainer(this)} ~Map(){} Shortcut Add(const Item& item) void Delete(Shortcut& shortcut) void Modify(Shortcut& shortcut, const Item& item) Value Delete(const Key& key) const Value& Get(constKey& key) bool Exist(const Key& key) protected: virtual void ConAdd(const ConItem& item){} virtual ConValue ConDelete(const ConKey& key) virtual ConValue ConGet(const ConKey& key) virtual bool ConExist(const ConKey& key) } Add op eration of the class Map. This op eration deferres the op erations ConExist , ConGet and ConAdd to the concrete implementation and adds or mo dies the item in the container base ob ject. template <class Key, class Value, class Less=less<Key>> Container< KeyValue<Key,Value> >::Shortcut Map<Key,Value,Less> ::Add(const Item& item) { Shortcut sh if(ConExist(item.key)) { sh = ConGet(item.key) Container<Item>::Modify(sh,item) } else { sh = Container<Item>::Add(item) ConItem itemcon(sh,sh) ConAdd(itemcon) } return sh } Delete (by shortcut) op eration of class Map. This op eration deletes the item asso ciated to the shortcut using its key. template <class Key, class Value, class Less=less<Key>>
24 void Map<Key,Value,Less>::Delete(Shortcut& shortcut) { if(shortcut.Defined()) Delete(shortcut.ItemOf().key) } Modify op eration of class Map. In this Container Abstraction this op eration havetobeoverrided to allowonly modingthe value and not the key. template <class Key, class Value, class Less=less<Key>> void Map<Key,Value,Less> ::Modify(Shortcut& shortcut, const Item& item) { if(shortcut.Defined()) if(!conless(shortcut,item.key) && !conless(item.key,shortcut)) Container<Item>::Modify(shortcut,item) } Delete (bykey) op eration of class Map. This op eration deletes the pair of shortcuts stored in the concrete implementation of the container abstraction using the ConDelete op eration and deletes the item from the Container base ob ject using the shortcut. template <class Key, class Value, class Less=less<Key>> Value Map<Key,Value,Less>::Delete(const Key& key) { Shortcut sh Value v sh = ConDelete(key) v = sh.ItemOf().value Container<Item>::Delete(sh) return v } Get op eration of class Map. This op eration uses the ConGet to get the shortcut of the key and returns the value of the item asso ciated to this shortcut. template <class Key, class Value, class Less=less<Key>> const Value& Map<Key,Value,Less>::Get(const Key& key) { Shortcut sh sh = ConGet(key) return sh.ItemOf().value } Exist op eration of class Map. template <class Key, class Value, class Less=less<Key>> bool Map<Key,Value,Less>::Exist(const Key& key) { return ConExist(key) }
25 Following we giveaversion of the concrete op erations of class Map using the the container interface and shortcuts. ConDelete concrete delete op eration of class Map. template <class Key, class Value, class Less=less<Key>> Map<Key,Value,Less>::ConValue Map<Key,Value,Less> ::ConDelete(const ConKey& key) { ConValue v if(ConExist(key)) { v = cache.CurrentShortcut() cache.Previous() return v } throw NotExistingKey return ConValue() } ConGet concrete get op eration of class Map. template <class Key, class Value, class Less=less<Key>> Map<Key,Value,Less>::ConValue Map<Key,Value,Less> ::ConGet(const ConKey& key) { if(ConExist(key)) return cache.CurrentShortcut() throw NotExistingKey return ConValue() } ConExist concrete exist op eration of class Map. template <class Key, class Value, class Less=less<Key>> bool Map<Key,Value,Less>::ConExist(const ConKey& key) { Iterator it if(!cache.IsDone()) if(!less(key,cache.CurrentItem().key) && !less(cache.CurrentItem().key,key)) return true it.First(this) while(!it.IsDone()) { if(!less(it.CurrentItem().key,key) && !less(key,it.CurrentItem().key)) { cache = it return true } it.Next() } return false }