Loading...
Searching...
No Matches
Coding Style

# Introduction

This document details the coding practices that are used in the OpenVDB codebase. Contributed code should conform to these guidelines to maintain consistency and maintainability. If there is a rule that you would like clarified, changed, or added, please send a note to openv.nosp@m.db@g.nosp@m.mail..nosp@m.com.

# Contents

- Naming Conventions
  - Namespaces
  - Classes and Structs
  - Class Methods
  - Class Instance Variables
  - Class Static Variables
  - Local Variables and Arguments
  - Constants
  - Enumeration Names
  - Enumeration Values
  - Typedefs
  - Global Variables
  - Global Functions
  - Booleans
- Practices
  - General
  - Formatting
  - Include Statements
  - Comments
  - Primitive Types
  - Macros
  - Classes
  - Conditional Statements
  - Namespaces
  - Exceptions
  - Templates
  - Miscellaneous

# Naming Conventions

## Namespaces

1. Lowercase words, keep simple and short (e.g., `tools`, `tree`).
2. Use `internal` (or `detail`) or module_internal for symbols such as templates that must be defined in header files but that are implementation details not intended for public use.

## Classes and Structs

1. Mixed case; first letter uppercase (e.g., `AffineMap`, `TreeIterator`)
2. Do not use a prefix.

## Class Methods

1. Mixed case; first letter lowercase (e.g., getAccessor(), gridType())
2. Accessor methods that return a member variable by reference or a primitive type by value are just the variable name (e.g., Grid::tree()).
3. Accessor methods that involve construction of objects or other computations are `get` + the variable name (e.g., Grid::getAccessor()).
4. Simple mutators are `set` + the variable name (e.g., Grid::setTree(tree);).

## Class Instance Variables

1. Mixed case; always prefixed by `m` (e.g., `mTree`, `mTransform`)
2. The `m` prefix may be omitted for members of structs used in the public API (e.g., struct Color { float r, g, b; }).

## Class Static Variables

1. Mixed case; always prefixed by `s` (e.g., `sInitialized`)

## Local Variables and Arguments

1. Use mixed case with an initial lower case letter (e.g., `ijk`, `offset`, `range`, `rhsValue`).

## Constants

1. All uppercase; words separated by underscores. If not in a namespace or local to a source file, then prefixed with the library name in all caps (e.g., `HALF_FLOAT_TYPENAME_SUFFIX`, `ZIP_COMPRESSION_LEVEL`)

## Enumeration Names

1. Mixed case; first letter uppercase (e.g., `GridClass`, `VecType`)

## Enumeration Values

1. With `enum`, all uppercase with words separated by underscores (e.g., `GRID_LEVEL_SET`, `VEC_INVARIANT`) and with a common prefix
2. With enum class, mixed case with the first letter uppercase (e.g., `GridClass::Unknown`, `GridClass::LevelSet`)

## Typedefs

1. Mixed case; first letter uppercase (e.g., `ConstPtr`, `ValueType`)
2. Do not use a prefix.

## Global Variables

1. Mixed case; always prefixed by `g` (e.g., `gRegistry`)
2. In general, try to use class static data instead of globals.

## Global Functions

1. Mixed case; always prefixed by `g` (e.g., gFunc()).
2. In general, try to use class static members instead of global functions.

## Booleans

1. When naming boolean functions and variables, use names that read as a condition (e.g., if (grid.empty()), if (matrix.isInvertible())).

# Practices

## General

1. Code must compile without any warning messages at the default warning level.
2. Prefer the C++ Standard Library to the C Standard Library.
3. Restrict variables to the smallest scopes possible, and avoid defining local variables before giving them values. Prefer declarations inside conditionals: if (Grid::Ptr grid = createGrid()) { ... } instead of Grid::Ptr grid = createGrid(); if (grid) { ... }
4. For new files, be sure to use the right license boilerplate per our license policy.

## Formatting

1. Indentation is 4 spaces. Do not use tabs.
2. Lines are no more than 100 characters long.
3. Use Unix-style carriage returns ("\n") rather than Windows/DOS ones ("\r\n").
4. Do not leave debug printfs or other debugging code lying around.
5. Leave a blank line between a group of variable declarations and other code.
6. Leave a space after the keywords `if`, `switch`, `while`, `do`, `for`, and `return`.
7. Leave a space on each side of binary operators such as `+`, `-`, `*`, `/`, `&&`, and `||`. For clarity in mathematical situations, you may omit the spaces on either side of `*` and `/` operators to emphasize their precedence over `+` and `-`.
8. Do not leave a space between any dereferencing operator (such as `*`, `&`, ``[], `->`, or ``.) and its operands.
9. In parameter lists, leave a space after each comma.
10. Do not leave a space after an opening parenthesis or before a closing parenthesis.
11. Parentheses should be used to clarify operator precedence in expressions.
12. Do not leave a space before an end-of-statement semicolon.
13. Do not use literal tabs in strings or character constants. Rather, use spaces or "\t".
14. If a parameter list is too long, break it between parameters. Group related parameters on lines if appropriate.
15. Modified spacing is allowed to vertically align repetitive expressions.
16. Always begin numeric constants with a digit (e.g., 0.001 not .001).
17. Use K&R-style brace placement in public code.
18. You may leave off braces for simple, single line flow control statements.
19. The return type in a function definition should go on a line by itself.

## Include Statements

