    <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  :: Patterns in C - Part 3: Strategy</title>
        <link>https://members.accu.org/index.php/journals/814</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">CVu Journal Vol 17, #3 - Jun 2005 + Design of applications and programs</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/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c96/">173</a>
                    (15)
<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/c67/">Design</a>
                    (236)
<br />

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

                    -                        <a href="https://members.accu.org/index.php/journals/c96+67/">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;Patterns in C - Part 3: Strategy</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 June 2005 05:00:00 +01:00 or Thu, 02 June 2005 05:00:00 +01:00</p>
<p><strong>Summary:</strong>&nbsp;<p>This part of the series will investigate a design pattern that adds flexibility to common software entities by letting clients customize and extend them without modifying existing code.</p>
</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e20" id="d0e20"></a></h2>
</div>
<p>Identifying and exploiting commonality is fundamental to
software design. By encapsulating and re-using common
functionality, the quality of the design rises above code
duplication and dreaded anti-patterns like copy-paste. This part of
the series will investigate a design pattern that adds flexibility
to common software entities by letting clients customize and extend
them without modifying existing code.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e24" id="d0e24"></a>Control Coupled
Customers</h2>
</div>
<p>To attract and keep customers, many companies offer some kind of
bonus system. In the example used in this article, a customer is
placed in one of three categories:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><span class="emphasis"><em>Bronze customers:</em></span> Get 2 %
reduction on every item bought.</p>
</li>
<li>
<p><span class="emphasis"><em>Silver customers:</em></span> Get 5 %
reduction on every item bought.</p>
</li>
<li>
<p><span class="emphasis"><em>Gold customers:</em></span> Get 10 %
off on all items and free shipping.</p>
</li>
</ul>
</div>
<p>A simple and straightforward way to implement a price
calculation based upon this bonus system is through conditional
logic.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e47" id="d0e47"></a>Listing 1:
Solution Using Conditional Logic</h3>
</div>
<pre class="programlisting">
typedef enum
{
   bronzeCustomer,
   silverCustomer,
   goldCustomer
} CustomerCategory;

