C++ Coding Standards: Atacama Large Millimeter Array
C++ Coding Standards: Atacama Large Millimeter Array
Atacama Revision: 5
                                           Large             2001-08-10
                                                             Software
                                           Millimeter        Standard
Software Standard
Alan Bridger
       UK Astronomy Technology Centre
Jim Pisano
       National Radio Astronomy Observatory
 Institute:                                     Date:
ALMA                                                  C++ Coding Standards
                              Change Record
 REVISION        DATE           AUTHOR             SECTIONS/PAGES AFFECTED
                                            REMARKS
1             2000-10-16 Alan Bridger           All
              Reformatted, tidied, minor changes, DOC++ added (from JP original)
2             2000-10-30 Alan Bridger           Section 6, appendix I
              Up to date version of DOC++ used.
3             2001-02-28 Alan Bridger           All
              Responded to review comments, assigned doc. #.
4             2001-06-11 Alan Bridger
              Namespace naming, exception guideline, copyright/license mods.
5             2001-08-8      Michele Zamparelli
              substituted DOC++ with doxygen
Revision: 5                                                              Page 2
ALMA                                                                                        C++ Coding Standards
                                                  Table of Contents
1             C++ Coding Standards.................................................................. 4
1.1           Scope.............................................................................................. 4
1.2           Introduction ..................................................................................... 4
2             Class Declarations......................................................................... 4
2.1           Organization .................................................................................... 5
2.2           Contents and Structure ................................................................... 5
3             Naming Conventions..................................................................... 6
3.1           Class Names................................................................................... 6
3.2           Namespaces ................................................................................... 6
3.3           Function Names.............................................................................. 7
3.4           Variable Names............................................................................... 7
3.5           Other Names................................................................................... 8
3.6           File Names...................................................................................... 8
4             Code Commenting......................................................................... 9
4.1           Header Files..................................................................................10
4.2           Source Files ..................................................................................10
5             Object Implementation Guidelines .............................................11
5.1           Structure........................................................................................11
5.2           Robustness...................................................................................12
5.3           Code Style.....................................................................................13
5.4           Organization ..................................................................................13
5.5           Debugging .....................................................................................14
6             Doxygen Use................................................................................14
7 References....................................................................................15
Revision: 5                                                                                                           Page 3
ALMA                                                                       C++ Coding Standards
1.1 Scope
              This document describes the C++ coding guidelines agreed upon by the software
              engineering team. These guidelines are expected to be adhered to in all future C++
              software development. Existing code will not be required to be rewritten to adhere to
              these guidelines, but it is suggested that reasonable efforts are made to adhere to the new
              guidelines when working on existing code.
1.2 Introduction
              Each section of this document contains recommended standards in that area, along with
              a further list of guidelines. A standard is required to be followed in all future
              development. If a programmer must violate a standard, then the reason for doing so
              must be strong and clearly documented via code comments. Guidelines are just that.
              Individual programmers are encouraged to program in a style which is consistent with the
              rest of the programming team, but differing code styles are acceptable.
              These standards recognize that individual programmers have the right to make judgments
              about how best to achieve the goal of code clarity. When working on others’ code, please
              respect and continue existing styles which, although they may differ from your own, meet
              these guidelines. This in turn leads to what is perhaps the most important aspect of
              coding style: consistency. Try, as much as possible, to use the same rules throughout the
              entire program or module.
2 Class Declarations
Standards
                   •   Robust, error-free, easy to use, understand, and maintain class declarations are
                       the single most critical element of programming style, see [5], item 18.
                   •   Within each section, member functions and member data should not be
                       interspersed.
Revision: 5                                                                                        Page 4
ALMA                                                                    C++ Coding Standards
2.1 Organization
Guidelines
                 -   There should be at most one public, one protected and one private section in
                     the class declaration. They should be ordered so that the public section comes
                     first, then the protected section, and lastly the private section.
                 -   Member functions and data should be listed logically. For example, all
                     constructors should be grouped together, all event handling routines may be
                     declared together, as may the routines which access member data. Each logical
                     group of functions should have a common comment above the group explaining
                     why they are grouped together.
                 -   In general there will be one class declaration per header file. In some cases,
                     smaller related classes may be grouped into one header file.
