Re: Design Problem Aggregation

From: Robert C. Martin (
Date: 05/11/04

Date: Tue, 11 May 2004 12:52:33 -0500

On 9 May 2004 15:54:24 -0700, (Merlin) wrote:

>Imagine the following classes (A class diagram will help)
>BASE, A, B, C, D, E, F, G.
>A, B, C, D, G inherit from BASE.
>E, F inherit from D.
>Class E has a member (aggregation by value) of type A.
>Class F has a member (aggregation by value) of type B.
>Class G has a member that is container that can accept objects of type
>D. As D is the base class of E and F we can add to the container
>objects of type E or F. I have made the container type safe in this
>I wanted G to be a collection of objects of type A or B but never C so
>I introduced an abstract class D and made the container of that type
>so it would only accept objects of base type D. However, although this
>looks ok, I am not happy with the extra work it has created.
>As I need to access the interface to A and B, I need to repeat all
>that interface in E and F. A and B have many member functions and I
>dont want to rewrite all that interface in E and F and delegate the
>calls to the aggregate.

In effect E and F are Decorators that allow insertion into G. (See
the Decorator pattern in the GOF book).

Another way to cut at this would be:

   | * A
   | | |Base|
   | +-+-+ A
   | \ \ |
   | +---+---+--+---+
   | | \| \| |
   +--|G| |A| |B| |C|

Thus, both A and B derive from a separate interface named Gpart. G
contains a list of Gparts. When you pull a Gpart out of the list you
then cast it to a Base and use it naturally.

This is called the Interface Segregation Principle. You can read
about this principle, and Decorators, and many other design patterns
and principles in:

Agile Software Development: Principles, Patterns, and Practices
Robert C. Martin, Prentice Hall, 2002.

>The solution where I provide a member function in classes E and F to
>return the aggregate seems wrong as its exposing a private data
>How can I change my design to make it better and flexible?
>I have intentionally used meaningless letters in order to focus on the
>relationships of the classes as oppose to what they model.
>I hope this wont confuse anyone.
>Many Thanks in advance

Robert C. Martin (Uncle Bob)
Object Mentor Inc.
unclebob @ objectmentor . com

"The aim of science is not to open the door to infinite wisdom,
 but to set a limit to infinite error."
    -- Bertolt Brecht, Life of Galileo