double calculatePrice(
    CustomerCategory category,
    double totalAmount, 
    double shipping)
{
   double price = 0;
    /* Calculate the total price depending on
       customer category. */
    switch(category) {
     case bronzeCustomer:
           price = totalAmount * 0.98 + 
               shipping;
           break;
     case silverCustomer:
           price = totalAmount * 0.95 + 
               shipping;
           break;
     case goldCustomer:
           /* Free shipping for gold
              customers.*/
           price = totalAmount * 0.90;
           break;
     default: onError(&quot;Unsupported category&quot;);
     break;
    }
    return price;
}
</pre>
<p>Before further inspection of the design, I would like to point
out that representing currency as double may lead to marginally
inaccurate results. Carelessly handled, they may turn out to be
fatal to, for example, a banking system.</p>
<p>Further, security issues like a possible overflow should never
be ignored in business code. However, such issues have been
deliberately left out of the example in order not to lose the focus
on the problem in the scope of this article.</p>
<p>Returning to the code, even in this simplified example, it is
possible to identify three serious design problems with the
approach, that wouldn't stand up well in the real-world:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p><span class="emphasis"><em>Conditional logic</em></span>. The
solution above basically switches on a type code, leading to the
risk of introducing a maintenance challenge. For example, the above
mentioned security issues have to be addressed on more than one
branch leading to potentially complicated, nested conditional
logic.</p>
</li>
<li>
<p><span class="emphasis"><em>Coupling</em></span>. The client of
the function above passes a flag (category) used to control the
inner logic of the function. Page-Jones defines this kind of
coupling as &quot;control coupling&quot; and he concludes that control
coupling itself isn't the problem, but that it &quot;<span class=
"quote">often indicates the presence of other, more gruesome,
design ills</span>&quot; [<a href="#Page-Jones">Page-Jones</a>]. One
such design ill is the loss of encapsulation; the client of the
function above knows about its internals. That is, the knowledge of
the different customer categories is spread among several
modules.</p>
</li>
<li>
<p><span class="emphasis"><em>It doesn't scale</em></span>. As a
consequence of the design ills identified above, the solution has a
scalability problem. In case the customer categories are extended,
the inflexibility of the design forces modification to the function
above. Modifying existing code is often an error-prone
activity.</p>
</li>
</ol>
</div>
<p>The potential problems listed above, may be derived from the
failure of adhering to one, important design principle.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e82" id="d0e82"></a>The Open-Closed
Principle</h2>
</div>
<p>Although mainly seen in the context of object oriented
literature, the open-closed principle defines properties attractive
in the context of C too. The principle is summarized as
&quot;<span class="quote">Software entities (classes, modules,
functions, etc.) should be open for extension, but closed for
modification</span>&quot; [<a href="#Martin">Martin</a>].</p>
<p>According to the open-closed principle, extending the behaviour
of an ideal module is achieved by adding code instead of changing
the existing source. Following this principle not only minimizes
the risk of introducing bugs in existing, tested code but also
typically raises the quality of the design by introducing loose
coupling. Unfortunately, it is virtually impossible to design a
module in such a way that it is closed against all kinds of
changes. Even trying to design software in such a way would
overcomplicate the design far beyond suitability. Identifying the
modules to close, and the changes to close them against, requires
experience and a good understanding of the problem domain.</p>
<p>In the example used in this article, it would be suitable to
close the customer module against changes to the customer
categories. Identifying a pattern that lets us redesign the code
above in this respect seems like an attractive idea.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e97" id="d0e97"></a>STRATEGY</h2>
</div>
<p>The design pattern STRATEGY provides a way to follow and reap
the benefits of the open-closed principle. Design Patterns
[<a href="#Gamma-">Gamma-</a>] defines the intent of STRATEGY as
&quot;<span class="quote">Define a family of algorithms, encapsulate
each one, and make them interchangeable. Strategy lets the
algorithm vary independently from clients that use it</span>&quot;.
Related to the discussion above, the price calculations in the
different customer categories are that &quot;<span class="quote">family
of algorithms</span>&quot;. By applying the STRATEGY pattern, each one
of them gets fully encapsulated rendering the structure in Figure
1.</p>
<div class="figure"><a name="d0e111" id="d0e111"></a>
<div class="mediaobject c3"><img src=
"/var/uploads/journals/resources/Patterns_in_C_3.png" align="middle" alt=
"STRATEGY Pattern Structure"></div>
<p class="title c4">Figure 1. STRATEGY Pattern Structure</p>
</div>
<p>The context, in this example the <tt class=
"classname">Customer</tt>, does not have any knowledge about the
concrete categories anymore; the concrete strategy is typically
assigned to the context by the application. All price calculations
are delegated to the assigned strategy.</p>
<p>Using this pattern, the interface for calculating price adheres
to the open closed principle; it is possible to add or remove
categories without modifying the existing calculation algorithms or
the <tt class="classname">Customer</tt> itself.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e127" id=
"d0e127"></a>Implementation Mechanism</h2>
</div>
<p>When implementing the STRATEGY pattern in C, without language
support for polymorphism and inheritance, an alternative to the
object oriented features has to be found for the abstraction.</p>
<p>This problem is almost identical to the one faced when
implementing the STATE pattern [<a href=
"#Petersen172">Petersen172</a>], indicating that the same mechanism
may be used, namely pointers to functions. The possibility to
specify pointers to functions proves to be an efficient technique
for implementing dynamic behaviour.</p>
<p>In a C-implementation, the basic structure in the diagram
remains, but the interface is expressed as a declaration of a
pointer to function.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e139" id="d0e139"></a>Listing 2:
Strategy interface in <tt class=
"filename">CustomerStrategy.h</tt></h3>
</div>
<pre class="programlisting">
typedef double (*CustomerPriceStrategy)(
    double amount, double shipping);