Standards
                 •   Class data members must always be private. If access to them is required then
                     this must be provided through public or protected member functions. See [5],
                     item 20.
                 •   Use const whenever possible for function, reference and pointer parameters,
                     and data member declarations, except where non-constness is required. Use the
                     mutable keyword to as needed for data which is logically but not physically
                     const (for example, read buffers implemented for efficiency).
                 •   A class’s declaration must expose the logical usage of the class, and protect or
                     hide its implementation details. The capacity to make the greatest degree of
                     enhancement and modification with the least change to class declaration is highly
                     desirable for effective maintenance, especially for class interfaces exposed in
                     shared libraries.
Guidelines:
Revision: 5                                                                                     Page 5
ALMA                                                                       C++ Coding Standards
                 -   Organize class member functions in your source code in the same order they are
                     declared in the class interface.
3 Naming Conventions
Standards
                 •   Clear and informative names are one of the best tools for creating easily
                     understandable code. The name of any identifier should succinctly describe the
                     purpose of that identifier.
                 •   Avoid abstract names (in a global context) that are likely to be reused by other
                     parts of the system.
Guidelines
Standards
                 •   Class names must identify the type of the object they represent. (e.g. “Message”
                     or “OutputDevice”).
Guidelines
                 -   Class names will consist of nouns or noun combinations. Derived class names
                     should be suffixed by base class names (e.g. “ClockOutputDevice” or
                     “EditorCWin”).
                 -   The capitalization rule for class names should be all words in the name
                     capitalized, e.g. “ClassName”.
3.2 Namespaces
Standards
Revision: 5                                                                                     Page 6
ALMA                                                                    C++ Coding Standards
Guidelines
                 -   The capitalization rule for Namespace names should be all words in the name
                     capitalized, e.g. “MySpace”. No underscores are allowed.
Standards
                 •   Function names must identify the ac tion performed or the information provided
                     by the function.
Guidelines
                 -   The capitalization rule for function names should be all words in the name
                     capitalized, except for the first, e.g. “functionName”.
Standards
                 •   The type and purpose of each variable should be evident within the code in which
                     it is used. E.g. the reader will expect counter to be an int, motorSet might
                     be a BOOLEAN or an array representing a set – context will usually clarify this.
                     And while the type of sessionId might not be obvious it will be expected to
                     be an identifier or handle that labels some sort of session. Class member data
                     must be easily distinguishable from local data in a consistent manner.
                 •   Names should be formed from composite words, delimited by upper case letters,
                     with no underscores allowed (except for appending pointer identifiers etc.)
                     Underscores should be used as delimiters in macro names.
Guidelines
                 -   Local variables should be named with the content of the variable. Each word
                     except the first one is capitalised. For example, counter and sessionId are
                     acceptable variable names.
                 -   Global variables should be similarly named except that each word is capitalised.
                     For example, ExposureTime is acceptable.
Revision: 5                                                                                      Page 7
ALMA                                                                     C++ Coding Standards
struct s * meaningfulName_p
                 -   Identify class member variables by appending "_m", where “m” stands for
                     “member.” Valid member variable names would include “fileName_m” and
                     “recordCount_m”.
                 -   The capitalization rule for variable names should be all words in the name
                     capitalized except for the first, e.g. “variableName”.
Standard
                 •   Macros, enumeration constants and global constant and typedef names should be
                     stylistically distinguished from class, function, and variable names.
                 •   Types (struct types, etc.) should be given meaningful names and begin with an
                     uppercase letter in order to distinguish them from variables.
Guideline
                 -   Macros, enumeration constants and global constant and global typedef names
                     should be in all uppercase with individual words separated by underscores, e.g.
                     DATA_VALID, const int MIN_WIDTH = 1;
