    <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 1</title>
        <link>https://members.accu.org/index.php/journals/788</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, #1 - Feb 2005 + 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/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c98/">171</a>
                    (9)
<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/c98-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c98+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;Patterns in C - Part 1</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 03 February 2005 13:16:10 +00:00 or Thu, 03 February 2005 13:16:10 +00:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e20" id="d0e20"></a></h2>
</div>
<p>Over the last ten years, the pattern format has gained a
tremendous popularity as the format used for capturing experience.
One of the reasons for this popularity is the unique success of the
classic book <i class="citetitle">Design Patterns</i> by the Gang
of Four [<a href="#GoF">GoF</a>]. The <i class="citetitle">Design
Patterns</i> book definitively served the community by spreading
the word about patterns.</p>
<p>Today, patterns in the software industry aren't limited to
design; there exists a broad range of patterns, covering analysis
patterns, patterns for organizations, patterns for testing,
etc.</p>
<p>As most patterns are described in the context of an object
oriented design, one is easily led to believe that patterns require
a language with support for object orientation. By browsing a
popular online bookstore, I noticed a lot of language specific
pattern literature: design patterns in Java, C#, Smalltalk and
other popular object oriented languages. But, where is the one
targeting the unique implementation constraints and techniques for
the C language? Isn't it possible to use patterns in the
development of C programs or doesn't it add any benefits?</p>
<p>An important thing to realize about patterns is that they are
neither a blueprint of a design, nor are they tied to any
particular implementation. By those means, shouldn't it be possible
to find mechanisms fitting the paradigm of C, letting C programmers
benefit from the experience captured by patterns?</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e39" id="d0e39"></a>What You Will
Experience in This Series ...</h2>
</div>
<p>It is my belief that C programmers can benefit from the growing
catalogue of patterns. This series will focus on the following
areas:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><span class="bold"><b>Implementation techniques</b></span>. I
will present a number of patterns and demonstrate techniques for
implementing them in the context of the C language. In case I'm
aware of common variations in the implementation, they will be
discussed as well. The implementations included should however not
by any means be considered as a final specification. Depending on
the problem at hand, the implementation trade-offs for every
pattern has to be considered.</p>
</li>
<li>
<p><span class="bold"><b>Problem solved</b></span>. Patterns solve
problems. Without any common problem, the &quot;pattern&quot; may simply not
qualify as a pattern. Therefore I will present the main problem
solved by introducing the pattern and provide examples of problem
domains where the pattern can be used.</p>
</li>
<li>
<p><span class="bold"><b>Consequences on the design</b></span>.
Every solution implies a set of trade-offs. Therefore each article
will include the consequences on the quality of the design by
applying the pattern.</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e60" id="d0e60"></a>... And What
You Won't</h2>
</div>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><span class="bold"><b>Object oriented feature
emulation</b></span>. The pattern implementations will not be based
on techniques for emulating object oriented features such as
inheritance or C++ virtual functions. In my experience, these
features are better left to a compiler; manually emulating such
techniques are obfuscating at best and a source of hard to track
down bugs at worst. Instead, it is my intent to present
implementations that utilize the strengths of the abstraction
mechanisms already included in the C language.</p>
</li>
<li>
<p><span class="bold"><b>In depth discussion of
patterns</b></span>. As the focus in these articles will be on the
implementation issues in C, the articles should be seen as a
complement to the pattern descriptions. By those means, this series
will not include exhaustive, in depth treatment of the patterns.
Instead I will provide a high-level description of the pattern and
reference existing work, where a detailed examination of the
pattern is found.</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e74" id="d0e74"></a>Pattern
Categories</h2>
</div>
<p>The patterns described in this series will span the following
categories.</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><span class="bold"><b>Architectural patterns</b></span>. Frank
Buschmann defines such a pattern as &quot;<span class="quote">a
fundamental structural organization schema for software systems. It
provides a set of predefined subsystems, specifies their
responsibilities, and includes rules and guidelines for organizing
the relationships between them</span>&quot; [<a href=
"#Buschmann-">Buschmann-</a>].</p>
</li>
<li>
<p><span class="bold"><b>Design patterns</b></span>. These
typically affect the subsystem or component level. Most patterns
described in this series will be from this category, including
patterns described in the classic <i class="citetitle">Design
Patterns</i> [<a href="#GoF">GoF</a>] book.</p>
</li>
<li>
<p><span class="bold"><b>Language level patterns</b></span>. This
is the lowest level of the pattern-categories, also known as
idioms. A language level pattern is, as its name suggests, mainly
unique to one particular programming language. One simple, classic
example is the <tt class="function">strcpy</tt> version from
Kernighan and Ritchie [<a href="#Kernighan-">Kernighan-</a>].</p>
<pre class="programlisting">
void strcpy(char *s, char *t) {
   while(*s++ = *t++);
}
</pre></li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e115" id="d0e115"></a>The
Foundation</h2>
</div>
<p>Our journey through the patterns will start with a language
level pattern that decouples interface from implementation, thus
improving encapsulation and providing loose dependencies.</p>
<p>This pattern will lay the foundation for many of the subsequent
parts of this series.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e122" id="d0e122"></a>FIRST-CLASS
ADT Pattern</h2>
</div>
<p>It's getting close to the project deadline as the project
manager rushes into your office. &quot;They found some problem with your
code&quot;, he says with a stressed voice. &quot;According to the test-team,
you cannot register more than 42 orders for a given customer.
Sounds strange, doesn't it?&quot;</p>
<p>Darn. You knew it. Those hard coded limits. &quot;Oh, I'll have a
look at it&quot;, you reply softly. &quot;Fine, I expect the problem to be
solved tomorrow&quot;, the manager mumbles as he leaves your office.</p>
<p>&quot;No problem&quot;, you reply, well confident that the design of the
customer routines are highly modular and clearly implemented (after
all, you've implemented it yourself).</p>
<p>You launch your favourite code-editor and open a file with the
following content:</p>
<pre class="programlisting">
/* Customer.h */
&lt; include guards and include files &gt;
#define MAX_NO_OF_ORDERS 42
/* Internal representation of a customer. */
typedef struct {
  const char* name;
  Address address;
  size_t noOfOrders;
  Order orders[MAX_NO_OF_ORDERS];
} Customer;
void initCustomer(Customer* theCustomer,
          const char* name, const Address* address);
void placeOrder(Customer* customer,
                const Order* order);
/* and a lot of other related functions */
</pre>
<p>A quick glance reveals the problem. Simply increasing <tt class=
"constant">MAX_NO_OF_ORDERS</tt> would do, wouldn't it? But what's
the correct value for it? Is it 64, 128, maybe even 2048 or some
other magic number? Should customers with one, single order
allocate space for, let's say, 2047 non-existing orders?</p>
<p>As you think of it, you realize that the current solution
doesn't scale well enough. Clearly, you need another algorithm. You
recall that a linked list exists in the company's code library. A
linked list must do the trick. However, this means changing the
internal structure of the Customer.</p>
<p>No problem, it looks like you thought of everything; the clients
of the customer module simply use the provided functions for all
access of the customer structure. Updating those functions should
be enough, shouldn't it?</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e144" id="d0e144"></a>Information
Hiding</h2>
</div>
<p>Well, in an ideal world the change would be isolated to the one,
single module. Given the interface above, clients depend upon the
internal structure in at least one way. At worst, the clients alter
the internals of the data structure themselves leading to costly
changes of all clients.</p>
<p>This can be prevented by frequent code-inspections and
programmer discipline. In any case, we still have the compile-time
dependencies and after changes, a re-compile of all clients is
required and the compilation time may be significant in large
systems.</p>
<p>The FIRST-CLASS ADT pattern will eliminate both dependency
problems. The pattern provides us with a method of separating
interface from implementation, thus achieving true information
hiding.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e153" id="d0e153"></a>Definition of
a FIRST-CLASS ADT</h2>
</div>
<p>ADT stands for Abstract Data Type and it is basically a set of
values and operations on these values. The ADT is considered
first-class if we can have many, unique instances of it.</p>
<p>Sounds close to the interface listed in the introductory example
above, doesn't it? However, the data type in the example is not
abstract as it fails to hide its implementation details. In order
to make it truly abstract, we have to utilize a powerful feature of
C - the ability to specify incomplete types.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e160" id="d0e160"></a>Incomplete
Types</h2>
</div>
<p>The C standard [<a href="#C_Standard">C_Standard</a>] allows us
to declare objects of incomplete types in a context where there
sizes aren't needed. In our example implementation, we are
interested in one property of incomplete types - the possibility to
specify a pointer to an incomplete type (please note that the
pointer itself is not of an incomplete type).</p>
<pre class="programlisting">
/* A pointer to an incomplete type (hides the
   implementation details). */
typedef struct Customer* CustomerPtr;
</pre>
<p>Instances of this pointer will serve as a handle for the clients
of a First-Class ADT. This mechanism enforces the constraint on
clients to use the provided interface functions because there is no
way a client can access a field in the <span class=
"structname">Customer</span> structure (the C language does not
allow an incomplete type to be dereferenced).</p>
<p>The type is considered complete as soon as the compiler detects
a subsequent specifier, with the same tag, and a declaration list
containing the members.</p>
<pre class="programlisting">
/* The struct Customer is an incomplete type. */
typedef struct Customer* CustomerPtr;
/* Internal representation of a customer. */
struct Customer {
  const char* name;
  Address address;
  size_t noOfOrders;
  Order orders[42];
};
/* At this point, struct Customer is considered
   complete. */
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e179" id="d0e179"></a>Object
Lifetime</h2>
</div>
<p>Before we dive into the implementation of an ADT, we need to
consider object creation and destruction.</p>
<p>As clients only get a handle to the object, the responsibility
for creating it rests upon the ADT. The straightforward approach is
to write one function that encapsulates the allocation of an object
and initializes it. In a similar way, we define a function for
destructing the object.</p>
<pre class="programlisting">
/* Customer.h */
&lt; includes and include guards as before &gt;
/* A pointer to an incomplete type (hides the
   implementation details). */
typedef struct Customer* CustomerPtr;
/* Create a Customer and return a handle to it. */
CustomerPtr createCustomer(const char* name,
                           const Address* address);
/* Destroy the given Customer. All handles to it
   will be invalidated. */
void destroyCustomer(CustomerPtr customer);

/* Customer.c */
#include &quot;Customer.h&quot;
#include &lt;stdlib.h&gt;
struct Customer {
  const char* name;
  Address address;
  size_t noOfOrders;
  Order orders[42];
};
CustomerPtr createCustomer(const char* name,
                           const Address* address) {
  CustomerPtr customer = malloc(sizeof * customer);
  if(customer) {
    /* Initialize each field in the customer. */
  }
  return customer;
}
void destroyCustomer(CustomerPtr customer) {
  /* Perform clean-up of the customer internals,
     if necessary. */
  free(customer);
}
</pre>
<p>The example above uses <tt class="function">malloc</tt> to
obtain memory. In many embedded applications, this may not be an
option. However, as we have encapsulated the memory allocation
completely, we are free to choose another approach. In embedded
programming, where the maximum number of needed resources is
typically known, the simplest allocator then being an array.</p>
<pre class="programlisting">
/* Example of a static approach for memory
   allocation. */
#define MAX_NO_OF_CUSTOMERS 42
static struct Customer objectPool[MAX_NO_OF_CUSTOMERS];
static size_t numberOfObjects = 0;
CustomerPtr createCustomer(const char* name,
                           const Address* address) {
  CustomerPtr customer = NULL;
  if(numberOfObjects &lt; MAX_NO_OF_CUSTOMERS) {
    customer = &amp;objectPool[numberOfObjects++];
    /* initialize the object */
  }
  return customer;
}
</pre>
<p>In case deallocation is needed, an array will still do, but a
more sophisticated method for keeping track of &quot;allocated&quot; objects
will be needed. However, such an algorithm is outside the scope of
this article.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e197" id="d0e197"></a>Copy
Semantics</h2>
</div>
<p>As clients only use a handle, which we have declared as a
pointer, to the ADT, the issue of copy semantics boils down to
pointer assignment. Whilst efficient, in terms of run-time
performance, copies of a handle have to be managed properly; the
handles are only valid as long as the real object exists.</p>
<p>In case we want to copy the real object, and thus create a new,
unique instance of the ADT, we have to define an explicit copy
operation.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e204" id="d0e204"></a>Dependencies
Managed</h2>
</div>
<p>With the interface above, the C language guarantees us that the
internals of the data structure are encapsulated in the
implementation with no possibility for clients to access the
internals of the data structure.</p>
<p>Using the FIRST-CLASS ADT, the compile-time dependencies on
internals are removed as well; all changes of the implementation
are limited to, well, the implementation, just as it should be. As
long as no functions are added or removed from the interface, the
clients do not even have to be re-compiled.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e211" id=
"d0e211"></a>Consequences</h2>
</div>
<p>The main consequences of applying the FIRST-CLASS ADT pattern
are:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p><span class="bold"><b>Improved encapsulation</b></span>. With
the FIRST-CLASS ADT pattern we decouple interface and
implementation, following the recommended principle of programming
towards an interface, not an implementation.</p>
</li>
<li>
<p><span class="bold"><b>Loose coupling</b></span>. As illustrated
above, all dependencies on the internals of the data structure are
eliminated from client code.</p>
</li>
<li>
<p><span class="bold"><b>Controlled construction and
destruction</b></span>. The FIRST-CLASS ADT pattern gives us full
control over the construction and destruction of objects, providing
us with the possibility to ensure that all objects are created in a
valid state. Similarly, we can ensure proper de-allocation of all
elements of the object, provided that client code behaves correctly
and calls the defined destroy-function.</p>
</li>
<li>
<p><span class="bold"><b>Extra level of indirection</b></span>.
There is a slight performance cost involved. Using the FIRST-CLASS
ADT pattern implies one extra level of indirection on all
operations on the data structure.</p>
</li>
<li>
<p><span class="bold"><b>Increased dynamic memory usage</b></span>.
In problem domains where there may be potentially many instances of
a quantity unknown at compile-time, a static allocation strategy
cannot be used. As a consequence, the usage of dynamic memory tends
to increase when applying the FIRST-CLASS ADT pattern.</p>
</li>
</ol>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e242" id="d0e242"></a>Examples of
use</h2>
</div>
<p>The most prominent example comes from the C language itself or,
to be more precise, from the C Standard Library - <tt class=
"type">FILE</tt>. True, <tt class="type">FILE</tt> isn't allowed by
the standard to be an incomplete type and it may be possible to
identify its structure, buried deep down in the standard library.
However, the principle is the same since the internals of
<tt class="type">FILE</tt> are implementation specific and programs
depending upon them are inherently non-portable.</p>
<p>[<a href="#Sedgewick">Sedgewick</a>] uses FIRST-CLASS ADT to
implement many fundamental data structures such as linked-lists and
queues.</p>
<p>This pattern may prove useful for cross-platform development.
For example, when developing applications for network
communication, there are differences between Berkeley Sockets and
the Winsock library. The FIRST-CLASS ADT pattern provides the tool
for abstracting away those differences for clients. The trick is to
provide two different implementations of the ADT, both sharing the
same interface (i.e. include file).</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e263" id="d0e263"></a>Next
time</h2>
</div>
<p>We will climb one step in the pattern categories and investigate
a pattern from the Design Patterns [<a href="#GoF">GoF</a>] book.
The next pattern may be useful for controlling the dynamic behavior
of a program and in eliminating complex conditional logic.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e271" id=
"d0e271"></a>Acknowledgements</h2>
</div>
<p>Many thanks to Drago Krznaric and Andre Saitzkoff for their
feedback.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e276" id="d0e276"></a>References</h2>
</div>
<div class="bibliomixed"><a name="GoF" id="GoF"></a>
<p class="bibliomixed">[GoF] Gamma, Helm, Johnson and Vlissides,
<span class="citetitle"><i class="citetitle">Design
Patterns</i></span>, Addison-Wesley</p>
</div>
<div class="bibliomixed"><a name="Buschmann-" id="Buschmann-"></a>
<p class="bibliomixed">[Buschmann-] Buschmann, Meunier, Rohnert,
Sommerlad and Stal, <span class="citetitle"><i class=
"citetitle">POSA, A System of Patterns, Volume 1</i></span>,
Wiley</p>
</div>
<div class="bibliomixed"><a name="Kernighan-" id="Kernighan-"></a>
<p class="bibliomixed">[Kernighan-] Kernighan and Ritchie,
<span class="citetitle"><i class="citetitle">The C Programming
Language</i></span>, Prentice Hall</p>
</div>
<div class="bibliomixed"><a name="C_Standard" id="C_Standard"></a>
<p class="bibliomixed">[C_Standard] ISO/IEC 9899:1999, The C
Standard</p>
</div>
<div class="bibliomixed"><a name="Sedgewick" id="Sedgewick"></a>
<p class="bibliomixed">[Sedgewick] Sedgewick, R., <span class=
"citetitle"><i class="citetitle">Algorithms in C</i></span>, Parts
1-4, 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>