</pre>
<p>The different strategies are realized as functions following the
signature specified by the interface. The privileges of each
customer category, the concept that varies, are now encapsulated
within their concrete strategy. Depending on the complexity and the
cohesion of the concrete strategies, the source code may be
organized as either one strategy per compilation unit or by
gathering all supported strategies in a single compilation unit.
For the simple strategies used in this example, the latter approach
has been chosen.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e148" id="d0e148"></a>Listing 3:
Interface to the Concrete Customer Categories in <tt class=
"filename">CustomerCategories.h</tt></h3>
</div>
<pre class="programlisting">
double bronzePriceStrategy(double amount,
    double shipping);

double silverPriceStrategy(double amount,
    double shipping);

double goldPriceStrategy(double amount,
    double shipping);
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e155" id="d0e155"></a>Listing 4:
Implementation of the Concrete Customer Strategies in <tt class=
"filename">CustomerCategories.c</tt></h3>
</div>
<pre class="programlisting">
/* In production code, all input should be
   validated and the calculations secured upon
   entry of each function.
*/
double bronzePriceStrategy(double amount,
    double shipping)
{
   return amount * 0.98 + shipping;
}

double silverPriceStrategy(double amount,
    double shipping)
{
   return amount * 0.95 + shipping;
}

double goldPriceStrategy(double amount,
    double shipping)
{
   /* Free shipping for gold customers. */
   return amount * 0.90;
}
</pre>
<p>Using the strategies, the context code now delegates the
calculation to the strategy associated with the customer.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e164" id="d0e164"></a>Listing 5:
<tt class="filename">Customer.c</tt></h3>
</div>
<pre class="programlisting">
#include &quot;CustomerStrategy.h&quot;
/* Other include files omitted... */
struct Customer
{
   const char* name;
   Address address;
   List orders;
   /* Bind the strategy to Customer. */
   CustomerPriceStrategy priceStrategy;
};

void placeOrder(struct Customer* customer,
    const Order* order)
{
   double totalAmount = customer-&gt;priceStrategy
(order-&gt;amount, order-&gt;shipping);
   /* More code to process the order&hellip; */
}
</pre>
<p>The code above solves the detected design ills. As the customer
now only depends upon the strategy interface, categories can be
added or removed without changing the code of the customer and
without the risk of introducing bugs into existing strategies. The
remaining open issue with the implementation is to specify how a
certain strategy gets bound to the customer.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e173" id="d0e173"></a>Binding the
Strategy</h2>
</div>
<p>The strategy may be supplied by the client of the customer and
bound to the customer during its creation, or an initial strategy
may be chosen by the customer itself. The former alternative is
clearly more flexible as it avoids the need for the customer to
depend upon a concrete strategy. The code below illustrates this
approach, using a customer implemented as a FIRST-CLASS ADT
[<a href="#Petersen171">Petersen171</a>].</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e181" id="d0e181"></a>Listing 6:
Binding Strategy Upon Creation, Customer.c</h3>
</div>
<pre class="programlisting">
CustomerPtr createCustomer(const char* name,
    const Address* address,
                           CustomerPriceStrategy priceStrategy)
{
   CustomerPtr customer = malloc(sizeof *
       customer);

   if(NULL != customer){
      /* Bind the initial strategy supplied by
         the client. */
      customer-&gt;priceStrategy = priceStrategy;

      /* Initialize the other attributes of
         the customer here. */
   }

   return customer;
}
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e186" id="d0e186"></a>Listing 7:
Client Code Specifying the Binding</h3>
</div>
<pre class="programlisting">
#include &quot;Customer.h&quot;
#include &quot;CustomerCategories.h&quot;

