Hopsan
Hopsan Coding Style

The following coding style is the preferred in all Hopsan C++ code.

Bracket Style

  • For functions there shall be one line break before the first curly brace.
  • For if statements, loops and similar, the starting brace shall come at the same line.
  • Single line statements must always be enclosed in braces.

Example:

int MyFunction(int a, int b)
{
int returnValue;
if(a > b) {
returnValue = b-a;
}
else if (a == b) {
returnValue = a+b;
}
else {
returnValue = a-b;
}
return returnValue;
}

Note! The previous (deprecated) style is still used in most of the code. The previous style said that "There shall be one line break before all brackets." This style can still be used if it makes the code easier to read.

Example:

int MyFunctionWithOldBracketStyle(int a, int b)
{
int returnValue;
if(a > b)
{
returnValue = b-a;
}
else
{
returnValue = a-b;
}
return returnValue;
}

Exceptions can be made for short one-line code blocks, but are generally not recommended.

Example:

if(a > max) { a = max; }

Variable Names

All code shall be self commenting. This means that non-obvious abbreviations shall be avoided. The purpose of a variable shall be well described by its name. Exceptions are component equations, where the physical denotation of the variable is to be used.

Correct:

  1. currentTimeStep
  2. distanceToCenter
  3. Kc
  4. rho

Incorrect:

  1. cTimeStep
  2. cTstep
  3. distToC
  4. distC
  5. flowCoefficient
  6. oilDensity

Variables begin with small letters, while every new word in the name shall be capitalized.

Correct:

  1. someHopsanVariable

Incorrect:

  1. somehopsanvariable
  2. SomeHopsanVariable

Certain variables shall have one or more small description letters prepended:

  1. g = Global variable (can be used anywhere in program)
  2. m = Member variable (can only be used in the current class)
  3. p = Pointer

Optional:

  1. v = Vector (array)
  2. n = Number variable

More than one letter can be used at a time. When these letters are prepended, the first letter in the actual variable name shall be capitalized.

Examples:

  1. mSomeHopsanVariable (member variable)
  2. mpSomeHopsanVariable (member pointer)
  3. vpDataVariables (vector with pointers in each element)
  4. mpvDataVariables (member pointer to vector)
  5. gSomeHopsanVariable (global variable)
  6. nThreads (variable describing "number of threads")

All global variables, member variables, pointers and number variables should have these prepended letters. An exception is made for public variables used in a data struct (public class) when its main purpose is to act as a simple data container.

Example:

struct Message
{
int type;
string text;
}
Message myMessage;
  1. myMessage.type (will return the type id of the message)