When developing a class structure,
often the choice will arise as to whether to employ inheritance
or explicit delegation as a means to
utilize the functionality of a particular class.
The choices a designer may be confronted with when
developing a system or a class library may be illustrated
by a simple example.
Suppose you must develop a system that produces
a kwicindex.
A kwicindex contains for each line of text
all possible rotations, so that each word can be
rapidly searched for, together with the context in which
it occurs.
The example is taken from [VanVliet], who discusses
a number of alternative solutions from the
perspective of information hiding.
An object-oriented solution appears to be surprisingly
simple, in particular when a suitable library is available.
The two classes that are of interest are, respectively,
a class line, to represent each line of text,
and a class index to represent the lines
generated for the kwicindex.
The class line is simply a list of words (strings)
that can be rotated.
The actual implementation of a line is
provided by an instantiation of
a generic (template) class list,
that is contained as a data member,
to which the operations insert and rotate
are delegated.
Instead of incorporating a member of type ,
the line class could have been made a descendant
of the class , as indicated below
class line : public list {
...
};
However, this would make the type line a subtype
of , which does not seem to be a wise decision.
Alternatively, private inheritance could have been employed
as in
class line : private list {
...
};
But, as we have noted before, private inheritance
may also introduce unwanted dependencies.
Explicit delegation seems to be the best solution,
because the relation between a line object
and a list of strings is best characterized
as a uses relation.
}
For the index class, a similar argument
as for the line class can be given as to
why delegation is used instead of public or private
inheritance.
Actually, the most difficult part of the code
is the function defining how to compare two lines
of text that is needed for sorting the index.
Comparison is based on the lexicographical order
as defined below.
The ease of implementing both the line and index
classes depends largely upon the availability of a
powerful list template class.
In the example, we employed
the functions to rotate
the elements in the list, and
to sort the elements in the list.
The function was used
to determine the relation between elements
of the list.
The actual library employed for this example
is the splash library, which is discussed in
section libraries.