Next: Organization of Source Code
Up: Programming Style
Previous: On the Process of
  Contents
Although C lacks the most powerful features of C++ as far as concepts
and data organization is concerned, Stroustrup says: ``Remember that
much programming can be simply and clearly done using only primitive,
data structures, plain functions, and a few library classes.'' This
means that one can write many useful and well-written programs
in C. Here are a few pointers that will assist you in structuring
your C program:
- Identify groups of variables having common function (e.g. basis
set, etc.) and organize them into structures. Use several levels of
hierarchy if necessary (e.g. a basis set is a collection of basis
functions each of which may be described by a structure). This is
called ``hierarchical ordering''.
- Think as generally as possible. What you may not need today will
be asked for tomorrow. Design data structures that are flexible and
modular, i.e. one can be easily modified without affecting the others
(e.g. you do not want the structure describing basis sets to know
anything about the type of basis functions it contains so that plane
waves can be used as easily as Gaussians).
- Write ``constructors'' for the structures, i.e. functions which
will initialize data in the structures (e.g. read basis set
information). Make as many ``constructors'' as necessary (e.g. basis
set info can be read from the checkpoint file or from pbasis.dat). If
it is difficult or impossible to write a ``constructor'' for some data
structure is a sign that your data hierachy is poorly designed and
there are mutual dependencies. Spend more time designing the
system. If it doesn't help, then use source code comments heavily to
describe the relationships not reflected in the code itself.
- Use global variables sparringly. Placing a variable into global
scope leaves it unprotected against ``unauthorized'' use or
modification (we are not talking about security here; it is a good
idea to protect data from the programmer, because if you do not want
some data A to be modified by function B, do not make
A available to B) and may also have impact on
program's performance. Sometimes it is a good idea to use global data
to reduce the cost of passing that data to a function. However, the
same effect may be achieved by organizing that data into a local
structure and passing the structure instead.
- Learn how to use static variables local to a source
file, it is a very powerful tool to protect data in a C program.
- Organize the source code such as to emphasize further the
structure of the program (see section 5.3).
More material on data organization may be found in the Stroustrup's
book.
Next: Organization of Source Code
Up: Programming Style
Previous: On the Process of
  Contents
psi
2003-01-07