{{#switch:|User|User talk=|#default={{#ifeq:{{{category}}}|no||}}}}

C++ Code Style

The document located HERE describes ITK coding conventions. Developers should follow these conventions when submitting contributions.

ITK Style Guide Insight Software Consortium

Purpose

The following document is a description of the accepted coding style for the NLM Insight Segmentation and Registration Toolkit (ITK). Developers who wish to contribute code to ITK should read and adhere to the standards described here.

Document Overview

This document is organized into the following sections.

This style guide is an evolving document.

Please dialog with the ITK developers if you wish to add, modify, or delete the rules described in these guidelines.

See:

http://www.itk.org/ITK/help/mailing.html

for more information about joining the ITK developers mailing list. This forum is one of the best venues in which to propose changes to these style guidelines.

Style Guidelines

The following coding-style guidelines have been adopted by the ITK community. To a large extent these guidelines are a result of the fundamental architectural and implementation decisions made early in the project. For example, the decision was made to implement ITK with a C++ core using principles of generic programming, so the rules are oriented towards this style of implementation. Some guidelines are relatively arbitrary, such as indentation levels and style. However, an attempt was made to find coding styles consistent with accepted practices. The point is to adhere to a common style to assist developers and users of the future learn, use, maintain, and extend ITK. (See the ITK Requirements document for more information.) Please do your best to be a upstanding member of the ITK community. The rules described here have been developed with the community as a whole in mind. If you consistently violate these rules you will likely be harassed mercilessly, first privately and then publicly. If this does not result in correct code layout, your right to CVS write access (if you are developer and wish to contribute code) may be removed. Similarly, if you wish to contribute code and are not a developer, your code will not be accepted until the style is consistent with these guidelines.

System Overview & Philosophy

The following implementation strategies have been adopted by the ITK community. These directly and indirectly affect the resulting code style. Understanding these strategies motivate the reasons for many of the style guidelines described in this document.

Implementation Language

The core implementation language is C++. C++ was chosen for its flexibility, performance, and familiarity to consortium members. (Auxiliary, interpreted language bindings such as Tcl, Python, and/or Java are also planned. These are aimply (run-time interpreted) layers on the C++ code.) ITK uses the full spectrum of C++ features including const and volatile correctness, namespaces, partial template specialization, operator overloading, traits, and iterators.

Generic Programming and the STL

Compile-time binding using methods of generic programming and template instantiation is the preferred implementation style. This approach has demonstrated its ability to create efficient, flexible code. Use of the STL (Standard Template Library) is encouraged. STL is typically used by a class, rather than as serving as a base class for derivation of ITK classes. Other STL influences are iterators and traits. ITK defines a large set of iterators; however, the ITK iterator style differs in many cases from STL because STL iterators follow a linear traversal model; ITK iterators are often designed for 2D, 3D, and even n-D traversal. Traits are used heavily be ITK. ITK naming conventions supersede STL naming conventions; this difference is useful in that it indicates to the developer something of the boundary between ITK and STL.

Portability

ITK is designed to compile on a set of target operating system/compiler combinations.

These combinations include, but are not limited to:

For a full list of the compilers supported please see:

Multi-Layer Architecture

ITK is designed with a multi-layer architecture in mind. That is, three layers, a templated layer, a run-time layer, and an application layer. The templated (or generic) layer is written in C++ and requires significant programming skills and domain knowledge. The run-time layer is generated automatically using the CableSwig wrapping system to produce language bindings to Tcl, Python, and Java. The interpreted layer is easier to use than the templated layer, and can be used for prototyping and smaller-sized application development. Finally, the application layer is not directly addressed by ITK other than providing simple examples of applications.

CMake Build Environment

The ITK build environment is CMake. CMake is an open-source, advanced cross-platform build system that enables developers to write simple \makefiles" (named CMakeLists.txt) that are processed to generated native build tools for a particular operating system/compiler combinations. See the CMake web pages at http://www.cmake.org for more information.

Doxygen Documentation System

The Doxygen open-source system is used to generate on-line documentation. Doxygen requires the embedding of simple comments in the code which is in turn extracted and formatted into documentation.

For more information about Doxygen, please see

  http://www.stack.nl/dimitri/doxygen/

vnl Math Library

ITK has adopted the vnl math library. Vnl is a portion of the vxl image understanding environment. See http://www.robots.ox.ac.uk/ vxl/ for more information about vxl and vnl.

Reference Counting

ITK has adopted reference counting via so-called "smart pointers" to manage object references. While alternative approaches such as automatic garbage collection were considered, their overhead due to memory requirements, performance, and lack of control as to when to delete memory, precluded these methods. Smart pointers manage the reference to objects, automatically incrementing and deleting an instance's reference count, deleting the object when the count goes to zero. These are the most important factors influencing the coding style found in Insight. Now we will look at the details.

Copyright

ITK has adopted a standard copyright. This copyright should be placed at the head of every source code file. The current copyright header and license reads as follows:

/*=========================================================================                                                                                      
 *                                                                                                                                                               
 *  Copyright Insight Software Consortium                                                                                                                        
 *                                                                                                                                                               
 *  Licensed under the Apache License, Version 2.0 (the "License");                                                                                              
 *  you may not use this file except in compliance with the License.                                                                                             
 *  You may obtain a copy of the License at                                                                                                                      
 *                                                                                                                                                               
 *         http://www.apache.org/licenses/LICENSE-2.0.txt                                                                                                        
 *                                                                                                                                                               
 *  Unless required by applicable law or agreed to in writing, software                                                                                          
 *  distributed under the License is distributed on an "AS IS" BASIS,                                                                                            
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.                                                                                     
 *  See the License for the specific language governing permissions and                                                                                          
 *  limitations under the License.                                                                                                                               
 *                                                                                                                                                               
 *=========================================================================*/

Copyright Header

File Organization

Classes are created and (usually) organized into a single class per file set. A file set consists of .h header file, .cxx implementation file, and/or a .hxx templated implementation file. Helper classes may also be defined in the file set, typically these are not visible to the system at large, or placed into a special namespace.

Source files must be placed in the correct directory for logical consistency with the rest of the system, and to avoid cyclic dependencies. Currently the ITK source directory structure is found in ITK/Modules and consists of the following subdirectories:

Each one of these directories represent a Group of Modules.

Please discuss with the ITK Developers about the best Module to place your new code.

For a full list of Modules, please see:

 http://www.itk.org/Doxygen/html/modules.html

Naming Conventions

In general,

(versus Time Stamp).

uppercase as in RGB.) While this does result in long names, it self-documents the code.

Depending on whether the name is a

variations on this theme result as explained in the following subsections.

Naming Classes

class name = <algorithm><input><concept>

adverb) comes first, followed by an input type (if the class is a filter), and completed by a concept name.

