Open CASCADE Technology
7.6.0
|
|
The purpose of this document is to define a common programming style for Open CASCADE Technology.
The common style facilitates understanding and maintaining a code developed cooperatively by several programmers. In addition, it enables construction of tools that incorporate knowledge of these standards to help in the programming.
OCCT programming style follows common and appropriate best practices, so some guidelines have been excerpted from the public domain.
The guide can be improved in the future as new ideas and enhancements are added.
Rules in this document refer to C++ code. However, with minor exceptions due to language restrictions, they are applicable to any sources in Open CASCADE Technology framework, including:
The names considered in this section mainly refer to the interface of Open CASCADE Technology libraries or source code itself.
Open CASCADE Technology is an open source platform available for an international community, thus all names need to be composed of English words or their abbreviations.
Names should be meaningful or, at least, contain a meaningful part. To better understand this requirement, let us examine the existing names of toolkits, packages, classes and methods:
Names related to a logically connected functionality should have the same prefix (start with the same letters) or, at least, have any other common part. For example, method GetCoord returns a triple of real values and is defined for directions, vectors and points. The logical connection is obvious.
Camel Case style is preferred for names. For example:
Usually a unit (e.g. a package) is a set of classes, methods, enumerations or any other sources implementing a common functionality, which is self-contained and independent from other parts of the library.
Names of units should not contain underscores, unless the use of underscores is allowed explicitly.
The following extensions should be used for source files, depending on their type:
Note that .lxx files should be avoided in most cases - inline method should be placed in header file instead.
Toolkit names are prefixed by TK, followed by a meaningful part of the name explaining the domain of functionality covered by the toolkit (e.g. TKOpenGl).
Names of public classes and other types (structures, enums, typedefs) should match the common pattern: name of the package followed by underscore and suffix (the own name of the type):
Static methods related to the whole package are defined in the class with the same name as package (without suffix).
Each type should be defined in its own header file with the name of the type and extension ".hxx". Implementation should be placed in the file with the same name and extension ".cxx"; for large classes it is possible to split implementation into multiple source files with additional suffixes in the names (usually numerical, e.g. BSplCLib_1.cxx).
For example, class Adaptor2d_Curve2d belongs to the package Adaptor2d; it is defined in header file Adaptor2d_Curve2d.hxx and implemented in source file Adaptor2d_Curve2d.cxx.
This rule also applies to complex types constructed by instantiation of templates. Such types should be given own names using typedef statement, located in same-named header file.
For example, see definition in the file TColStd_IndexedDataMapOfStringString.hxx:
The term function here is defined as:
It is preferred to start names of public methods from an upper case character and to start names of protected and private methods from a lower case character.
There are several rules that describe currently accepted practices for naming variables.
Name of a variable should not conflict with the existing or possible global names (for packages, macros, functions, global variables, etc.).
The name of a variable should not start with an underscore.
See the following examples:
The name of a function (procedure, class method) parameter should start with prefix the followed by the meaningful part of the name starting with a capital letter.
See the following examples:
The name of a class member variable should start with prefix my followed by the meaningful of the name starting with a capital letter.
See the following examples:
It is strongly recommended to avoid defining any global variables. However, as soon as a global variable is necessary, its name should be prefixed by the name of a class or a package where it is defined followed with _my.
See the following examples:
Static constants within the file should be written in upper-case and begin with prefix THE_:
The name of a local variable should be distinguishable from the name of a function parameter, a class member variable and a global variable.
It is preferred to prefix local variable names with a and an (or is, to and has for Boolean variables).
See the following example:
Avoid dummy names, such as i, j, k. Such names are meaningless and easy to mix up.
The code becomes more and more complicated when such dummy names are used there multiple times with different meanings, or in cycles with different iteration ranges, etc.
See the following examples for preferred style:
To improve the open source readability and, consequently, maintainability, the following set of rules is applied.
All comments in all sources must be in English.
Try to stay within the limit of 120 characters per line in all sources.
Prefer C++ style comments in C++ sources.
Delete unused code instead of commenting it or using #define.
Indentation in all sources should be set to two space characters. Use of tabulation characters for indentation is disallowed.
Punctuation rules follow the rules of the English language.
In declarations of simple pointers and references put asterisk (*) or ampersand (&) right after the type without extra space.
Since declaration of several variables with mixed pointer types contrudicts this rule, it should be avoided. Instead, declare each variable independently with fully qualified type.
Examples:
Separate logical blocks of code with one blank line and comments.
See the following example:
Notice that multiple blank lines should be avoided.
Use function descriptive blocks to separate function bodies from each other. Each descriptive block should contain at least a function name and purpose description.
See the following example:
Figure brackets { } and each operator (for, if, else, try, catch) should be written on a dedicated line.
In general, the layout should be as follows:
Entering a block increases and leaving a block decreases the indentation by one tabulation.
Single-line conditional operators (if, while, for, etc.) can be written without brackets on the following line.
Having all code in the same line is less convenient for debugging.
In comparisons, put the variable (in the current context) on the left side and constant on the right side of expression. That is, the so called "Yoda style" is to be avoided.
Use alignment wherever it enhances the readability. See the following example:
Comments should be indented in the same way as the code to which they refer or they can be in the same line if they are short.
The text of the comment should be separated from the slash character by a single space character.
See the following example:
Use an early return condition rather than collect indentations.
Write like this:
Rather than:
This helps to improve readability and reduce the unnecessary indentation depth.
Trailing spaces should be removed whenever possible. Spaces at the end of a line are useless and do not affect functionality.
Split headers into groups: system headers, headers per each framework, project headers; sort the list of includes alphabetically. Within the class source file, the class header file should be included first.
This rule improves readability, allows detecting useless multiple header inclusions and makes 3rd-party dependencies clearly visible. Inclusion of class header on top verifies consistency of the header (e.g. that header file does not use any undefined declarations due to missing includes of dependencies).
An exception to the rule is ordering system headers generating a macros declaration conflicts (like "windows.h" or "X11/Xlib.h") - these headers should be placed in the way solving the conflict.
The source or header file should include only minimal set of headers necessary for compilation, without duplicates (considering nested includes).
The source code is one of the most important references for documentation. The comments in the source code should be complete enough to allow understanding the corresponding code and to serve as basis for other documents.
The main reasons why the comments are regarded as documentation and should be maintained are:
The comments should be compatible with Doxygen tool for automatic documentation generation (thus should use compatible tags).
Each class should be documented in its header file (.hxx). The comment should give enough details for the reader to understand the purpose of the class and the main way of work with it.
Each class or package method should be documented in the header file (.hxx).
The comment should explain the purpose of the method, its parameters, and returned value(s). Accepted style is:
//! Method computes the square value. //! @param theValue the input value //! @return squared value Standard_Export Standard_Real Square (Standard_Real theValue);
It is very desirable to put comments in the C/C++ sources of the package/class.
They should be detailed enough to allow any person to understand what each part of code does.
It is recommended to comment all static functions (like methods in headers), and to insert at least one comment per each 10-100 lines in the function body.
There are also some rules that define how comments should be formatted, see Formatting Rules.
Following these rules is important for good comprehension of the comments. Moreover, this approach allows automatically generating user-oriented documentation directly from the commented sources.
The following rules define the common style, which should be applied by any developer contributing to the open source.
Try to design general classes (objects) keeping possible inheritance in mind. This rule means that the user who makes possible extensions of your class should not encounter problems of private implementation. Try to use protected members and virtual methods wherever you expect extensions in the future.
Avoid using 'friend' classes or functions except for some specific cases (for example, iteration) 'Friend' declarations increase coupling.
Avoid providing set/get methods for all fields of the class. Intensive set/get functions break down encapsulation.
Avoid hiding a base class virtual function by a redefined function with a different signature. Most of the compilers issue warning on this.
Try not to mix different error indication/handling strategies (exceptions or returned values) on the same application level.
When compiling the source pay attention to and try to minimize compiler warnings.
Try to minimize compilation dependencies by removing unnecessary inclusions.
This section defines the rules for writing a portable and maintainable C/C++ source code.
Use package or class methods returning reference to wrap global variables to reduce possible name space conflicts.
Use protected members instead of private wherever reasonable to enable future extensions. Use private fields if future extensions should be disabled.
Use constant variables (const) and inline functions instead of defines (#define).
Avoid usage of explicit numeric values. Use named constants and enumerations instead. Numbers produce difficulties for reading and maintenance.
If a class has a destructor, an assignment operator or a copy constructor, it usually needs the other two methods.
A class with virtual function(s) ought to have a virtual destructor.
Declaration of overriding method should contains specifiers "virtual" and "override" (using Standard_OVERRIDE alias for compatibility with old compilers).
This makes class definition more clear (virtual methods become highlighted).
Declaration of interface using pure virtual functions protects against incomplete inheritance at first level, but does not help when method is overridden multiple times within nested inheritance or when method in base class is intended to be optional.
And here "override" specifier introduces additional protection against situations when interface changes might be missed (class might contain old methods which will be never called).
Do not redefine a default parameter value in an inherited function.
Use const modifier wherever possible (functions parameters, return values, etc.)
Avoid goto statement unless it is really needed.
Declare a cycle variable in the header of the for() statement if not used out of cycle.
Avoid usage of C-style comparison for non-boolean variables:
This chapter contains rules that are critical for cross-platform portability.
The source code must be portable to all platforms listed in the official 'Technical Requirements'. The term 'portable' here means 'able to be built from source'.
The C++ source code should meet C++03 standard. Any usage of compiler-specific features or further language versions (for example, C++11, until all major compilers on all supported platforms implement all its features) should be optional (used only with appropriate preprocessor checks) and non-exclusive (an alternative implementation compatible with other compilers should be provided).
Avoid usage of global variables. Usage of global variables may cause problems when accessed from another shared library.
Use global (package or class) functions that return reference to static variable local to this function instead of global variables.
Another possible problem is the order of initialization of global variables defined in various libraries that may differ depending on platform, compiler and environment.
Avoid explicit usage of basic types (int, float, double, etc.), use Open CASCADE Technology types from package Standard: Standard_Integer, Standard_Real, Standard_ShortReal, Standard_Boolean, Standard_CString and others or a specific typedef instead.
Do not assume sizes of types. Use sizeof() instead to calculate sizes.
In accordance with C++03 standard source files should be trailed by an empty line. It is recommended to follow this rule for any plain text files for consistency and for correct work of git difference tools.
The rules listed in this chapter are important for stability of the programs that use Open CASCADE Technology libraries.
When using Open CASCADE Technology in an application, call OSD::SetSignal() function when the application is initialized.
This will install C handlers for run-time interrupt signals and exceptions, so that low-level exceptions (such as access violation, division by zero, etc.) will be redirected to C++ exceptions that use try {...} catch (Standard_Failure) {...} blocks.
The above rule is especially important for robustness of modeling algorithms.
Take care about cycling of handled references to avoid chains, which will never be freed. For this purpose, use a pointer at one (subordinate) side.
See the following example:
In C++ use new and delete operators instead of malloc() and free(). Try not to mix different memory allocation techniques.
Use the same form of new and delete.
Define a destructor, a copy constructor and an assignment operator for classes with dynamically allocated memory.
Every variable should be initialized.
Uninitialized variables might be kept only within performance-sensitive code blocks and only when their initialization is guaranteed by subsequent code.
Avoid hiding the global new operator.
In operator=() assign to all data members and check for assignment to self.
Don't check floats for equality or non-equality; check for GT, GE, LT or LE.
Package Precision provides standard values for SI units and widely adopted by existing modeling algorithms:
as well as definition of infinite values within normal range of double precision:
Avoid usage of iteration over non-indexed collections of objects. If such iteration is used, make sure that the result of the algorithm does not depend on the order of iterated items.
Since the order of iteration is unpredictable in case of a non-indexed collection of objects, it frequently leads to different behavior of the application from one run to another, thus embarrassing the debugging process.
It mostly concerns mapped objects for which pointers are involved in calculating the hash function. For example, the hash function of TopoDS_Shape involves the address of TopoDS_TShape object. Thus the order of the same shape in the TopTools_MapOfShape will vary in different sessions of the application.
Do not throw from within a destructor.
Avoid the assignment of a temporary object to a reference. This results in a different behavior for different compilers on different platforms.
These rules define the ways of avoiding possible loss of performance caused by ineffective programming.
Declare fields of a class in the decreasing order of their size for better alignment. Generally, try to reduce misaligned accesses since they impact the performance (for example, on Intel machines).
List class data members in the constructor's initialization list in the order they are declared.
Prefer initialization over assignment in class constructors.
When programming procedures with extensive memory access, try to optimize them in terms of cache behavior. Here is an example of how the cache behavior can be impacted:
On x86 this code
is more efficient then
since linear access does not invalidate cache too often.
Draw Harness provides TCL interface for OCCT algorithms.
There is no TCL wrapper over OCCT C++ classes, instead interface is provided through the set of TCL commands implemented in C++.
There is a list of common rules which should be followed to implement well-formed Draw Harness command.
Command should return 0 in most cases even if the executed algorithm has failed. Returning 1 would lead to a TCL exception, thus should be used in case of a command line syntax error and similar issues.
Command arguments should be validated before usage. The user should see a human-readable error description instead of a runtime exception from the executed algorithm.
Command should warn the user about unknown arguments, including cases when extra parameters have been pushed for the command with a fixed number of arguments.
Informative messages should be printed into standard output std::cout, whilst command results (if any) – into Draw Interpreter.
Information printed into Draw Interpreter should be well-structured to allow usage in TCL script.
Any command with a long list of obligatory parameters should be considered as ill-formed by design. Optional parameters should start with flag name (with '-' prefix) and followed by its values:
Functions Draw::Atof() and Draw::Atoi() support expressions and read values in C-locale.
class Package_Class { public: //! @name public methods //! Method computes the square value. //! @param theValue the input value //! @return squared value Standard_Export Standard_Real Square (const Standard_Real theValue); private: //! \@name private methods //! Auxiliary method void increment(); private: //! \@name private fields Standard_Integer myCounter; //!< usage counter };