    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: The Encapsulate Context Pattern</title>
        <link>https://members.accu.org/index.php/journals/246</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #63 - Oct 2004 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c149/">63</a>
                    (6)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c149-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c149+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;The Encapsulate Context Pattern</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 01 October 2004 16:25:39 +01:00 or Fri, 01 October 2004 16:25:39 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="article" lang="en">
<div class="titlepage">
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e21" id="d0e21"></a>Prologue</h2>
</div>
<p><span class="emphasis"><em>Encapsulate Context</em></span> was
born after a query to accu-general in Summer 2002. I don't think I
was looking to write a pattern but I'm glad I did - in retrospect I
wish I had begun writing patterns earlier. However, writing
patterns is hard work and time consuming. Between the first draft
and the version you are about to read 18 months elapsed. The paper
may bear my name but it wouldn't be the paper it is without the
help of many others.</p>
<p>The version here hasn't changed in several months and is the
same as that printed in the EuroPLoP 2003 conference proceedings.
This doesn't mean it won't change again, to some degree patterns
are living entities that change as people use them and gain
experience. So, I wouldn't be surprised if the pattern appears
again, elsewhere, with further revisions.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e30" id="d0e30"></a>Abstract</h2>
</div>
<p>A system contains data, which must be generally available to
divergent parts of the system, but we wish to avoid using long
parameter lists to functions or global data; therefore, we place
the necessary data in a Context container and pass this object from
function to function.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e35" id="d0e35"></a>Audience</h2>
</div>
<p><span class="emphasis"><em>Encapsulate Context</em></span> is
principally written for software developers designing and writing
programs. The pattern was originally written for C++ developers,
however examples have been reported from other languages such as
Java and Smalltalk. It is believed that users of any language will
find the pattern useful, although C++ developers may find the
pattern of particular interest.</p>
<p>By exploring the pattern in depth this paper offers a rigorous
explanation of where the pattern occurs, the forces and the
consequences of using the pattern. For reference purposes a summary
section has been included at the end of the paper. Experienced
developers may prefer to read the summary first before reading the
entire paper.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e44" id="d0e44"></a>Example</h2>
</div>
<p>In traditional structured programming, global data is minimised
by use of function call parameters. This tradition has continued,
with some modifications in object-oriented programming. For
example:</p>
<pre class="programlisting">
void ProcessMarketTrade(MarketMessage&amp; msg,
                     MarketDataStore&amp; store) {
  if(msg.Trade() == Sell)
    store.Sell(msg.Commodity(),
               msg.Price(), msg.Quantity());
  else
    store.Buy(msg.Commodity(),
              msg.Price(), msg.Quantity());
} // ProcessMarketTrade
</pre>
<p>We now decide that any trade which results in a negative
quantity should result in an error message, hence the function
<tt class="function">Sell</tt> must have access to the log manager,
consequently a handle must be passed down. The code becomes:</p>
<pre class="programlisting">
void ProcessMarketTrade(MarketMessage&amp; msg,
                       MarketDataStore&amp; store,
                       LogManager* log) {
  if(msg.Trade() == Sell)
    store.Sell(msg.Commodity(), msg.Price(),
               msg.Quantity(), log);
  ... as before ...
</pre>
<p>Such changes have a habit of reoccurring, so, when we add a
transaction history the code changes again:</p>
<pre class="programlisting">
void ProcessMarketTrade(MarketMessage&amp; msg,
                MarketDataStore&amp; store,
                LogManager* log,
                TransactionHistory&amp; history) {
  if(msg.Trade() == Sell)
    store.Sell(msg.Commodity(), msg.Price(),
               msg.Quantity(), log, history);
  ... and so on ...
</pre>
<p>Several problems are clearly apparent. First the parameter list
is growing with a negative effect on comprehensibility, even though
the additional code is trivial it increases the bulk. Secondly, we
are breaking encapsulation. Initially <tt class=
"function">Sell</tt> was an encapsulated function, by adding more
and more parameters its inner workings are being exposed.</p>
<p>More ominously, we have a ripple effect running through
interface and implementation code. The function that calls
<tt class="function">ProcessMarketTrade</tt> must itself have
access to <tt class="classname">LogManager</tt> and <tt class=
"classname">TransactionHistory</tt>, and in turn, the function that
calls that function, and so on. Even though these functions will
only act as pass-throughs for the handles they are affected.</p>
<p>Less obvious is the capacity for redundant code to enter the
system. If at some future date we dispense with the transaction
history then removal impacts at least three different functions. To
be sure, the temptation would be to disable the code while leaving
it in place, hence we simply make it an anonymous parameter in
<tt class="function">Sell</tt>:</p>
<pre class="programlisting">
void MarketStore::Sell(Commodity&amp; c,
                       Price&amp; p,
                       Quantity&amp; q,
                       LogManager* log,
                       TransactionHistory&amp;) {
  ....
</pre>
<p>In choosing not to delete the history in full we are storing up
complications for future refactorings, we are also half-way to
implementing the Poltergeist anti-pattern (<a href=
"#Brown1998">Brown1998</a>).</p>
<p>These problems are exacerbated when a dependency inversion
design is adopted. We may decide to recast our market message
processing as a Command pattern (<a href=
"#Gamma1994">Gamma1994</a>):</p>
<pre class="programlisting">
class MarketMessageCommand {
public:
  virtual void Action(MarketDataStore&amp;,
                      LogManager*) = 0;
  ....
};
class Buy : public MarketMessageCommand {
public:
  virtual void Action(MarketDataStore&amp;,
                      LogManager*);
  ....
};
class Sell : public MarketMessageCommand {
public:
  virtual void Action(MarketDataStore&amp;,
                      LogManager*);
  ....
};
</pre>
<p>To ensure substitutability each <tt class=
"classname">MarketMessageCommand</tt> must implement <tt class=
"methodname">Action</tt> with the same signature as the abstract
base class. Consequently commands such as <tt class=
"classname">Buy</tt> are complicated with parameters which are
unused. Worse, the potential for ripple effects is magnified across
all objects in the hierarchy. If the exchange introduces a
programmatic way of signalling transition point in the trading day
with an enumeration such as:</p>
<pre class="programlisting">
enum TradingDay { 
  Closed, PreOpen, Open, Settlement, Suspended
};
</pre>
<p>A new market message is needed to handle this, but so too is a
state variable:</p>
<pre class="programlisting">
class TradingDayChange : public MarketMessageCommand {
public:
  virtual void Action(MarketDataStore&amp;,
                      LogManager*,
                      TradingDay&amp; activity);
  ....
};
</pre>
<p>Since our new message can change the state activity a new
parameter is needed, to maintain a common signature this parameter
must be added to <tt class="classname">MarketMessageCommand</tt>
and all derived classes. Again, we are increasing the length of the
parameter list, introducing a ripple effect and adding complexity.
Our main loop may look like:</p>
<pre class="programlisting">
int main() {
  MarketDataStore marketData;
  LogManager *log(LogFactory());
  TradingDay exchangeStatus(Closed):
  MessageSource source;
  while(true) {
    auto_ptr&lt;MarketMessageCommand&gt;
                      w(source.NextMessage());
    w-&gt;Action(marketData, log, exchangeStatus);
  }
  delete log;
  return 0;
}
</pre>
<p>Faced with the problem of adding yet more parameters we may be
tempted to consider global variables. After all, an exchange is
open or closed, there is only one instance of such a flag surely? A
tempting solution, the exchange status is a simple variable,
initialisation is not a significant problem, and being stack based
a memory leak is a non-issue.</p>
<p>However, for <tt class="classname">LogManager</tt> a global
variable is decidedly less tempting. The example above strictly
controls the use of log through scope and parameter passing, were
the same variable global it could potentially be accessed before
creation, e.g. the <tt class="classname">MarketDataStore</tt>
constructor may choose to log a message.</p>
<p>We would then be forced into the position of trying to enforce
creation before use. This is known to be problematic and the best
known solution (access through a function) suffers from known
issues in multi-threaded systems. Further, the same problems occur
in reverse when cleanly ending the program.</p>
<p>While we may be able to survive one or two such global variables
we quickly find the number increasing, first the exchange status,
then the log manager, what of our transaction history? Have we
loaded any DLL plug-ins? Better have a global list of their
handles. As we add more global variables it becomes harder to
reason about the initialisation sequence for each - particularly
important when one makes use of another. It is also more difficult
to reason about the internal state of the program because it is
dispersed with no central point of reference.</p>
<p>Even with the best will in the world the old issues of globals
still exist. Judicious use of namespaces, and careful coding may
afford us the luxury of a few globals but the old issues have not
gone away, merely repositioned or hidden for a while.</p>
<p>The solutions so far suggested do nothing to improve either the
testability of our system or the transfer of components to
follow-on projects. Suppose we wish to use our <tt class=
"classname">MarketMessageCommand</tt> in a market simulator. Long
parameter lists, and global variables force us to implement
plumbing around the hierarchy so we can use the commands.</p>
<p>Likewise, if we wish to write a test harness for our hierarchy,
or force test data through the system we must implement the
necessary plumbing to support the classes.</p>
<p>Each additional parameter or global variables makes the classes
and methods more specific and less of a commodity. Without such
specifics, the <tt class="classname">MarketMessageCommand</tt>
hierarchy implements generic, run-time polymorphic handling of
messages. Longer parameter lists increase coupling, tying classes
closer to the environment, shorter interfaces are more loosely
coupled and result in a more general the class.</p>
<p>The nub of the problem is the ever-expanding parameter list. At
first this appears simply unsightly, however, as we can see, the
need pass more and more parameters is a real issue.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e151" id="d0e151"></a>Problem</h2>
</div>
<p>Access to common data is important to many systems. Many systems
contain data which must be generally available to divergent parts
of the system, e.g. configuration data, run-time handles and
in-memory application data.</p>
<p>However, we wish to avoid using global data - such data is
normally regarded as poor engineering practice. Traditionally the
problem is addressed by passing such data as function call
parameters but over time parameter list become longer. Long
parameter lists themselves have an adverse effect on
maintainability and on object substitutability.</p>
<p>While access to such data is a common requirement neither of the
two common techniques are without problems. Access to the data is
not as trivial as it first appears, and as any system grows the
drawbacks of each solution become greater.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e160" id="d0e160"></a>Forces</h2>
</div>
<p>There are several forces that any solution to this problem must
accommodate for it to be widely applicable.</p>
<div class="orderedlist">
<ol type="1">
<li>
<p><span class="bold"><b>Substitutability</b></span></p>
<p>Software designs based on common interfaces, with object
substitutability - either run-time polymorphic or compile-time
polymorphic - are restricted in the parameters that can be easily
passed to an object because all objects must conform to a common
interface with common function signatures to ensure commonality of
access - i.e. the Liskov Substitution Principle - LSP (<a href=
"#Liskov1988">Liskov1988</a>, <a href=
"#Martin1996">Martin1996</a>).</p>
<p>However, where all data is supplied to objects and function via
call parameters, if any object requires additional data it must be
passed via a call parameter, to keep LSP all similar objects must
also accept this parameter even if they have no functional
requirement for it.</p>
<p>For an object, changing any function-method call signature,
whether by addition, revision or removal breaks LSP. The object in
question can no longer be substituted for other similar objects.
The compiler should refuse to compile the resulting program.
Typically we must either change every class in the same hierarchy
to match the new signature, change every call to the
function-method, or both.</p>
<p>Having broken LSP we are forced to restore LSP by changing other
parts of the system. This creates ripple effects through the code
base. A good solution to the overall problem would ensure that LSP
is not broken, and consequently, ripple effects within the code
base are minimised.</p>
</li>
<li>
<p><span class="bold"><b>Encapsulation</b></span></p>
<p>Good software practice values encapsulation, however,
traditional solutions threaten encapsulation:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Over-long parameter lists to function calls reduce encapsulation
because the parameters suggest the internal workings to
developers.</p>
</li>
<li>
<p>Global variables break encapsulation by definition. They are
considered poor programming practice, leading to side-effects and
increased coupling.</p>
</li>
<li>
<p>Within C++ systems there are additional problems associated with
instantiation and destruction - particularly in multi-threaded
developments. Although C++ namespaces allow better management of
globals they do not resolve instantiation and coupling
problems.</p>
</li>
</ul>
</div>
<p>A good solution would preserve encapsulation thereby minimising
side effects and coupling.</p>
</li>
<li>
<p><span class="bold"><b>Coupling to the Environment</b></span></p>
<p>The parameters passed to a function, or method, define the state
of the system external to the object in question. An object
receiving a method call knows its own state (even if this is
stateless), what it does not know is the state of the rest of the
system, i.e. the context in which it is called. If global data is
used it becomes harder to reason about the state of the system at
the point of call.</p>
<p>Likewise, a simple function maintains little or no state between
calls, the external state is everything, the result of the function
call depends on the context in which it is called.</p>
<p>The more tightly coupled an object is to its environment the
more difficult it is to use the object in a different setting.
Opportunities for using the object in a different environment, e.g.
within a test harness, or re-used in a different system, are much
reduced. At the same time, the amount of consideration developers
must pay the object's environment is increased. Thereby, reducing
readability, understandability and maintainability.</p>
<p>A solution that minimised coupling would do much to improve
understandibility, maintainability and improve the opportunities
for alternative uses.</p>
</li>
<li>
<p><span class="bold"><b>Avoid Data Copying</b></span></p>
<p>One solution to the global v. parameter conflict would be to
retain a copy of such data in individual objects. Unfortunately,
this is not always practical, especially when the system has a
large number of small objects and/or objects exist in difference
execution threads.</p>
<p>Reasons for not copying pieces of data may include, but are not
limited to:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Data may be changing rapidly, e.g. equity market prices, and
needs to be available in several different locations in the
program</p>
</li>
<li>
<p>Data and operations on the data may overwhelm the class, e.g. a
simple command class used in a Command pattern may only have one
significant method, to additionally store data, handles, and
accessors would rob the class of its simplicity.</p>
</li>
<li>
<p>Overhead of a copy operation both in terms of time and memory
used - this is particularly so if the data is seldom accessed, e.g.
command line options.</p>
</li>
<li>
<p>Data may be singleton in nature, or encounter problems when
copied, e.g. a handle to a log file may be easily copied but we do
not wish to store multiple copies of the handle to prevent dangling
pointers (or references) when the file is closed. However, use of
the Singleton (<a href="#">Gamma1995</a>) pattern may not be
appropriate.</p>
</li>
</ul>
</div>
<p>Since these potential solutions are unavailable they represent
forces in their own right. Further, as modern systems frequently
end up with a large number of small objects these problems are
increasing.</p>
</li>
</ol>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e240" id="d0e240"></a>Solution</h2>
</div>
<p>Provide a Context container that collects data together and
encapsulates common data used throughout the system.</p>
<p>For example:</p>
<p>class Context { LogManager* log_; ComandLineOptions cmdOpts_;
ApplicationData* store_; .... };</p>
<p>Rather than supply multiple parameters, we supply a Context
object. The object acts as a container for program state data, a
central repository for widely used data within the system. The
Context object provides few, if any, functions itself. The object
is passed, or more likely a reference is passed, to functions when
they are called - utilising the &quot;parameterize from above&quot;
paradigm.</p>
<p>There are typically three types of data found in a context
class:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><span class="bold"><b>Configuration data</b></span>, e.g.
command line options.</p>
</li>
<li>
<p><span class="bold"><b>Application data</b></span>, e.g. market
data.</p>
</li>
<li>
<p><span class="bold"><b>Transient run-time data</b></span>, e.g.
handle to log manager.</p>
</li>
</ul>
</div>
<p>The example given here uses one context class for simplicity.
While the simplicity of a single context has a lot to recommend it,
without careful attention the class may become a kitchen-sink,
overwhelmed with any, and all, data in a system. When this happens
we start to see the emergence of a <span class=
"emphasis"><em>Blob</em></span> anti-pattern (<a href=
"#Brown1998">Brown1998</a>).</p>
<p>To counter the drift towards <span class=
"emphasis"><em>Blob</em></span> we can split the class into two or
more discrete classes, e.g. one for system data and handles with a
second for application data (see Figure 1).</p>
<div class="figure"><a name="d0e282" id="d0e282"></a>
<div class="mediaobject c2"><img src="/var/uploads/journals/resources/kelly-diag.png"
align="middle" alt=
"Solution places context data in a single container"></div>
<p class="title c3">Figure 1. Solution places context data in a
single container</p>
</div>
<p>Specifically, we can distinguish three types of split:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><span class="bold"><b>Temporal</b></span>: data is separated on
the basis of its lifespan, data which is short lived is kept
separate from data which exists for long periods. . It is better
not to mix transient data with persistent data lest expired data
remains in the container.</p>
</li>
<li>
<p><span class="bold"><b>Horizontal</b></span>: separating
reference data from value data, usually needed when one application
becomes large itself, inflating the size of the context.</p>
</li>
<li>
<p><span class="bold"><b>Vertical</b></span>: separating the
context class into a small hierarchy, usually needed when the same
context is needed in a family of programs. This allows for
specialisation through inheritance to provide each family member
with a specialised Context object and common code to be shared
across the family.</p>
</li>
</ul>
</div>
<p>Such splits will mitigate the <span class=
"emphasis"><em>Blob</em></span> tendencies but also detract from
the pattern simplicity. Splitting the Context class should also
help improve compile times, since we can assume that although some
functions will need to be passed all the fragments of the original
context, many will require fewer fragments thus reducing
dependencies.</p>
<p>However, while it may be desirable to split the Context class
for a variety of reasons this can be taken too far. The use of many
fine-grained Context objects may return us over long parameter
lists.</p>
<p>Thus, any implementation of <span class=
"emphasis"><em>Encapsulate Context</em></span> pattern should
consider the following issues:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><span class="bold"><b>Is a single Context class the best
answer?</b></span> The initially simplicity of a single Context may
lead to difficulties as anti-patterns emerge.</p>
</li>
<li>
<p><span class="bold"><b>What is the life expectancy of the
data?</b></span> Bundling short-lived or rapidly changing data
together with constant data may lead to confusion or
inaccuracies.</p>
</li>
<li>
<p><span class="bold"><b>Is there a family of programs under
development?</b></span> Is there benefit from creating vertical
hierarchy of Context facilitating technology transfers between
programs?</p>
</li>
<li>
<p><span class="bold"><b>Are we creating problems by mixing
reference and value data in the same context?</b></span> Could this
data be split horizontally between several Context objects?</p>
</li>
<li>
<p><span class="bold"><b>Are we in danger of creating too many,
fine-grained, Context classes?</b></span></p>
</li>
</ul>
</div>
<p>These issues must be addressed together as the answers to each
question influences the others.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e345" id=
"d0e345"></a>Resolution</h2>
</div>
<p>Applying this solution to the example given at the start of this
paper we get:</p>
<pre class="programlisting">
// MarketContext.hpp
class LogManager;
class CommandLineOptions;
class MarketDataStore;
class MarketContext {
  LogManager* log_;
  CommandLineOptions opts_;
  MarketDataStore* marketData_;
public:
  MarketContext(LogManager*,
                CommandLineOptions&amp;,
                MarketDataStore*);
  LogManager* Log();
  MarketDataStore* MarketData();
  CommandLineOptions&amp; CmdOptions()
                                const;
};
</pre>
<p>With this context class the presence or absence, of a <tt class=
"classname">TransactionLog</tt> is abstracted to a detail about
<tt class="classname">MarketContext</tt>.</p>
<p>The class should take a minimal role in the lifetime of enclosed
classes, it is better to present these as ready constructed to the
class. This removes life-cycle issues from the domain of the
context class, and, because enclosed classes are often just
references or pointers, the .hpp interface file should only need
forward declarations thereby reducing potential ripple effect. (The
decision on whether to use pointers or references to object is
outside the scope of this paper.)</p>
<p>Continuing this example the body of the program is
refactored:</p>
<pre class="programlisting">
class MarketMessageCommand {
public:
  virtual void Action(MarketContext&amp;) = 0;
  ....
};
int main() {
  LogManager* log(LogFactory());
  CmdLineOptions options(argc, argv);
  MarketDataStore marketData;
  MarketContext context(log, options,
                        &amp;marketData);
  MessageSource source;
  while(true) {
    auto_ptr&lt;MarketMessageCommand&gt;
                     w(source.NextMessage());
    w-&gt;Action(context);
  }
  return 0;
}
</pre>
<p>The context provides access to data which otherwise may be made
<span class="emphasis"><em>Singleton</em></span>, global or both,
for example the <tt class="classname">LogManager</tt>.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e374" id=
"d0e374"></a>Variations</h2>
</div>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><span class="bold"><b>Provide parent's this
pointer</b></span></p>
<p>The passing of this pointers to worker objects can be seen as a
variation on this theme, in effect the calling object is itself
acting as a context object for the worker objects. (One consequence
of using Context classes is that the need to pass this is usually
reduced.</p>
</li>
<li>
<p><span class="bold"><b>Provide forwarding functions to
encapsulated data</b></span></p>
<p>Rather than expose an entire member class the <tt class=
"classname">MarketContext</tt> class could implement forwarding
methods, for example, the <tt class="varname">CmdOptions</tt>
member could be replaced with:</p>
<pre class="programlisting">
class MarketContext {
  ...
  bool IsVerbose() const {
    return opts_.IsVerbose();
  };
  ... and other forwarding functions ...
};
</pre>
<p>However, it is best to keep the class as lightweight as
possible, to this end, the class exposes the key objects
encapsulated rather than implement pass through calls onto the
underlying data. It is the underlying class that decides what to
expose rather than the context class. Further, although such
forwarding functions may be convenient they contribute the tendency
for the context class to become a <span class=
"emphasis"><em>Blob</em></span> (<a href=
"#Brown1998">Brown1998</a>) so are best avoided.</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e406" id=
"d0e406"></a>Consequences</h2>
</div>
<p>As a result of the pattern, several of the forces detailed above
are resolved or balanced:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p><span class="bold"><b>Substitutability</b></span></p>
<p>Parameters passed to a function call can be restricted to
Context objects containing system state data and parameters which
specifically refer to the function call task in hand, e.g. market
trades. Function signatures are free of the clutter which can make
them fragile - there is no longer a need for every class method in
the hierarchy to accept every parameter ever needed.</p>
</li>
<li>
<p><span class="bold"><b>Encapsulation</b></span></p>
<p>The Context object effectively compacts the parameter list on a
function call signature, thereby abstracting state variables and
promoting encapsulation of the function. In addition there is a
reduction in ripple effect as function signatures become more
stable.</p>
<p>Having relieved the problems of passing parameter to a function
the attractions of global data are reduced. Indeed, the Context
object provides a natural home for data with characteristics of
global variables.</p>
</li>
<li>
<p><span class="bold"><b>Coupling to the Environment</b></span></p>
<p>The Context class is encapsulated through its own, well-known,
common, interface. This allows the solution to be applied to
compile-time and run-time polymorphic designs, using either
template metaprogramming or v-table dispatch techniques.</p>
<p>By providing several context classes data is encapsulated along
temporal, horizontal or vertical lines further reducing coupling.
It is difficult to eliminate all coupling because some classes will
always need other classes, to be sure, choosing the granularity of
the coupling is a design issue.</p>
<p>Additionally, by separating the classes implementing algorithms,
from the plumbing which supplies the data the classes themselves
are less coupled and more like commodities, making transfer to
other developments easier.</p>
</li>
<li>
<p><span class="bold"><b>Avoid Data Copying</b></span></p>
<p>Since the Context class contains common data with little
overhead there is no need to copy the data in local objects. There
may be multiple references to the Context object in the system,
particularly if multiple threads are being used. Hence some care
must be taken to avoid dangling references to Context objects.</p>
</li>
</ol>
</div>
<p>In addition there are other beneficial consequences:</p>
<div class="orderedlist">
<ol start="5" type="1">
<li>
<p><span class="bold"><b>Reasoning</b></span></p>
<p>State data that needs to be shared or retained is factored,
objects are left with either transient data or completely
stateless. By centralising the core data within a system we have
made it easier to reason about the system. We can halt the program
and look in one place to see what state the program is in rather
than having to look in multiple places.</p>
</li>
<li>
<p><span class="bold"><b>Instantiation</b></span></p>
<p>Instantiation issues are simplified because objects must be
created before being placed in the context and are subsequently
only accessed through the context. Destruction issues are similarly
handled because all access is via the context. The life-span of the
context can be clearly defined at a high level.</p>
</li>
<li>
<p><span class="bold"><b>Uncluttered Code</b></span></p>
<p>Pass-through code and long parameter lists have been minimised,
and the potential for future redundant code has been reduced - it
is easier to add and remove elements from the Context class. (This
may entail a recompile of the whole system when the interface to
the Context class is changed but recompilation should be
well-defined procedure.)</p>
</li>
<li>
<p><span class="bold"><b>Synchronisation Point</b></span></p>
<p>The Context class can provide a useful place to add mutexes for
multi-threaded systems. In multi-threaded environments the Context
object can hold all shared data, acting as a gatekeeper with mutex
control. This is reminiscent of the <span class=
"emphasis"><em>Monitor Object</em></span> pattern (<a href=
"#Schmidt2000">Schmidt2000</a>) with the same potential for
bottlenecks if lock access is not carefully considered.</p>
<p>Bottlenecks may be avoided if the data is either immutable (e.g.
command line options which do not change), or data elements manager
their own locking (e.g. a log manager which implements its own
synchronisation) and application data is absent.</p>
</li>
</ol>
</div>
<p>However, there are several less desirable consequences:</p>
<div class="orderedlist">
<ol start="9" type="1">
<li>
<p><span class="bold"><b><span class=
"emphasis"><em>Blob</em></span> Tendencies</b></span></p>
<p>As already mentioned, care must be taken as systems develop that
a context class does not become a <span class=
"emphasis"><em>Blob</em></span>. Already in the example given we
see the mixing of value data and reference data. Without vigilance
context classes may grow to encompass far more data and
functionality than is strictly necessary.</p>
<p>Invariably, the context class ends up touching most aspects of
the system. It is therefore best-placed low down in the dependency
hierarchy of classes - although this can lead to its own dependency
inversion problems and small changes necessitate a major recompile
of the system.</p>
<p>Once this happens we are in danger of implementing the
<span class="emphasis"><em>Blob</em></span> anti-pattern.</p>
<p>Fortunately, change to the Context class tends to be additive in
nature so seldom breaks other parts of the system, still, the
friction of change is increased. One way to minimise this is to
ensure that no operations are placed inside the context class. A
second technique is to use multiple Context classes as described
above, however, introducing too many Context classes will introduce
some of the original problems we sought to resolve.</p>
</li>
<li>
<p><span class="bold"><b>Hidden Globals</b></span></p>
<p>Blind use of Context classes can give rise to an abuse known as
&quot;Hide Forbidden Globals&quot; (<a href="#Green2001">Green2001</a>). This
is characterised by a kitchen-sink approach to the Context class
where every second variable is listed. Typically we see Context
members which are referenced in only a few points within the
system, usually such data would be better embedded in specific
classes rather than placed in Context.</p>
</li>
<li>
<p><span class="bold"><b>Dominant Sibling</b></span></p>
<p>Program families may share a common root Context class, which
they embellish through inheritance. In this model the context
underpins the common code of the family. If one family member
becomes dominant there will be pressure to enhance the common root
to facilitate the dominant member. This has a negative effect on
the other family members which start to see the common root as a
Blob, forcing upon them additional dependencies and complications
they do not need.</p>
<p>In the program family we find elements of functional overlap,
e.g. a market trading system and a market simulation system.</p>
<p>Both may use the <tt class=
"classname">MarketMessageCommmand</tt> and hence rely on the
<tt class="classname">MarketContext</tt> class as above. As one
program, say the simulation, becomes more important and bigger
objects start to appear in the command hierarchy which are specific
to the one application, eventually, one of these will require some
data which is not available in the context class. For immediate
simplicity we are tempted to add this into the context.
Unfortunately, the trading system now has this data even though it
is never used. If continued, over time, the trading system will be
inhibited by a <tt class="classname">Context</tt> class which is
obscured with unused functions.</p>
<p>More confusing too are the results if the trading system now
develops its own specialist message commands, and makes demands for
specific fields on the context class.</p>
<p>This is normally an indication that the <tt class=
"classname">Context</tt> class should be split vertically. We may
choose to create a hierarchy of three classes: a common base class,
a derived class with simulator enhancements and second derived
class with the trading system enhancements.</p>
<p>At this point we may compile different versions accepting either
a <tt class="classname">SimulatorContext</tt> or a <tt class=
"classname">TradingContext</tt>, or we may choose to down-cast the
provided context - assuming that the simulator message classes will
only ever be passed a <tt class="classname">SimulatorContext</tt>
by way of a <tt class="classname">MarketContext</tt> handle.</p>
</li>
</ol>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e549" id="d0e549"></a>Known
Uses</h2>
</div>
<div class="variablelist">
<dl>
<dt><span class="term">Chutney Technologies Apptimizer
(C++)</span></dt>
<dd>
<p>Apptimizer uses a single Context object to store handles to
important system objects, e.g., <tt class=
"classname">Configuration</tt>, <tt class=
"classname">CachedData</tt>, <tt class=
"classname">ConnectionServer</tt>, etc. These system objects are
accessed by polymorphic command objects, which receive the Context
as a parameter to their <tt class="methodname">execute()</tt>
method.</p>
</dd>
<dt><span class="term">Reuters Liffe Connect Data Router
(C++)</span></dt>
<dd>
<p>This system uses two context objects, split horizontally. The
first holds system data, log manager handles, a configuration
cache, COM parameters, and the second holds application data
exclusively.</p>
</dd>
<dt><span class="term">Jiffy XML Database Server (C++)</span></dt>
<dd>
<p>The Jiffy server has three context objects split along temporal
lines. One Context object exists for the length of the program run,
this encapsulates process wide context, items such as: log manager
handle, command line options and the database store index. A second
Context class is used to represent data associated with
connections. Each TCP connection is assigned a session context to
hold items such as the user id for the connection. Finally, the
underlying database from Sleepycat uses its own database-context
object to maintain state between database calls.</p>
<p>In this case, the database-context objects are short lived, each
one is limited to function call scope (although it will be passed
to several underlying functions in turn). A session context lives
for the duration of the TCP connection, while the process context
is created shortly after the application starts running and is
destroyed at the end of the program run.</p>
</dd>
<dt><span class="term">Enterprise Java Beans</span></dt>
<dd>
<p>Enterprise Java makes use of Session Beans and Context Beans
that encapsulate program state information. Although the objective
of Java Beans is to implement component based transaction
programming the most of the underlying forces are the same, namely:
substitutability of different beans, encapsulation of context from
server to client and clearly defined coupling.</p>
<p>However, the fourth force, <span class="emphasis"><em>avoid data
copying</em></span>, is absent. In the distributed environment for
which Java Beans is designed data copying is essential.</p>
</dd>
</dl>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e596" id="d0e596"></a>Related
Patterns</h2>
</div>
<div class="variablelist">
<dl>
<dt><span class="term"><span class="emphasis"><em>Command, Chain of
Responsibility and Objects for States.</em></span></span></dt>
<dd>
<p>Although the <tt class="classname">Command</tt> pattern is cited
here the same principles apply to any design based on the
dependency inversion principle using class hierarchies, e.g.
<span class="emphasis"><em>Chain of Responsibility</em></span>
(<a href="#Gamma1994">Gamma1994</a>), <span class=
"emphasis"><em>Objects for States</em></span> (<a href=
"#Henney2002">Henney2002</a>), etc. For each of these the hierarchy
provides the algorithm while the Context object(s) provide the
data.</p>
</dd>
<dt><span class="term"><span class=
"emphasis"><em>Singleton</em></span></span></dt>
<dd>
<p><span class="emphasis"><em>Encapsulate Context</em></span> may
be a useful alternative to <span class=
"emphasis"><em>Singleton</em></span> (<a href=
"#Gamma1994">Gamma1994</a>) in many program designs.</p>
</dd>
<dt><span class="term"><span class=
"emphasis"><em>Observer</em></span></span></dt>
<dd>
<p><span class="emphasis"><em>Encapsulate Context</em></span> may
be contrasted with <span class="emphasis"><em>Observer</em></span>
(<a href="#Gamma1994">Gamma1994</a>). Like the Subject in
<span class="emphasis"><em>Observer</em></span> the Context class
is a central repository of data. Like <span class=
"emphasis"><em>Observer</em></span> there is a many to one
relationship. However, the critical difference lies in the updating
mechanics.</p>
<p>The subject in <span class="emphasis"><em>Observer</em></span>
knows its observers, when it is updated it will update all its
observers. This satisfies the motivation for the pattern that seeks
to keep two, or more, objects consistent. Thus, when one
<span class="emphasis"><em>Observer</em></span> changes, and hence
changes the Subject the other <span class=
"emphasis"><em>Observer</em></span>s must be informed. In effect,
Subject is an active participant in the execution of the
program.</p>
<p>In <span class="emphasis"><em>Encapsulate Context</em></span>
there is no requirement on the Context class to inform its clients
that something has changed. Indeed, it doesn't know who its clients
are so it cannot inform them. <span class=
"emphasis"><em>Encapsulate Context</em></span> keeps the various
objects consistent by centralising the data. It is essentially
passive during execution.</p>
<p>While there is obvious transformation for turning a Context
object into a Subject, and hence <span class=
"emphasis"><em>Encapsulate Context</em></span> into an <span class=
"emphasis"><em>Observer</em></span> pattern, and vice versa, there
are fundamentally different motivations and forces underlying the
two patterns.</p>
</dd>
<dt><span class="term"><span class=
"emphasis"><em>Monitor</em></span></span></dt>
<dd>
<p>As noted above (Consequences section), in multi-threaded systems
mutex control can be added to <span class=
"emphasis"><em>Encapsulate Context</em></span> to assist with
synchronisation issues. In this the pattern is acting like
Schmidt's <span class="emphasis"><em>Monitor Object</em></span>
(<a href="#Schmidt2000">Schmidt2000</a>). While this can provide a
simple way to synchronise access to resources it is not without a
cost.</p>
<p>Firstly, by using the context class as a monitor introduces
pressure to perform more processing within the monitor class. This
contributes to the Blob tendencies already described.</p>
<p>Secondly, the consequences encountered by <span class=
"emphasis"><em>Monitor Object</em></span> are introduced into the
design. Specifically, the liabilities associated with <span class=
"emphasis"><em>Monitor Object</em></span> need to be recognised,
i.e. limited scalability, complicated extensibility semantics,
inheritance anomaly and nested monitor lockout.</p>
<p>Readers are strongly advised to read Schmidt before using this
<span class="emphasis"><em>Encapsulate Context</em></span> as a
synchronisation point.</p>
</dd>
<dt><span class="term"><span class="emphasis"><em>Arguments
Object</em></span></span></dt>
<dd>
<p>This pattern shares much in common with Nobel's <span class=
"emphasis"><em>Arguments Object</em></span> pattern (<a href=
"#Nobel1997">Nobel1997</a>). The key difference is that Nobel
suggests the pattern as a code level pattern for reducing the
number of parameters passed to a function, while <span class=
"emphasis"><em>Encapsulate Context</em></span> advocates using the
same paradigm as a high level feature to wrap the state of the
system.</p>
</dd>
<dt><span class="term"><span class="emphasis"><em>Introduce
Parameter Object</em></span></span></dt>
<dd>
<p>Both the <span class="emphasis"><em>Encapsulate
Context</em></span> and <span class="emphasis"><em>Arguments
Object</em></span> patterns resemble Fowler's <span class=
"emphasis"><em>Introduce Parameter Object</em></span> refactoring
pattern (<a href="#Fowler2000">Fowler2000</a>). However, Fowler
introduces this as only a refactoring pattern without discussion of
the issues involved in grouping data or alternative solutions. It
is possible to view Fowler's pattern as an application of either
<span class="emphasis"><em>Encapsulate Context</em></span> or
<span class="emphasis"><em>Arguments Object</em></span> when
refactoring code.</p>
</dd>
<dt><span class="term">Open Arguments</span></dt>
<dd>
<p>Some of the motivations of <span class=
"emphasis"><em>Encapsulate Context</em></span> are shared with
<span class="emphasis"><em>Open Arguments</em></span> (<a href=
"#Patow2003">Patow2003</a>). Both aim to provide a consistent
interface through which, diverse parts of a system may access
parameters. The focus of <span class="emphasis"><em>Open
Arguments</em></span> is internal mechanisms of the context object
and how this object may support a dynamic set of parameters at
run-time. In contrast, <span class="emphasis"><em>Encapsulate
Context</em></span> focuses on parameter passing at compile-time.
<span class="emphasis"><em>Open Arguments</em></span> considers a
parameter block which stored the various parameters, this has clear
parallels with the context class in <span class=
"emphasis"><em>Encapsulate Context</em></span>. The two patterns do
not exclude one another, and under the right circumstances may be
complementary.</p>
</dd>
</dl>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e784" id=
"d0e784"></a>Discussion</h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e787" id="d0e787"></a>Separating
Data</h3>
</div>
<p>At first glance <span class="emphasis"><em>Encapsulate
Context</em></span> may seem counter to the principles of
object-orientation, this is not so. Instead we are separating the
data into that which (a) truly belongs to a given object (e.g.
market price and quantity) and (b) that which is owned the system
as a whole. There is a casual similarity with the separation of
algorithm and container used by the Standard Template Library.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e795" id="d0e795"></a>Instantiation
Issues</h3>
</div>
<p>While this paper notes the instantiation problems associated
with global objects it does not provide an in-depth discussion or
offer detailed solutions. To do so is beyond the scope of this
pattern. However, it is suggested that some of these problems can
be alleviated by application of the <span class=
"emphasis"><em>Encapsulate Context</em></span> pattern.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e803" id="d0e803"></a>Testing</h3>
</div>
<p>With designs based on <span class="emphasis"><em>Encapsulate
Context</em></span> we may arrange for artificially configured
context objects to used for testing. For example, a test harness
could create a context object and populate with data to simulate a
scenario we wished to test, the test can then be run without to see
how the system behaves in these conditions.</p>
<p>Extending this ideas we can imagine two versions of the
<tt class="classname">MarketContext</tt> class, one of which
validates all inputs and one that is optimised for speed.
Alternatively, a Context class could load test data to create a
specific test scenario, or dump their &quot;state&quot; to file at the end of
a test - or in the event of program failure.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e816" id="d0e816"></a>Aspect Oriented
Programming</h3>
</div>
<p>Aspect oriented programming may provide an alternative means to
resolving some of the forces which produce this pattern. The data
within the Context class certainly seems to cross-cut the systems
concerned. The logger functionality is both a core example for both
Aspect documentation and this pattern. Since C++ does not currently
support Aspects, nor are they a standard part of Java, they cannot
be regarded as a common solution to this problem and forces.</p>
<p>The main difference appears to centre on the method of passing
the context object to the function. This pattern assumes that the
context object is passed by way of a function parameter, however,
beyond this assumption the concept of bundling the context into one
object is still applicable. The key difference is the mechanism for
accessing the context object.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e823" id="d0e823"></a>Pre and Post
Conditions</h3>
</div>
<p>By their nature, context objects represent the state of the
system. This makes them very good places to make uses of pre and
post conditions to validate system state. Indeed, developers using
context objects should be encouraged to use pre and post
conditions.</p>
<p>Use of such pre and post conditions is regarded by many as good
programming practice. Used as comments these can help developers
reason about the state of the system, used as compiler enforced
checks (e.g. macros in C++, conditionals in C#) the system can
perform a degree of self validation as well as helping programmers
reason.</p>
<p>Pre and post conditions could be placed within the context
objects &quot;getter and setter&quot; functions to validate the state of the
object, or used by functions accepting context objects to ensure
the program is in a suitable state for the function.</p>
<p>Use of such conditions to check state of the system is common
practice formal methods systems, e.g. VDM (<a href=
"#Jones1986">Jones1986</a>) and Z (<a href=
"#Wordsworth1992">Wordsworth1992</a>). Such languages specify a
&quot;state&quot; for the system before and after and operation - the program
state in VDM parlance. Further research is need on whether
<span class="emphasis"><em>Encapsulate Context</em></span> pattern
can be useful in development of formal methods based systems.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e843" id="d0e843"></a>Value Data or
Reference Data</h3>
</div>
<p>The solution section, above, notes that care should be taken
where reference and value type data is mixed within a single
Context object. Such mixing may be a signal that refactoring may be
required, and that the Context object should be split
horizontally.</p>
<p>However, Context objects observed in actual system frequently
mix these data types. While this may indicate poor design it also
reflects the fact that Context objects may be required to group
various types of data with different reference characteristics.
This fact may also indicate that the pattern has been introduced to
a system as the result of refactoring and that other parts of the
system have not been refactored yet.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e850" id="d0e850"></a>Genesis of a
Pattern Language - Further Research</h2>
</div>
<p>Many of the issues raised in the discussion section suggest
further variations of this pattern beyond those outlined already.
It is also possible to see how, taken together, <span class=
"emphasis"><em>Arguments Object</em></span>, <span class=
"emphasis"><em>Introduce Parameter Object</em></span>, <span class=
"emphasis"><em>Singleton</em></span>, <span class=
"emphasis"><em>Open Arguments</em></span> and <span class=
"emphasis"><em>Encapsulate Context</em></span> may represent part
of an entire pattern language. We may tentatively label this
pattern language <span class="emphasis"><em>Context
Objects</em></span>.</p>
<p>For example, <span class="emphasis"><em>Singleton</em></span>
could be redefined as an example of <span class=
"emphasis"><em>Encapsulate Context</em></span> where there is only
one instance of the <span class="emphasis"><em>Context
Object</em></span>, and the object is accessed via a global
variable instead of via parameter passing.</p>
<p>There are four groupings within which to consider variation
within the <span class="emphasis"><em>Context Objects</em></span>
pattern language:</p>
<div class="variablelist">
<dl>
<dt><span class="term">Access Mechanism</span></dt>
<dd>
<p>Function parameter passing is used in <span class=
"emphasis"><em>Encapsulate Context</em></span> to make the Context
object accessible. In contrast, <span class=
"emphasis"><em>Singleton</em></span> uses a global access point.
Thread local storage has been suggested as an alternative access
mechanism for multi-threaded systems. A further access mechanism,
where available, is the Point Cut provided by AspectJ and other
aspect oriented languages.</p>
</dd>
<dt><span class="term">Context Lifetime</span></dt>
<dd>
<p>While <span class="emphasis"><em>Singletons</em></span> are
generally instantiated for the lifetime of a program run, Nobel's
<span class="emphasis"><em>Arguments Objects</em></span> are more
ephemeral, being created and destroyed in a short space of time. By
extending the consideration of the temporal aspects - described
above for <span class="emphasis"><em>Encapsulate
Context</em></span> - more pattern variations are possible.</p>
</dd>
<dt><span class="term">Cardinality of Context</span></dt>
<dd>
<p>Related to the discussion of lifetime is the issue of
cardinality of Context objects. Obviously in cases such as
<span class="emphasis"><em>Argument Object</em></span> it is of
little importance whether one or one hundred Context objects
co-exist. However, in some cases it may be important to limit the
number of Context objects within a system, for example, we may wish
to limit each thread to one instance of an object, or limit a whole
program to one Context object corresponding to the mouse state.</p>
</dd>
<dt><span class="term">Internal Implementation</span></dt>
<dd>
<p><span class="emphasis"><em>Encapsulate Context</em></span>
assumes a fixed internal state where data elements are hard coded
and fixed at compile time. In contrast <span class=
"emphasis"><em>Open Arguments</em></span> allows the content of the
Context to change at run time. As already noted both patterns share
other similarities and thus may belong to a common language. In
this case, the internal representation of data can have a
significant effect on system design.</p>
</dd>
</dl>
</div>
<p>The creation of a <span class="emphasis"><em>Context
Objects</em></span> pattern language is beyond the scope of this
paper. However, it is clear that such a language could unify
existing patterns and probably help identify more patterns.</p>
<p>The author looks forward to hearing about such a project and is
more than willing to participate in such an endeavour.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e944" id="d0e944"></a>More
Examples</h2>
</div>
<p>The examples presented are given in C++ although it is expected
that the pattern is generally applicable to all languages. The
author looks forward to hearing of implementations in Java and C#
especially</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e949" id="d0e949"></a>Summary</h2>
</div>
<p>In any non-trivial system there will be a number of data
elements that are widely used throughout the program, e.g. log
manager and the application data model. Typically these will be
classes in their own right and accessed through handles (references
or pointers.) Since global data is regarded as poor practice it is
likely that these handles will be passed by way of function call
parameters. However, this technique can soon lead to long parameter
lists which are not only difficult to understand but tend to make
the program more fragile.</p>
<p>Therefore, we create a context class that encapsulates these
data elements, and pass a handle to this object to the diverse
functions.</p>
<p>While similar techniques have been suggested by others (e.g.
<a href="#Nobel1997">Nobel1997</a>, <a href=
"#Fowler2000">Fowler2000</a>) this pattern discusses the forces and
consequences when applied system wide. This can bring considerable
benefits to a design, but if used recklessly can result in a number
of known anti-patterns.</p>
<p>Rather than use a single context class it may be appropriate to
design a system with several. These are divided along temporal,
horizontal or vertical lines to ensure that each is consistent and
promotes good design.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e966" id=
"d0e966"></a>Acknowledgements</h2>
</div>
<p>This pattern was the result of a conversation on the <tt class=
"literal">accu-general</tt> mailing list entitled: &quot;overload 49 and
state&quot; with significant contributions from Kevlin Henney and Josh
Walker, running from 18th June 2002. I am grateful to Kevlin for
acting as initial pattern shepherd and Josh for reviewing the
results and providing an additional example. The paper was further
shepherded by Frank Buschmann in April 2003 for submission to
EuroPlop. Again, I am most grateful to Frank for his time and
interest.</p>
<p>In addition, I am most grateful to all in Workshop D at EuroPLoP
2003 for their many varied and useful comments concerning the
pattern, their support and their suggestions for improvement.</p>
<div class="sidebar informaltable">
<table border="1" cellspacing="0">
&lt;colgroup&gt;
&lt;col&gt;
&lt;col&gt;&lt;/colgroup&gt;
&lt;thead&gt;
<tr>
<th colspan="2" align="center">Principles and Patterns
Glossary</th>
</tr>
&lt;/thead&gt;
&lt;tbody&gt;
<tr>
<td><span class="bold"><b>Pattern Name</b></span></td>
<td><span class="bold"><b>Description</b></span></td>
</tr>
<tr>
<td>Arguments Object (Nobel, 1997)</td>
<td>
<p>&quot;Large protocols [interfaces] are easy to use because they offer
a large amount of behaviour to their clients. Unfortunately, they
are often difficult or time consuming to implement, and for client
programmers to learn. [...]</p>
<p>Therefore: make an arguments object to capture the common parts
of the protocol.&quot;</p>
</td>
</tr>
<tr>
<td>Blob (Brown, 1998, p.73)</td>
<td>
<p>&quot;The <span class="emphasis"><em>Blob</em></span> is found in
designs where one class monopolizes the processing, and other
classes primarily encapsulate data. This AntiPattern is
characterized by a class diagram composed of a single complex
controller class surrounded by simple data classes, [...]</p>
<p>Architectures with the <span class=
"emphasis"><em>Blob</em></span> have separated process from data;
in other words they are procedural-style rather than object
oriented architectures.&quot;</p>
</td>
</tr>
<tr>
<td>Chain of Responsibility (Gamma, 1994, p.223)</td>
<td>&quot;Avoid coupling the sender of a request to its receiver by
giving more than one object a chance to handle the request. Chain
the receiving objects and pass the request along the chain until an
object handles it.&quot;</td>
</tr>
<tr>
<td>Command (Gamma, 1994, p. 233)</td>
<td>&quot;Encapsulate a request as an object, thereby letting you
parameterize clients with different requests, queue or log
requests, and support undoable operations.&quot;</td>
</tr>
<tr>
<td>Hide Forbidden Globals (Green, 2001)</td>
<td>&quot;Since global variables are 'evil', define a structure to hold
all the things you'd put in globals. Call it something clever like
<span class="structname">EverythingYoullEverNeed</span>. Make all
functions take a pointer to this structure (call it <i class=
"parameter"><tt>handle</tt></i> to confuse things more). This gives
the impression that you're not using global variables, you're
accessing everything through a &quot;handle&quot;.</td>
</tr>
<tr>
<td>Introduce Parameter Object (Fowler, 2000, p.295)</td>
<td>&quot;Often you see a particular group of parameters that tend to be
passed together. Several methods may use this group, either on one
class or in several classes. Such a group of classes is a data
clump and can be replaced with an object that carried all the data.
It is worthwhile to turn these parameters into objects and just to
group the data together. This refactoring is useful because it
reduces long parameter lists, and long parameter lists are hard to
understand.&quot;</td>
</tr>
<tr>
<td>Liskov Substitution Principle (Liskov, 1988)</td>
<td>
<p>&quot;Functions that use pointers or references to base classes must
be able to use objects of derived classed without knowing it.&quot;
(Martin, 1996)</p>
<p>When using class hierarchies as a means of data abstraction,
sub-types must be able to fully substitute for the super-types.</p>
</td>
</tr>
<tr>
<td>Monitor Object (Schmidt, 2000, p.399)</td>
<td>Synchronises concurrent method execution to ensure that only
one method at a time runs within an object. It also allows an
object's methods to cooperatively schedule their execution
sequences.</td>
</tr>
<tr>
<td>Observer (Gamma, 1994, p.293)</td>
<td>&quot;Define a one-to-many dependency between objects so that when
one object changes state, all its dependants are notified and
updated automatically.&quot;</td>
</tr>
<tr>
<td>Objects for State (Henney, 2002)</td>
<td>&quot;Allow an object to alter its behaviour significantly by
delegating state-based behaviour to a separate object.&quot;</td>
</tr>
<tr>
<td>Open Arguments (Patow, 2003)</td>
<td>
<p>&quot;<span class="emphasis"><em>Open Arguments</em></span> is used
to create a generic interface for parameter passing, decoupling the
API declaration of the procedures and functions from the type and
number of the parameters they receive.</p>
<p>A parameter block is passed from function to function, the block
contains a dynamic store (often a map) of parameter names and
values.&quot;</p>
</td>
</tr>
<tr>
<td>Singleton (Gamma, 1994, p.127)</td>
<td>&quot;Ensure a class only has one instance, and provide a global
point of access to it.&quot;</td>
</tr>
&lt;/tbody&gt;
</table>
</div>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e1081" id=
"d0e1081"></a>Bibliography</h2>
</div>
<div class="bibliomixed"><a name="Brown1998" id="Brown1998"></a>
<p class="bibliomixed">[Brown1998] Brown, J. B., Malveau, R.C.,
McCormick, H.W., and Mowbray, T.J. (1998) <span class=
"citetitle"><i class="citetitle">Anti-Patterns</i></span>,
Wiley.</p>
</div>
<div class="bibliomixed"><a name="Fowler2000" id="Fowler2000"></a>
<p class="bibliomixed">[Fowler2000] Fowler, M. (2000) <span class=
"citetitle"><i class="citetitle">Refactoring</i></span>,
Addison-Wesley.</p>
</div>
<div class="bibliomixed"><a name="Gamma1994" id="Gamma1994"></a>
<p class="bibliomixed">[Gamma1994] Gamma, E., Helm, R., Johnson,
R., and Vlissides, J, (1994) <span class="citetitle"><i class=
"citetitle">Design Patterns</i></span>, Addison-Wesley.</p>
</div>
<div class="bibliomixed"><a name="Green2001" id="Green2001"></a>
<p class="bibliomixed">[Green2001] Green, R. 2001 <span class=
"citetitle"><i class="citetitle">How to Write Unmaintainable
Code</i></span>, <span class="bibliomisc"><a href=
"http://www.web-hits.org/txt/codingunmaintainable.html" target=
"_top">http://www.web-hits.org/txt/codingunmaintainable.html</a></span></p>
</div>
<div class="bibliomixed"><a name="Henney2002" id="Henney2002"></a>
<p class="bibliomixed">[Henney2002] Henney, K. 2002 <span class=
"citetitle"><i class="citetitle">Objects for State</i></span>,
<span class="bibliomisc"><a href="http://www.curbralan.com" target=
"_top">http://www.curbralan.com</a></span></p>
</div>
<div class="bibliomixed"><a name="Jones1986" id="Jones1986"></a>
<p class="bibliomixed">[Jones1986] Jones, C. B. (1986) <span class=
"citetitle"><i class="citetitle">Systematic Software Development
using VDM</i></span>.</p>
</div>
<div class="bibliomixed"><a name="Liskov1988" id="Liskov1988"></a>
<p class="bibliomixed">[Liskov1988] Liskov, B. (1988) &quot;Data
abstraction and hierarchy&quot;, <span class="citetitle"><i class=
"citetitle">SIGPLAN Notices</i></span>, 23, 17-34.</p>
</div>
<div class="bibliomixed"><a name="Martin1996" id="Martin1996"></a>
<p class="bibliomixed">[Martin1996] Martin, R. C. (1996) &quot;The
Liskov Substitution Principle&quot;, <span class="citetitle"><i class=
"citetitle">The C++ Report</i></span>, <span class=
"bibliomisc"><a href=
"http://www.objectmentor.com/resources/%20articles/lsp.pdf" target=
"_top">http://www.objectmentor.com/resources/
articles/lsp.pdf</a></span>.</p>
</div>
<div class="bibliomixed"><a name="Nobel1997" id="Nobel1997"></a>
<p class="bibliomixed">[Nobel1997] Nobel, J. 1997, &quot;Arguments and
Results&quot;, <span class="citetitle"><i class="citetitle">Pattern
Languages of Programming (PLoP) conference</i></span>, Washington
University, <span class="bibliomisc"><a href=
"http://citeseer.nj.nec.com/107777.html" target=
"_top">http://citeseer.nj.nec.com/107777.html</a></span></p>
</div>
<div class="bibliomixed"><a name="Patow2003" id="Patow2003"></a>
<p class="bibliomixed">[Patow2003] Patow, G., and Lyardet, F.
(2003) &quot;Open Arguments&quot;, <span class="citetitle"><i class=
"citetitle">EuroPLoP 2003</i></span>, proceedings pending
publication.</p>
</div>
<div class="bibliomixed"><a name="Schmidt2000" id=
"Schmidt2000"></a>
<p class="bibliomixed">[Schmidt2000] Schmidt, D., Stal, M.,
Rohnert, H., and Buschmann, F. (2000) &quot;Monitor Object&quot;, in
<span class="citetitle"><i class="citetitle">Pattern-Oriented
Software Architecture 3</i></span>, Wiley, pp. 399-422.</p>
</div>
<div class="bibliomixed"><a name="Wordsworth1992" id=
"Wordsworth1992"></a>
</div>
</div>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