Standards
• C++ Implementation (source) file names should have the extension “.cpp”.
                 •   File names should contain only alphanumeric characters, “_” (underscore), “+”
                     (plus sign), “-“ (minus sign), or “.” (period). Meta-characters and spaces must be
                     avoided. Also file names that only vary by case are not permitted.
                 •   When used with the ESO CMM filenames should contain the module name as a
                     prefix.
Guideline
Revision: 5                                                                                       Page 8
ALMA                                                                     C++ Coding Standards
4 Code Commenting
Standards
                 •    All files, both header and source, must begin with the standard header
                      information, which contains the file identification information, a one line
                      description of the class, and the copyright notice. See the example header files in
                      Appendix A. Different copyright statements may be required for different sites.
                 •    The header may also contain a longer description of the purpose of the class and
                      any other pertinent information about the class.
                 •    A change log for each module must be maintained in a manner appropriate to the
                      development environment. Exactly how this is done is still to be determined by
                      the development environment chosen.
                 •    Comments intended for documentation should use the doxygen style. A template
                      for the ALMA project may be found in Appendix A.
                 •    Block style comments should be preceded by an empty line and have the same
                      indentation as the section of code to which they refer. Block style comments
                      should appear at the beginning of the relevant segment of code. C++ style
                      comments ("//") are preferred.
              Block Style:
              //
              // ...............
              // ....................
              // .......................
              //
                 •    Brief comments on the same line as the statement that they describe are
                      appropriate for the in-line commenting style. There should be at least 4 spaces
                      between the code and the start of the comment.
In-Line Comments:
                     ...........                              // .........
                     ...........                              // .........
                     ...........                              // .........
                 •    Use in-line comments to document variable usage and other small comments.
                      Block style comments are preferable for describing computation processes and
                      program flow.
Guidelines
Revision: 5                                                                                       Page 9
ALMA                                                                      C++ Coding Standards
                  −   Use the $Id$ RCS identifier for all RCS-based source-code control tools. The
                      $Id$ identifier expands to $Id: filename revision date time author state $.
                      When used with ESO's CMM the identifier must be preceded by @(#).
                  −   Use a “ToDo” section in the header comments to indicate those items that remain
                      to be done.
              The primary goal of interface comments is to define the class and its members at a level
              appropriate for a new user of the class. Interface comments should be as concise as
              possible to meet this goal.
Standards
                      b) What the parameters are, how they are used, and any preconditions that must
                         be established for the parameters. A variable name, in addition to its type,
                         must be used to identify the parameter’s purpose.
c) What the function is going to do to the parameters and to the object itself.
                      d) What the results/return values are in all the different cases possible for the
                         function.