static CustomerPtr createBronzeCustomer(const
    char* name, const Address* address)
{
  return createCustomer(name, address,
      bronzePriceStrategy);
}
</pre>
<p>Depending on the problem at hand, a context may be re-bound to
another strategy. For example, as a customer gets promoted to the
silver category, that customer should get associated with the
<tt class="classname">silverPriceStrategy</tt>. Using the technique
of pointers to functions, a run-time change of strategy simply
implies pointing to another function.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e196" id="d0e196"></a>Listing 8:
Rebinding a Strategy, <tt class="filename">Customer.c</tt></h3>
</div>
<pre class="programlisting">
void changePriceCategory(CustomerPtr customer,
    CustomerPriceStrategy newPriceStrategy)
{
   assert(NULL != customer);
   customer-&gt;priceStrategy = newPriceStrategy;
}
</pre>
<p>Yet another alternative is to avoid the binding altogether and
let the client pass the different strategies to the context in each
function invocation. This alternative may be suitable in case the
context doesn't have any state memory. However, for our example,
which uses first-class objects, the opposite is true and the
natural abstraction is to associate the customer with a
price-strategy as illustrated above.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e205" id="d0e205"></a>Comparison of
STRATEGY and STATE</h2>
</div>
<p>When discussing the STRATEGY pattern, its relationship with the
pattern preceding it in the <i class="citetitle">Design
Patterns</i> [<a href="#Gamma-">Gamma-</a>] book deserves special
mention. The design patterns STATE [<a href="#Gamma-">Gamma-</a>]
[<a href="#Petersen172">Petersen172</a>] and STRATEGY are closely
related. Robert C. Martin puts it this way: &quot;<span class=
"quote">all instances of the State pattern are also instances of
the Strategy pattern, but not all instances of Strategy are
State</span>&quot; [<a href="#Martin">Martin</a>].</p>
<p>This observation leads us to a recommendation by John Vlissides,
co-author of <i class="citetitle">Design Patterns</i>, stating that
&quot;<span class="quote">Let the intents of the patterns be your guide
to their differences and not the class structures that implement
them</span>&quot; [<a href="#Vlissides">Vlissides</a>]. And indeed, even
though STATE and STRATEGY have a similar structure and use similar
mechanisms, they differ in their intent.</p>
<p>The STATE pattern focuses upon managing well-defined transitions
between discrete states, whereas the primary purpose with STRATEGY
is to vary the implementation of an algorithm.</p>
<p>Related to the example used in this article, had the categories
been based on the sum of money spent by a customer, STATE would
have been a better choice; the categories would basically
illustrate the lifecycle of a customer, as the transitions between
categories depend upon the history of the customer object itself.
The STATE pattern may be used to implement this behaviour as a
finite state machine.</p>
<p>On the other hand, in case the placement in a certain category
is the result of a membership fee, STRATEGY is a better
abstraction. It is still possible for a customer to wander between
different categories, but a transition to a new category doesn't
depend upon the history of that customer object.</p>
<p>Although not to be taken as a universal truth, a further
observation relates to the usage of these two patterns and their
relationships towards the client. STATE tends to be an internal
concern of the context and the existence of STATE is usually
encapsulated from the client. Contrasting this with STRATEGY, the
client usually binds a concrete strategy to its context.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e247" id=
"d0e247"></a>Consequences</h2>
</div>
<p>The main consequences of applying the STRATEGY pattern are:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>The benefits of the open-closed principle.</p>
<p>The design pattern STRATEGY offers great flexibility in that it
allows clients to change and control the behavior of an existing
module by implementing their own, concrete strategies. Thus, new
behavior is supported by adding new code instead of modifying
existing code.</p>
</li>
<li>
<p>Reduces complex, conditional logic.</p>
<p>Complex interactions may lead to monolithic modules littered
with conditional logic, potentially in the form of control
coupling. Such code tends to be hard to maintain and extend. By
encapsulating each branch of the conditionals in a strategy, the
STRATEGY pattern eliminates conditional logic.</p>
</li>
<li>
<p>Allows different versions of the same algorithm.</p>
<p>The non-functional requirements on a module may typically vary
depending on its usage. The typical trade-off between an algorithm
optimized for speed versus one optimized with respect to memory
usage is classical. Using the Strategy pattern, the choice of
trade-offs may be delegated to the user (&quot;Strategies can provide
different implementations of the same behavior&quot; [<a href=
"#Gamma-">Gamma-</a>]).</p>
</li>
<li>
<p>An extra level of indirection.</p>
<p>The main issue with this consequence arises as data from the
context has to be obtained in a strategy. As all functions used as
strategies have to follow the same signature, simply adding
potentially unrelated parameters lowers the cohesion. Implementing
the context as a FIRST-CLASS ADT [<a href=
"#Petersen171">Petersen171</a>] may solve this problem as it
reduces the parameters to a single handle.</p>
<p>With the FIRST-CLASS ADT approach, the knowledge about the data
of interest is encapsulated within each strategy and obtained
through the handle to the FIRST-CLASS ADT. A careful design should
strive to keep the module implemented as a FIRST-CLASS ADT highly
cohesive and avoid having it decay into a repository of unrelated
data needed by different strategies (such a design ill typically
indicates that the wrong abstraction has been chosen). Similarly,
in case the flexibility of the STRATEGY pattern isn't needed and
the problem may be solved by conditional logic that is easy to
follow, the latter is probably a better choice.</p>
</li>
</ol>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e281" id="d0e281"></a>Example of
Use</h2>
</div>
<p>STRATEGY may prove useful for specifying policies in framework
design. Using STRATEGY, clients may parameterize the
implementation.</p>
<p>For example, error-handling is typically delegated to the
application. Such a design may be realized by letting the client
provide a strategy to be invoked upon an error. By those means, the
error may be handled in an application specific manner, which may
stretch between simply ignoring the error to logging it or even
reboot the system.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e288" id="d0e288"></a>Next
Time</h2>
</div>
<p>The next article will look further into dependency management
and continue to build on the open-closed principle by introducing a
C implementation of the OBSERVER [<a href="#Gamma-">Gamma-</a>]
pattern.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e296" id=
"d0e296"></a>Acknowledgements</h2>
</div>
<p>Many thanks to Magnus Adamsson, Tord Andersson, Drago Krznaric
and Andr&eacute; Saitzkoff for their feedback.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e301" id="d0e301"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Martin" id="Martin"></a>
<p class="bibliomixed">[Martin] Robert C. Martin, &quot;<span class=
"citetitle"><i class="citetitle">Agile Software
Development</i></span>&quot;, Prentice Hall</p>
</div>
<div class="bibliomixed"><a name="Gamma-" id="Gamma-"></a>
<p class="bibliomixed">[Gamma-] Gamma, E., Helm, R., Johnson, R.,
and Vlissides, J, &quot;<span class="citetitle"><i class=
"citetitle">Design Patterns</i></span>&quot;, Addison-Wesley</p>
</div>
<div class="bibliomixed"><a name="Petersen171" id=
"Petersen171"></a>
<p class="bibliomixed">[Petersen171] Adam Petersen, &quot;Patterns in C,
part 1&quot;, C Vu 17.1</p>
</div>
<div class="bibliomixed"><a name="Petersen172" id=
"Petersen172"></a>
<p class="bibliomixed">[Petersen172] Adam Petersen, &quot;Patterns in C,
part 2: STATE&quot;, C Vu 17.2</p>
</div>
<div class="bibliomixed"><a name="Page-Jones" id="Page-Jones"></a>
<p class="bibliomixed">[Page-Jones] Meilir Page-Jones,
&quot;<span class="citetitle"><i class="citetitle">The Practical Guide
to Structured Systems Design</i></span>&quot;, Prentice Hall</p>
</div>
<div class="bibliomixed"><a name="Vlissides" id="Vlissides"></a>
<p class="bibliomixed">[Vlissides] John Vlissides, &quot;<span class=
"citetitle"><i class="citetitle">Pattern Hatching</i></span>&quot;,
Addison-Wesley</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
