Open CASCADE Technology
6.7.0
|
|
The purpose of this document is to define and formalize one style of programming for developers working on Open CASCADE Technology. The establishment of a common style facilitates understanding and maintaining code developed by more than one programmer as well as making it easier for several people to co-operate in the development of the same framework. In addition, following a common programming style enables the construction of tools that incorporate knowledge of these standards to help in the programming task. Using a consistent coding style throughout a particular module, package, or project is important because it allows people other than the author, and the author himself, to easily understand and (hopefully) maintain the code. Most programming styles are somewhat arbitrary, and this one is no exception. Some guidelines have been excerpted from the public domain of widely accepted practices. This suggests that the guide will continue to evolve over time as new ideas and enhancements are added.
Rules in this document was written for C++ code. However, with minor exceptions due to language restrictions, them should be applied to any sources in Open CASCADE Technology framework, including:
The names considered in this section are mainly those which compound the interface to Open CASCADE Technology libraries as well as source code itself.
All names are composed of English words and their abbreviations. Open CASCADE Technology is an open source available for international community.
Names should be suggestive or, at least, contain a suggestive part. Currently, there is no exact rule that would define how to generate suggestive names. However, usually names given to toolkits, packages, classes and methods are suggestive. Here are several examples:
Names that define logically connected functionality should have the same prefix (start with the same letters) or, at least, have any other common part in them. As an example the method GetCoord can be given. It 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 unit (e.g. package) is a set of classes, methods, enumerations or any other sources implementing certain common functionality which, to the certain extent, is self contained and independent from other parts of library.
Names of units should not contain underscores, except cases where usage of underscores is allowed explicitly. Usually names of files consisting Open CASCADE Technology are constructed according to the rules defined in the appropriate sections of this document.
The following extensions should be used for source files, depending on their type:
.cdl - CDL declaration files .cxx - C++ source files .hxx - C++ header files .lxx - headers with definitions of inline methods (CDL packages)
The following rules are usually used in naming of toolkits:
Toolkits names are prefixed by TK, followed by suggestive part of name explaining the domain of functionality covered by the toolkit (e.g. TKOpenGl).
Usually source files located in the unit have names that start from the name of the unit, separated from remaining part of file name (if any) by underscore "_". For instance, names of files containing sources of C++ classes are constructed according to the following template.
The following template should be used for names of files containing sources of C++ classes:
<unit-name>_<class-name>.cxx (.hxx, .cdl etc.)
Files that contain sources related to whole unit are called by the name of unit with appropriate extension.
The term 'function' here is defined as:
It is preferred to name public methods from upper case, while protected and private methods from low case.
There are several rules that describe currently accepted practice used for naming variables.
Name of variable should not conflict with the global names (packages, macros, functions, global variables etc.), either existing or possible. The name of variable should not start with underscore(s).
See the following examples:
The name of a function (procedure, class method) parameter should start with 'the' followed by the rest of the name starting with capital letter.
See the following examples:
The name of a class member variable should start with 'my' followed by the rest of the name (rule for suggestive names applies) starting with capital letter.
See the following examples:
It is strongly recommended to avoid defining any global variables. However, as soon as global variable is necessary, the following rule applies. Global variable 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 spelled upper-case and started with 'THE_' prefix:
Local variable name should be constructed in such way that it can be distinguished 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' (also 'is', 'to' and 'has' for Boolean variables).
See the following examples:
Avoid dummy names like I, j, k. Such names are meaningless and easy to mix up. Code becomes more and more complicated when such dummy names used multiple times in code with different meaning, in cycles with different iteration ranges and so on.
See the following examples for preferred style:
In order 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.
In all sources try not to exceed 120 characters limit of line length.
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 English. C/C++ reserved words, commas, colons and semicolons should be followed by a space character if they are not at the end of line. There should be no space characters after '(' and before ')'. Closing and opening brackets should be separated by a space character. For better readability it is also recommended to surround conventional operators by a space character. See the following 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 description of purpose. See the following example:
Figure brackets '{', '}' and each operator (for, if, else, try, catch) should be on dedicated line. General block should have layout similarly to the following:
Entering block increases and leaving block decreases indentation to one tabulation.
Single-line conditional operator (if, while, for etc.) can be written without brackets on the following line.
Code on the same line is less convenient for debugging.
Use alignment wherever it enhances readability. See the following example:
Comments should be indented similar to the code which they refer to or can be on the same line if they are short. Text should be delimited with single space character from slash. See the following example:
Prefer early return condition rather than collecting indentations. Better write like this:
rather than:
to improve readability and reduce unnecessary indentation depth.
Trailing spaces should be removed when possible. Spaces at end of line are useless and do not affect functionality.
Split into groups: system headers, per framework headers, project headers; sort includes list alphabetically. This rule can improve readability, allows detection of useless header's multiple inclusions and makes 3rd-party dependencies clearly visible.
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 of that code, and to serve as basis for other documents. The main reasons why 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 or .cdl). The comment should give enough details for the reader to understand the purpose of the class and main way of work with it.
Each class or package method should be documented in the header file (.hxx or .cdl). 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 does each part of code, and get familiar with it. It is recommended to comment all static functions (like methods in headers), and at least each 10-100 lines of the function bodies. There are also some rules that define how comments should be formatted, see section "Formatting Rules". Following these rules is important for good comprehension of the comments; moreover it makes possible to automatically generate user-oriented documentation directly from commented sources.
The following set of rules defines 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 making possible extensions of your class the user should not encounter with problems of private implementations. Try to use protected members and virtual methods wherever you expect extensions in the future.
Avoid using 'friend' classes or functions except some specific cases (ex., 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 level of an application.
When compiling the source pay attention to and try to minimize compiler warnings.
Try to minimize compilation dependencies by removing unnecessary inclusion.
This section defines rules for writing portable and maintainable C/C++ source code.
Use package or class methods returning reference to wrap global variables to reduces 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. Magic numbers are badly to read and maintain.
A class with any of (destructor, assignment operator, copy constructor) usually needs all of them.
A class with virtual function(s) ought to have a virtual destructor.
Do not redefine a default parameter value in an inherited function.
Use const modifier wherever possible (functions parameters, return values etc.)
Avoid goto statement except the cases where it is really needed.
Declaring 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.
It is required that 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 (C++11, until all major compliers on all supported platforms do not implement all it features) should be optional (escaped with appropriate preprocessor checks) and non-exclusive (alternative implementation should be provided, compatible with other compilers).
Avoid usage of global variables. Usage of global variables may cause problems of accessing them from another shared library. Instead of global variables, use global (package or class) functions that return reference to static variable local to this function. 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 - see Standard_Integer, Standard_Real, Standard_ShortReal, Standard_Boolean, Standard_CString and others) or 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 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, make sure to 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 that purpose, use a pointer at one (subordinate) side. See the following example:
In MyPackage.cdl:
class MyFirstHandle; class MySecondHandle; pointer MySecondPointer to MySecondHandle; ...
In MyPackage_MyFirstHandle.cdl:
class MyFirstHandle from MyPackage ... is ... SetSecondHandleA (me: mutable; theSecond: MySecondHandle from MyPackage); SetSecondHandleB (me: mutable; theSecond: MySecondHandle from MyPackage); ... fields ... mySecondHandle : MySecondHandle from MyPackage; mySecondPointer : MySecondPointer from MyPackage; ... end MyFirstHandle from MyPackage;
In MyPackage_MySecondHandle.cdl:
class MySecondHandle from MyPackage ... is ... SetFirstHandle (me: mutable; theFirst: MyFirstHandle from MyPackage); ... fields ... myFirstHandle : MyFirstHandle from MyPackage; ... end MySecondHandle from MyPackage;
In C++ code:
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 guarantied by following 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 infinity values within sanity 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 order.
Since the order of iteration is unpredictable in this case, 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 destructor.
Avoid possible assignments of the temporary object to a reference. Different behavior for different compiler of different platforms.
These rules define the ways of avoiding possible loss of performance caused by ineffective programming.
In a class, declare its fields 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.
In class constructors prefer initialization over assignment.
When programming procedures with extensive memory access, try to optimize them in terms of cache behavior. Here is an example of how cache behavior can be impact: On x86 this code
is more efficient than
since linear access (above) does not invalidate cache too often.
Here is C++ source file sample:
//! Sample documented class 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 };
TCL script for Draw Harness:
GLSL program: