Table of Contents
This page will act as an outline for the coding conventions used within the Spike Engine and recommendations for conventions to be used within projects using the Engine.
Coding conventions are essential for maintaining code readability, consistency, and collaboration within a development team, especially within projects as large as a Game or Engine.
Code that follows an established guideline is easier to understand, maintain, and extend. Throughout this page you will learn the coding conventions used throughout the internals of the Spike Engine.
You can take our conventions as-is, or modify them to suit your team's needs.
We chose our conventions based on the following goals:
Readability: Code may go untouched for long periods of time. This is expected, so we must make code that is understandable with minimal searches.
Extensibility: As the project progresses code will be modified and extended upon. As a result, generic code is split into external libraries with a clear layout for dependent code, forming layers. Equally, code must be minimally tied to other systems where applicable to ensure systems function appropriately, even after multiple edits.
Consistency: Both across documentation and working within the engine, readers and programmers expect a consistent experience, ensuring focus on the content.
Adoption: Many of the classes and functions within Spike and its external libraries are applicable and may be used within other applications. As such, naming should reflect commonly used practices across a range of open-source and industry standard libraries, alongside native C++ functionality.
Currently, code should target C++20, i.e., should not use C++23 features. You should also ideally consider portability to other platforms / environments before using >= C++17 features within the Engine, Libraries or Game Projects.
In general, every header should have an associated source file. Common exceptions include:
Small source files, containing main()
Header only libraries or interfaces / base classes
Correct header usage is important to ensuring readability and providing optimised code.
The following rules will provide general guidelines for using headers.
In general, headers containing code portions should use the hpp extension, while purely definitive headers should use h. This is not strictly vital, nor does it affect performance but can make navigation more intuitive.
All headers should be self contained, this meaning when included within users projects or other portions of the engine, the header has no special conditions to be included. Ideally, if a code portion requires and external library not native to the engine or external Spike libraries, it will be included within the source file(s) with wrappers used for passing required data between users.
A header should have header guards and ideally have no transitive includes (all required includes should be included within the header).
When a header declares inline functions or templates that clients of the header will instantiate, the inline functions and templates must also have definitions in the header, either directly or in files it includes. Do not move these definitions to separately included header file(s).
All headers need guards to prevent multiple inclusion, either via the pragma or define methods:
To ensure the define is unique, it should include the solution name, project name and header name
Only include header files which contain the definitions or declarations of required symbols, a header file does not need to be included otherwise.
As stated above, do not rely on transitive inclusions. This allows for easy dependency tracking. This also extends to source files.
Include the definition of a function at its point of declaration in a header file only when the definition is short. If necessary to make the definition ODR-safe, mark it with an inline specifier.
If this is done, if the function is larger than 10 lines, it is worth separating out the definition below the class within a pragma region or comment, keeping the definition clean.
It is recommended to include headers in the following order:
Related headers
C system headers
C++ standard library headers
External library headers
Your projects headers
Equally, all includes should be listed from the source directory where applicable (e.g. "source-folder/header.h")
Separating each include chunk with an empty line can keep the header neat and make ensuring OOI easier.
Sometimes, system-specific code needs conditional includes. Such code can put conditional includes after other includes. Of course, keep your system-specific code small and localised. Ideally, implement interfaces where applicable, confining conditionals to small code regions and providing common interfaces within other code portions.
ideally headers should be prefaced with a header summary, outlining the content contained within the header, e.g.
Ideally, only include external library headers within source files, removing the dependencies from other projects using said headers.
With few exceptions, place code in a namespace.
Namespaces should have unique names based on the project name, and possibly its subsection / use-case. Do not use the using-directive (e.g., using namespace foo) and do not use inline namespaces, as these can negate the intended scoping from a namespace.
It is worth ensuring namespaces do not become deeply nested as in some situations, fully-qualified names are required, creating a lot of clutter.
Namespaces should be written in lowercase.
If a method, class, struct or variable does not need to be referenced outside of the source file, provide internal linkage by placing them within an unnamed namespace or declaring them static.
Prefer placing free functions within a namespace. Avoid creating a class of entirely static functions without good reason (e.g. a static member variable required by many functions).
Free functions should use snake case e.g. function_name.
Member functions should make use of camel case e.g. FunctionName.
Leaf functions handling operations that will not throw such as maths functions should use the noexcept specifier, as seen within the Spike Maths Library.
Local variables should be defined within the lowest scope possible and initialised at declaration.
For variables used within conditional statements, they should ideally be defined within those statements to ensure they are confined to that scope. With an exception being objects (classes or structs), that are local to the method, it may be more efficient to declare the variable outside of the loop and if needed, define a reset function if a clean slate of the object is needed per iteration.
Objects with static storage duration are highly discouraged in most scenarios.
Global and static variables are very useful for a large number of applications: named constants, auxiliary data structures internal to some translation unit, logging, registration mechanisms, backends, etc.
However, static objects with non trivial destructors can cause hard to find bugs based on destruction order issues.
Avoid virtual method calls in constructors, and avoid initialization that can fail if you can’t signal an error. Member variables should be initialised here.
Do not define implicit conversions. Use the explicit keyword for conversion operators and single-argument constructors. Implicit Conversions can result in potentially unintended behaviour that raises no errors, resulting in potentially difficult to find bugs.
Use structs for passive objects/PODs that carry data or custom data types e.g. vector3, quaternion etc. Everything else is a class.
Class names should be written in camel case (ClassName) while structs should be written in full lowercase or snake case (optionone or option_two).
A struct should be preferred as using a struct can provide a meaningful name to each member variable, resulting in more readable code when compared with .first or std::get<X>.
All inheritance must be public. If private inheritance is desired, prefer using a private member of the base class instead. Equally, the final kayword should be used on classes who are not intended to be base classes.
Do not overuse implementation inheritance. Composition is often more appropriate. Try to restrict the use of inheritance to the “is-a” case: Bar should inherit from Foo if it can reasonably be said that Bar “is a kind of” Foo.
Annotate overrides of virtual functions or virtual destructors with an override or final specifier. Do not use virtual when declaring an override.
Operators should be overloaded where appropriate, ideally using the noexcept specifier if not calling code that may throw, as seen within the Spike Maths Library.
Do not use user-defined literals.
Member methods and variables should be grouped based on focus, with variables coming before any method declarations.
Member variables of different access control may be placed in any order, usually preferring the order; private, protected, public. Empty sections may be omitted.
As for methods, prefer the opposite order, with constructors and destructors being declared first, and overloaded operators being declared last.
See Defining Functions in Header Files for details on methods.
We allow use of friend classes and functions, within reason.
Friends should usually be defined in the same file so that the reader does not have to look in another file to find uses of the private members of a class.
Friends extend the encapsulation boundary of a class. In some cases this is better than making a member public when you want to give only one other class access to it. However, most classes should interact with other classes solely through their public members.
Prefer small and focused functions.
We recognise that long functions are sometimes appropriate, so no hard limit is placed on functions length. If a function exceeds about 40 lines, think about whether it can be broken up without harming the structure of the program.
Even if your long function works perfectly now, someone modifying it in a few months may add new behaviour. This could result in bugs that are hard to find. Keeping your functions short and simple makes it easier for other people to read and modify your code, and subsequently test those modifications.
Use overloaded functions only if a reader looking at a usage can get a good idea of what is happening without having to first figure out exactly which overload is being called.
You may overload a function when there are no semantic differences between variants. These overloads may vary in types, qualifiers, or argument count. However, a reader of such a call must not need to know which overload is chosen.
Prefer a single, comprehensive comment that documents the entire overload set and is placed before the first declaration.
Where a reader might have difficulty connecting the umbrella comment to a specific overload, have a comment for specific overloads.
Smart pointers provide greater control and safety compared to raw pointers but may not be applicable in all scenarios.
Unique pointers hold sole ownership of an object, destroying it once out of scope. These can avoid the need for the delete call. These cannot be copied but may be moved, representing a transfer of ownership.
Shared pointers (or ref within Spike) express shared ownership of an object with a reference counter. They may be moved or copied with ownership shared between all references. The associated object is deleted once all shared pointers to it are destroyed.
Raw pointers have no ownership management of their object, meaning they must be deleted before leaving scope, else memory may be leaked. These are commonly used within game engines or performance critical code, assuming there is appropriate memory management in place to prevent memory leaks.
Do not use exceptions. It is recommended to use manual error handling. Exceptions at face value provide greater benefits than drawbacks, but integration into existing code has implications on all dependent code. If exceptions can be propagated beyond a project, it also becomes problematic to integrate the project into existing exception-free code, such as the integration of exceptions within the spike libraries.
Equally, spike libraries provide an error header that contains custom user error types that may be extended with optional message parameters for more context. Equally, most situations where an error may occur are errors that are non critical. As a result, it is more beneficial to use the manual error handling to allow the program to handle errors safely and continue execution without crashing.
Exceptions to this rule include more critical systems such as memory management. Such as within spike libraries, where try-catch blocks are used around vectors within the stack allocators.
If in doubt, use these rules:
If an error is expected during runtime, use a detectable result e.g. nullptr, errlib::Error etc.
If using errlib::Error, ensure enough context is given to allow a user to determine the error appropriately and log to their own logging systems if desired.
If an error should not occur in a correct build, use an assertion e.g. for internal invariants.
A good example is within DearImGui, for the assertions on a missing End call, this allows user to catch these self inflicted errors during development.
Ideally, do not use assertions to handle bad input or runtime failures, these should be handled via the return types above.
Make sure to include runtime handling on-top of assertions if an assertion is being used for some runtime errors, using the assertion only as an additional debug diagnostic.
Exceptions are only valid if you are using an exception-based API and have critical errors that may occur at runtime and are capable of occurring within a correct build.
Use the noexcept keyword when a function is guaranteed not to throw an exception. Equally, using noexcept on a class or structs move constructor can improve performance, such as within vectors, whereby resizing will result in movement of the objects into the new larger vector, rather than copying them.
Prefer unconditional noexcept if exceptions are completely disabled .
Prefer against using RTTI. RTTI allows querying the C++ class of an object at run-time. This is done through the use of typeid or dynamic_cast.
RTTI is beneficial in some scenarios, such as handling many abstract objects e.g. a vector of base class pointers.
However, use of RTTI can make code hard to maintain. It can lead to type-based decision trees or switch statements scattered throughout the code, all of which must be examined when making further changes.
Under type-based decisions, it may be more beneficial to use a virtual method or the visitor design pattern.
Prefer C++ style casts static_cast<T>(X) or brace initialisation T{X} over C style casting. An exception is when casting to void.
Uses:
Use brace initialisation for arithmetic types
For explicit conversion, use static_cast
Use static_cast as a C-style cast when you need to explicitly up-cast a pointer from a class to its base-class, or when you need to explicitly cast a pointer from a base-class to a subclass. In this case, you must be sure your object is actually an instance of the subclass.
Use const_cast to remove the const qualifier
Use reinterpret_cast to do unsafe conversions of pointer types to and from integer and other pointer types, including void*.
Use the prefix form (++i) of the increment and decrement operators unless you need postfix semantics.
This can avoid an extra variable (copied its value before the operation).
Use const whenever it makes sense. constexpr is a better choice for some uses of const such as global constant variables (e.g. PI).
Use constexpr to define true constants or to ensure constant initialization. Use constinit to ensure constant initialization for non-constant variables. Functions can be declared consteval to restrict their use to compile time.
Do not use constexpr or consteval to force inlining.
The standard library header <stdint.h> defines types like int16_t, uint32_t, int64_t, etc, which have shortened aliases within spike libraries def_aliases.h. You should always use those in preference to short, unsigned long long, and the like, when you need a guarantee on the size of an integer. Of the built-in integer types, only int should be used.
Prefer using signed integer types unless the value is used as a bit pattern or the value should be able to go past its maximum signed value. if you merely need to ensure a number is never negative, use assertions.
Try to use iterators and containers rather than pointers and sizes, try not to mix signedness, and try to avoid unsigned types (except for representing bitfields or modular arithmetic). Do not use an unsigned type merely to assert that a variable is non-negative.
If you need to work with memory addresses as integers, store them in uintptr_t rather than uint32_t or uint64_t.
Prefer against using macros, instead using inline functions, enums and const variables. Otherwise, prefix a macro with the namespace to prevent collision.
Macros can do things these other techniques cannot, and you do see them in many codebases. And some of their special features (like stringifying, concatenation, etc) are not available through the language properly. But before using a macro, it is worth considering carefully whether there’s a non-macro way to achieve the same result. This can improve debugging significantly.
For pointers, use nullptr and for chars use '\0'.
The most important consistency rules are those that govern naming. The style of a name immediately informs us what sort of thing the named entity is; a type, a variable, a function, a constant, a macro, etc.