TITLE: the capsule design pattern

CLARKE: Allan Clarke (clarke@ses.com)

Robert Martin has an interesting article titled "Cross
Casting: The Capsule Pattern", in the June 97 issue of
"The C++ Report". The focus of this pattern is to
reduce coupling between application layers.

I'll paraphrase some of that material here. If you find
this interesting, check out the article for more details.

In C++ you can use the dynamic_cast facility to do more
than cast simply up or down the inheritance heirarchy.
For example, given the heirarchy below,

	class A { ... virtual ... };
	class B { ... virtual ... };
	class C : public A, public B { ... virtual ... };

you can perform the following "cross" cast

	A* ap = new C;

	...

	B* bp = dynamic_cast<B*>(ap);

This is interesting notedly because class A and class B
are completely unrelated. The main idea of this pattern
is to define

	class Capsule
	{
	  public:
		virtual ~Capsule () {}
	};

as the unspecific class that much of your application
code sees. In lower layers of your application code, 
you can construct instances like this

	class ComplexError : public Capsule, 
			     public GUIError,
			     public CommError
	{
		...
	};

As this instance propogate through intermediate layers,
its seen as a Capsule*. When it reachs the upper layers,
the Capsule* can be cross cast to "see if its interesting"
to this layer, as in

	Capsule* cap = lowerLayers (...);

	if (dynamic_cast<GUIError*>(cap))
	{
		// process the GUI error here
	}

There are more details about a graceful way to keep the
type testing logic above to a minimum by breaking the
handling of the "error" from the error capsule. (I'll
post another tip on this soon).

Check out the article!