1. Always use double quotes ("") to include header files that live in the same directory as your source code.
2. Use angle brackets (<>) to include header files from outside a file’s directory.
3. Do not use absolute paths in include directives.
4. If there is a header corresponding to a given source file, list it first, followed by other local headers, library headers and then system headers.

## Header Files

1. Header files have a .h extension.
2. All header files should be bracketed by `#ifdef` "guard" statements.
3. In class definitions, list public, then protected, then private members.
4. List methods before variables.
5. Fully prototype all public functions and use descriptive naming for each argument.
6. Declare every function defined in a header but outside a class definition explicitly as `inline`.
7. Prefer forward declarations to `#include` directives in headers.
8. Do not take advantage of indirect inclusion of header files.
9. Do not use anonymous namespaces in header files.

## Source Files

1. Source files have a .cc extension.
2. Properly prototype all file static functions with usefully named arguments.
3. Whenever possible, put variables and functions in an anonymous namespace.
4. Avoid global variables.

## Comments

1. Use `//` style comments instead of / * * / style, even for multi-line comments.
2. Use multi-line comments to describe following paragraphs of code.
3. Use end-of-line comments to describe variable declarations or to clarify a single statement.
4. Large blocks of code should be commented out with #if 0 and `#endif`.
5. Do not leave obsolete code fragments within comments as an historical trail.
6. Document public code with Doxygen comments, formatted as follows:

       /// @brief Create a new grid of type @c GridType classified as a "Level Set",
       /// i.e., a narrow-band level set.
       ///
       /// @param voxelSize  the size of a voxel in world units
       /// @param halfWidth  the half width of the narrow band in voxel units
       ///
       /// @details The voxel size and the narrow band half width define the grid's
       /// background value as halfWidth*voxelWidth.  The transform is linear
       /// with a uniform scaling only corresponding to the specified voxel size.
       ///
       /// @note It is generally advisable to specify a half-width of the narrow band
       /// that is larger than one voxel unit, otherwise zero crossings are not guaranteed.
       template<typename GridType>
       typename GridType::Ptr createLevelSet(
           Real voxelSize = 1.0, Real halfWidth = LEVEL_SET_HALF_WIDTH);

## Primitive Types

1. Avoid writing code that is dependent on the bit size of primitive values, but when specific bit sizes are required, use explicitly-sized types such as `int32_t` or `uint64_t`.

## Macros

1. Avoid macros for constants. Use global static constants instead. (Local static constants are not guaranteed to be initialized in a thread-safe manner.)
2. Avoid macro functions. Use `inline` and templates instead.

## Classes

1. Constructors that can be called with only one argument should be prefixed with the `explicit` keyword to avoid unintended type conversions.
2. Never call virtual methods from destructors.
3. If you have a copy constructor, make sure you have an assignment operator.
4. If you have an assignment operator, you probably need a copy constructor.
5. If you have data members that are pointers to dynamically allocated memory, make sure you have a copy constructor and an assignment operator, both of which do the right thing with that memory.
6. Classes which are to be subclassed always have a virtual destructor, even if it is empty.
7. Check against self assignment and return *this in assignment operators.
8. Declare methods as `const` wherever possible.
9. Declare object-valued input arguments as const references wherever possible. Primitives may be passed by value, however.
10. Arithmetic, logical, bitwise, dereference, and address of operators should only be used when their semantics are clear, obvious, and unambiguous.
11. The application operator [ () ] is allowed for functors.
12. Conversion operators should be avoided.
13. Never return const references to stack allocated or implicitly computed objects.
14. If a class does not have a copy constructor and/or assignment operator, consider creating a private unimplemented copy constructor and/or assignment operator to prevent automatically generated versions from being used.

## Conditional Statements

1. For test expressions, use a form that indicates as clearly as possible the types of operands by avoiding implicit casts.
2. Assignments that occur within conditional statements must have no effect in the enclosing scope.
3. Allow for arithmetic imprecision when comparing floating point values.
4. In switch statements, always comment fallthroughs and empty cases.

# Namespaces

1. Namespaces should be used whenever possible.
2. Avoid pulling in entire namespaces with `using` directives (e.g., using namespace std;).
3. `using` declarations are allowed for individual symbols (e.g., using std::vector;), but they should never appear in a header file.
4. Define global operators in the namespace of their arguments.
5. Namespaces are not indented.

## Exceptions

1. Appropriate use of exceptions is encouraged.
2. Methods should declare all exceptions they might throw using comments, but not exception specifications.
3. Throw scope local exception instances, not pointers or references or globals.
4. Catch exceptions by reference.
5. Never allow an exception to escape from a destructor.

## Templates

1. Use `typename` rather than `class` when declaring template type parameters.

## Miscellaneous

1. Don’t use pointers to run through arrays of non-primitive types. Use explicit array indexing, iterators or generic algorithms instead.
2. Use C++ casts (static_cast<int>(x) or int(x)), not C casts ((int)x).
3. Multiple variables of the same data type may be declared on the same line if closely related.
4. Library code must never deliberately terminate the application in response to an error condition.
5. Avoid using malloc/free when new/delete can be used instead.
6. Avoid `goto`.
7. Avoid "magic numbers". Use named constants when necessary.
8. If you use typeid/typeinfo, be aware that although all runtimes support typeinfo::name(), the format of the string it returns varies between compilers and even for a given compiler the value is not guaranteed to be unique.