concepts, here are a few of them.

The more common or important concepts are underlined.


The naming of classes is an art form; please review existing names to catch the spirit of the naming convention.

Example names include:

Naming Files

Naming Methods and Functions

Global functions and class methods, either static or class members, are named beginning with a capital letter. The biggest challenge when naming methods and functions is to be consistent with existing names. For example, given the choice between ComputeBoundingBox() and CalculateBoundingBox() (CalcBoundingBox() is not allowed because it is not spelled out), the choice is ComputeBoundingBox() because \Compute" is used elsewhere in the system in similar settings (The concepts described previously should be used whenever possible). When referring to class methods in code, an explicit this-> pointer should be used, as in this->ComputeBoundingBox(). The use of the explicit this-> pointer helps clarify exactly which method, and where it originates, is being invoked. Similarly the \::" global namespace should be used when referring to a global function.

Naming Class Data Members

Class data members are prepended with m as in m_Size. This clearly indicates the origin of data members, and differentiates them from all other variables.

Naming Local Variables

Local variables begin in lowercase. There is more flexibility in the naming of local variables; please remember that others will study, maintain, fix, and extend your code. Any bread crumbs that you can drop in the way of explanatory variable names and comments will go a long way towards helping other developers.

Naming Template Parameters

Template parameters follow the usual rules with naming except that they should start with either the capital letter T or V. Type parameters begin with the letter T while value template parameters begin with the letter V.

Naming Typedefs

Typedefs are absolutely essential in generic programming. They significantly improve the readibility of code, and facilitate the declaration of complex syntactic combinations. Unfortunately, creation of typedefs is tantamount to creating another programming language. Hence typedefs must be used in a consistent fashion. The general rule for typedef names is that they end in the word Type. For example typedef TPixel PixelType; However, there are many exceptions to this rule that recognize that ITK has several important concepts that are expressed partially in the names used to implement the concept. An iterator is a concept, as is a container or pointer. These concepts are used in preference to Type at the end of a typedef as appropriate. For example

typedef typename ImageTraits::PixelContainer PixelContainer;

Here Container is a concept used in place of Type. ITK currently identifies the following concepts used when naming typedefs.

Using Underscores

Don't use them. The only exception is when defining preprocessor variables and macros (which are discouraged). In this case, underscores are allowed to separate words.

Preprocessor Directives

Header Includes

Header includes use the style

#include "itkImage.h"

Only the required headers should be included. If an included header already includes a header for a class also used in the current file, the header for that class should not be included.

Header includes are preferred over forward declarations. Forward declarations are only used to prevent circular dependencies.

Namespaces

All classes should be placed in the itk:: namespace. Additional sub-namespaces are being designed to support special functionality.

Please see current documentation to determine if there is a subnamespace is relevant to your situation. Normally sub-namespaces are used for helper ITK classes.

Code should not use using namespace. This is to avoid namespace conflicts, but, more importantly, to improve readability.

When declaring or defining members of the "itk" namespace, for example, the 'itk::' namespace prefix should not be added. That is, code within "namespace itk { ... }" should not used "itk::".

Const Correctness

Const correctness is important. Please use it as appropriate to your class or method.

Code Layout and Indentation

The following are the accepted ITK code layout rules and indentation style. After reading this section, you may wish to visit many of the source files found in ITK. This will help crystallize the rules described here.

General Layout

int i;
int j;
char* stringname;

Class Layout

Classes are defined using the following guidelines.

The class layout looks something like this:

#ifndef itkImage_h
#define itkImage_h

#include "itkImageBase.h"
#include "itkPixelTraits.h"
#include "itkDefaultImageTraits.h"
#include "itkDefaultDataAccessor.h"

namespace itk
{

/** \class Image
 *  \brief Templated n-dimensional image class.
 *
 * .... detailed documentation....
 */
template< typename TPixel, unsigned int VImageDimension=2,
          typename TImageTraits=DefaultImageTraits< TPixel, VImageDimension > >
class Image: public ImageBase< VImageDimension >
{
public:
    //....stuff...
protected:
    //....stuff...
private:
    //....stuff...
};

} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkImage.hxx"
#endif

#endif

Method Definition

template<typename TPixel, unsigned int VImageDimension, typename TImageTraits>
const double *
Image<TPixel, VImageDimension, TImageTraits>
::GetSpacing() const
{
  //...stuff...
}

Use of Braces

for( unsigned int ii = 0; ii < 3; ++ii )
  {
  ...
  }


or when using an if:

if( condition )
  {
  ...
  }
else if( other condition )
  {
  ...
  }
else
  {
  ....
  }


Indentation Inside Braces

Source code in the body of the brackets must be aligned along with the brackets. As in

if ( condition )
  {
  unsigned int numberOfIterations = 100;
  filter->SetNumberOfIterations( numberOfIterations );
  filter->Update();
  filter->Print( std::cout );
  }

Doxygen Documentation System

See more at

 https://www.stack.nl/~dimitri/doxygen/manual/index.html

Documenting a Class

/** \class Object
* \brief Base class for most itk classes.
*
* Object is the second-highest level base class for most itk objects.
* It extends the base object functionality of LightObject by
* implementing debug flags/methods and modification time tracking.
*/

Documenting a Method

/** Access a pixel at a particular index location.
* This version can be an lvalue. */
TPixel & operator[](const IndexType &index)
{ return this->GetPixel(index); }

The key here is that the comment starts with /**, each subsequent line has an aligned *, and the comment block terminates with a */.

Documenting ivars

public:

  /** Set/Get the standard deviation of the Gaussian used for smoothing. */
  itkSetMacro( Sigma, SigmaArrayType );
  itkGetConstMacro( Sigma, SigmaArrayType );

private:

  SigmaArrayType m_Sigma;

Using Standard Macros (itkMacro.h)

Some of the more important object macros are as follows.

Please review this file and become familiar with these macros.

Exception Handling

Indicate that methods throw exceptions in the method declaration as in:

const float* foo() const throws itk

Documentation Style

The Insight consortium has adopted the following guidelines for producing supplemental documentation (documentation not produced by Doxygen).

CMake Style

A proposal style guide for CMake variables is presented HERE.



ITK: [Welcome | Site Map]