MFC Programmer's SourceBook : Thinking in C++
Bruce Eckel's Thinking in C++, 2nd Ed Contents | Prev | Next

Abstracting usage

With creation out of the way, it’s time to tackle the remainder of the design: where the classes are used. Since it’s the act of sorting into bins that’s particularly ugly and exposed, why not take that process and hide it inside a class? This is simple “complexity hiding,” the principle of “If you must do something ugly, at least localize the ugliness.” In an OOP language, the best place to hide complexity is inside a class. Here’s a first cut:

A TrashSorter object holds a vector that somehow connects to vectors holding specific types of Trash. The most convenient solution would be a vector<vector<Trash*>>, but it’s too early to tell if that would work out best.

In addition, we’d like to have a sort( ) function as part of the TrashSorter class. But, keeping in mind that the goal is easy addition of new types of Trash, how would the statically-coded sort( ) function deal with the fact that a new type has been added? To solve this, the type information must be removed from sort( ) so all it needs to do is call a generic function which takes care of the details of type. This, of course, is another way to describe a virtual function. So sort( ) will simply move through the vector of Trash bins and call a virtual function for each. I’ll call the function grab(Trash*), so the structure now looks like this:

However, TrashSorter needs to call grab( ) polymorphically, through a common base class for all the vectors. This base class is very simple, since it only needs to establish the interface for the grab( ) function.

Now there’s a choice. Following the above diagram, you could put a vector of trash pointers as a member object of each subclassed Tbin. However, you will want to treat each Tbin as a vector, and perform all the vector operations on it. You could create a new interface and forward all those operations, but that produces work and potential bugs. The type we’re creating is really a Tbin and a vector, which suggests multiple inheritance. However, it turns out that’s not quite necessary, for the following reason.

Each time a new type is added to the system the programmer will have to go in and derive a new class for the vector that holds the new type of Trash, along with its grab( ) function. The code the programmer writes will actually be identical code except for the type it’s working with . That last phrase is the key to introduce a template, which will do all the work of adding a new type. Now the diagram looks more complicated, although the process of adding a new type to the system will be simple. Here, TrashBin can inherit from TBin, which inherits from vector<Trash*> like this (the multiple-lined arrows indicated template instantiation):

The reason TrashBin must be a template is so it can automatically generate the grab( ) function. A further templatization will allow the vectors to hold specific types.

That said, we can look at the whole program to see how all this is implemented.

//: C25:Recycle4.cpp
//{L} TrashPrototypeInit
//{L} FillBin Trash TrashStatics
// Adding TrashBins and TrashSorters
#include <fstream>
#include <vector>
#include "Trash.h"
#include "Aluminum.h"
#include "Paper.h"
#include "Glass.h"
#include "Cardboard.h"
#include "fillBin.h"
#include "sumValue.h"
#include "../purge.h"
using namespace std;
ofstream out("Recycle4.out");

class TBin : public vector<Trash*> {
public:
  virtual bool grab(Trash*) = 0;
};

template<class TrashType>
class TrashBin : public TBin {
public:
  bool grab(Trash* t) {
    TrashType* tp = dynamic_cast<TrashType*>(t);
    if(!tp) return false; // Not grabbed
    push_back(tp);
    return true; // Object grabbed
  }
};

class TrashSorter : public vector<TBin*> {
public:
  bool sort(Trash* t) {
    for(iterator it = begin(); it != end(); it++)
      if((*it)->grab(t))
        return true;
    return false;
  }
  void sortBin(vector<Trash*>& bin) {
    vector<Trash*>::iterator it;
    for(it = bin.begin(); it != bin.end(); it++)
      if(!sort(*it))
        cerr << "bin not found" << endl;
  }
  ~TrashSorter() { purge(*this); }
};

int main() {
  vector<Trash*> bin;
  // Fill up the Trash bin:
  fillBin("Trash.dat", bin);
  TrashSorter tbins;
  tbins.push_back(new TrashBin<Aluminum>());
  tbins.push_back(new TrashBin<Paper>());
  tbins.push_back(new TrashBin<Glass>());
  tbins.push_back(new TrashBin<Cardboard>());
  tbins.sortBin(bin);
  for(TrashSorter::iterator it = tbins.begin(); 
    it != tbins.end(); it++)
    sumValue(**it);
  sumValue(bin);
  purge(bin);
} ///:~ 

TrashSorter needs to call each grab( ) member function and get a different result depending on what type of Trash the current vector is holding. That is, each vector must be aware of the type it holds. This “awareness” is accomplished with a virtual function, the grab( ) function, which thus eliminates at least the outward appearance of the use of RTTI. The implementation of grab( ) does use RTTI, but it’s templatized so as long as you put a new TrashBin in the TrashSorter when you add a type, everything else is taken care of.

Memory is managed by denoting bin as the “master container,” the one responsible for cleanup. With this rule in place, calling purge( ) for bin cleans up all the Trash objects. In addition, TrashSorter assumes that it “owns” the pointers it holds, and cleans up all the TrashBin objects during destruction.

A basic OOP design principle is “Use data members for variation in state, use polymorphism for variation in behavior.” Your first thought might be that the grab( ) member function certainly behaves differently for a vector that holds Paper than for one that holds Glass. But what it does is strictly dependent on the type, and nothing else.

  1. TbinList holds a set of Tbin pointers, so that sort( ) can iterate through the Tbins when it’s looking for a match for the Trash object you’ve handed it.
  2. sortBin( ) allows you to pass an entire Tbin in, and it moves through the Tbin, picks out each piece of Trash, and sorts it into the appropriate specific Tbin. Notice the genericity of this code: it doesn’t change at all if new types are added. If the bulk of your code doesn’t need changing when a new type is added (or some other change occurs) then you have an easily-extensible system.
  3. Now you can see how easy it is to add a new type. Few lines must be changed to support the addition. If it’s really important, you can squeeze out even more by further manipulating the design.
  4. One member function call causes the contents of bin to be sorted into the respective specifically-typed bins.
Contents | Prev | Next


Go to CodeGuru.com
Contact: webmaster@codeguru.com
© Copyright 1997-1999 CodeGuru