Guideline
                  -   The preferred format for member data element comments is doxygen style
                      comments (///) above at the same indentation level of the code that is being
                      discussed. C++ style comments (//) may be used when documentation is not
                      required.
Standards
                  •   All comments in source code files must be up-to-date at all times during that
                      code's lifetime.
Revision: 5                                                                                       Page 10
ALMA                                                                      C++ Coding Standards
Guidelines
                  -   Use a line of dashes ‘—‘ to visually block off member function definitions in the
                      source file. This allows easy identification of where the functions start.
5.1 Structure
Standards
                  •   In general, hide the implementation details from the interface. This encompasses
                      issues including data member accessibility (avoid public), implementation of
                      assignment operators and copy constructors, and judicious use of inheritance and
                      virtual functions. See [5] items 20, 11-17, and 35-43.
                  •   For software intended for workstations make use of namespaces to partition the
                      global name space. For software intended for LCUs (and for common software
                      that can be used on LCUs or workstations) namespace support cannot be
                      guaranteed and so namespaces should not be used.
                  •   When namespaces are not used, structs can be used to break up the global name
                      space. Global scope functions, data, and even types should be kept to a
                      minimum, and these identifiers linked to the most logically-related class.
                      Functions used within a class should be member functions of that class rather
                      than hidden global scope functions. Enumerated types used specifically for one
                      class should be declared within that class. See [5], items 28, 32 and 47. Also of
                      note is a macro definition in ACE that simulates namespaces.
Guidelines
Revision: 5                                                                                       Page 11
ALMA                                                                       C++ Coding Standards
                  -   Global static objects should be avoided. If they are used, care should be used
                      when declaring global static objects as they cause initialization ordering
                      problems and cause problems in a multi-threaded environment. An instantiator
                      class which counts references to an object should be imple mented. See [4], topic
                      4.04 or [5], item 47.
                  -   Project-wide header files which declare, include and define everything useful and
                      shared for an entire project simplifies the project organization. This process must
                      be somewhat controlled as it can lead to large includes and slow the build process
                      dramatically. As the project matures, this project-wide header can be pared down
                      with forward declarations replacing include files.
                  -   Create your own exception heirarchies reflecting the domain and define relevant
                      exception classes derived from the standard exception class. See [10]. E.g.
                  -   Users of ACE TAO on vxWorks may still be constrained to using the ACE
                      exception emulation and should follow the ACE guidelines.
5.2 Robustness
              Function definitions must -- to the fullest extent possible -- trap invalid or undefined use
              of the class.
Standards
                  •   Declare const variables instead of using #defines for simple constants. The
                      compiler will provide a level of type checking when the constants are used.
                  •   Initialize all member data and local variables. All pointers should be initialized
                      to appropriate values or NULL.
Revision: 5                                                                                         Page 12
ALMA                                                                    C++ Coding Standards
Guidelines
                 -   Keep local variables as local as possible. A counter which is used only in one
                     for loop should be initialized in that loop, rather than at the top of the function.
                     Keep in mind however, that any variables declared inside nested loops will be
                     repeatedly constructed and destructed. In cases where construction or destruction
                     are expensive, it may be preferable to declare the variable outside the loop.
Standard
Guidelines
                 -   Avoid very long functions which may be difficult to comprehend and maintain.
                     If a function becomes too long, break it into logical chunks and put each chunk
                     into a function of its own. A function that is more than 100 lines, including
                     comments and white space, is generally considered to be too long. Some authors
                     recommend that a function should fit on one screen of your text editor.
                 -   Use braces liberally. It is a good idea to put braces around any branch or loop
                     code even if it is a single statement, because sooner or later someone will want to
                     add another statement to the loop and forget to add the brace.
                 -   Use parentheses liberally. They do not add code, but they can help avoid
                     precedence or ordering mistakes, and can help readability.
                 -   Use white space liberally to make code more readable by putting space before
                     and after operators and between the sections of a complex statement.
                 -   Line length should not exceed 80 characters as telnet interfaces are sometimes
                     used to deal with code.
5.4 Organization
Guidelines
Revision: 5                                                                                     Page 13
ALMA                                                                        C++ Coding Standards
                  -   Optimize code only after performance measurement shows where the time is
                      going. It is easy to incorrectly guess what areas of code are the bottlenecks. See
                      [7].
                  -   White space should be used to group functions, and to group steps of algorithms
                      within functions.
5.5 Debugging
Guideline
6             Doxygen Use
              The ALMA standard code documentation tool is doxygen. In this section a suggested
              standard doxygen usage is presented. It is not intended that this be a doxygen primer - the
              documentation for doxygen is easily available (see [8]) and is much better for that. Note
              that the latest version of doxygen is 1.2.8.1
              In very brief terms doxygen uses special comment delimiters (/**…*/ or ///… and
              //@{…//@}) to allow the programmer to add his or her own documentation comments.
              In addition doxygen constructs class hierarchies.
              In addition special tokens, similar to Javadoc ones, allow the specification of particular
              attributes such as author, version, etc.
              The following are the recommended standards for using doxygen for ALMA software. A
              suggested example ALMA usage of doxygen may be found in the appendices, including
              examples of each of the following.
                  •   Use @see (where appropriate) for class documentation. Author and version are
                      stored in the code repository.
                  •   Use @exception, @return, @pre, @post, and @param (where appropriate) for
                      C++ methods. The class Bar has a constructor method with examples.
                  •   Use upwards arrows in the class graphs to conform with accepted generalisation
                      convention.
              A doxygen configuration file is included in the example. It should be noted that this is a
              suggested doxygen usage and that no doubt it will solicit comments. The authors feel that
Revision: 5                                                                                        Page 14
ALMA                                                                    C++ Coding Standards
              a separate document on doxygen usage for IDL, C, C++ and Java might be more
              appropriate.
7             References
              1. Taligent’s Guide to Designing Programs, Taligent Press, 1994.
3. C++ Programming Guidelines, Plum, T., Saks, D., Plum Hall, 1991.
              7. More Effective C++: 35 New Ways to Improve Your Programs and Designs,
                 Meyers, S., Addison-Wesley, 1996.
              Foo.h
Foo.h
#ifndef FOO_H
#define FOO_H
//    @(#) $Id$
//
//    [Insert copyright statement appropriate to author(s).]
//
//    Produced for the ALMA project
//
//    This library is free software; you can redistribute it
Revision: 5                                                                                    Page 15
ALMA                                                 C++ Coding Standards
class         Foo
{
public:
  /**
   * constructor
   * A more detailed description of the constructur
   * and its peculiarities
   */
    Foo();
     /**
      * constructor with param
      * A more detailed description of this constructor
      * and why it differs from the previous one
      */
       Foo( const Foo &);
~Foo();
Revision: 5                                                          Page 16
ALMA                                             C++ Coding Standards
    /**
     * A set function
     * the peculiarity of this function
     * @param new value the counter should be reset to
     */
      void setCount( const int _newValue);
protected:
  /// a protected member variable
  double doubleCount;
private:
  /**
   * private members only show up if your doxygen configuration
   * file is set up accordingly
   */
  int m_currentCount;
};
#endif
              Intermediate.h
#ifndef INTERMEDIATE_H
#define INTERMEDIATE_H
// @(#) $Id$
//
// [Insert here the same copyright and license statement as presented
above]
//@Include: Foo.h
/**
 * Just to make the class graph look more a little more
 * interesting. Here we show multiple inheritance from one
 * docified class and a nondocified one.
 *
 * @see        Foo, NotDocified
 */
Revision: 5                                                       Page 17
ALMA                                                 C++ Coding Standards
#endif
              Bar.h
#ifndef BAR_H
#define BAR_H
// @(#) $Id$
//
// [Insert copyright and license statement as presented above]
//
//
/**
 *      A derived class.
 *      Here we show inheritance from a single docified class.
 *      This example shows how to structure the members of a
 *      class, if desired.
 *
 *      @include: Function.h
 *      @include: Intermediate.h
 *      @see            Foo
 */
//@{
        // constructor
        /**
         * This constructor takes two arguments and serves as
         * a suggested example of how ALMA methods should be
         * documented. It demonstrates documenting parameters
         * exceptions, return values, and pre- and post-
         * conditions.
         *
         *     @param a this is good for many things
         *     @param b this is good for nothing
         *     @return A Bar, whatever that is.
         *     @exception      None
         *     @pre   None required
         *     @post Whatever must happen next
         */
        /// destructor
        ~Bar() ;
Revision: 5                                                          Page 18
ALMA                                                                                  C++ Coding Standards
//@{
    //@}
};
#endif
              function.h
#ifndef FUNCTION_H
#define FUNCTION_H
// @(#) $Id$
//
// [Insert copyright and license statement as presented above]
//
//
              1
                  For the class hierarchies. This may be overridden for a simpler, plain HTML representation.
Revision: 5                                                                                                     Page 19
ALMA                                                                   C++ Coding Standards
This output was produced by running doxygen on the above with the command
doxygen alma-doxy
              run in the directory where the header files are, and using some simple HTML files for
              customised headers and footers. The doxygen options were specified in the alma-doxy
              configuration file. The ALMA project should adopt a standard configuration file.
              The customised headers are examples. The ALMA project may wish to adopt standard
              headers, but it may also be appropriate for each package to provide its own standard
              headers. The example banner/footer is a suggested ALMA standard.
Revision: 5 Page 20