You are here: Home Service Coding Style & Conventions

Coding Style & Conventions

 

General Recommendations

  • Check for errors early and often. Return from errors immediately.
  • Have you checked for compiler warnings? Warnings often point to real bugs.
  • Use an efficient debug output implementation through a macro statement, a function call or an object method.
  • If possible reduce object and file dependencies. Eliminate needless import or include statements.
  • All identifier, names and comments should be written in English.
  • Check again for warnings or errors before committing source code.

 

Source File Structure

  • Source file names should have the right suffix: .c .h .cpp .cxx .java etc.
  • Use Unix-style carriage returns ("\n") rather than Windows/DOS ones ("\r\n").
  • File content should be kept within 80 columns (for laptop side-by-side diffing, two-window tiling or hardcopy printing).
  • Special whitespace characters like TAB and page break must be avoided.
  • Avoid non-ASCII characters and use a standard encoding scheme (e.g. UTF-8).
  • Break lines after a comma or an operator. Align the new line with the beginning of the expression on the previous line.
totalSum=a+b+c+
         d+e;

method(param1,param2,
       param3);

setText("Long line split"+
         "into two parts.");
  • Reserved words, colons and semicolons should be and operators may be surrounded by a space character.
  • Apply 1..4 spaces as indentation per logic level. Note that class visibility and goto labels do not consume a logic level.
  • Logical units within a block should be separated by one blank line.
// Create a new identity matrix
Matrix4x4 matrix=new Matrix4x4();

// Precompute angles for efficiency
double cosAngle=Math.cos(angle);
double sinAngle=Math.sin(angle);

// Specify matrix as a rotation transformation
matrix.setElement(1,1, cosAngle);
matrix.setElement(1,2, sinAngle);
matrix.setElement(2,1,-sinAngle);
matrix.setElement(2,2, cosAngle);

// Apply rotation
transformation.multiply(matrix);
  • Parentheses after function names and terminating semicolons have no space before them.
  • Use either the // or /*...*/ syntax for comments, as long as you are consistent.
  • There should be a space after the starting comment identifier.
  • All comments must follow the documentation rules for your project.
  • For JavaDoc comments use the following form.
/**
 * Return lateral location of the specified position.
 * If the position is unset, NaN is returned.
 *
 * @param x    X coordinate of position.
 * @param y    Y coordinate of position.
 * @param zone Zone of position.
 * @return     Lateral location.
 * @throws IllegalArgumentException  If zone is <= 0.
 */

public double computeLocation(double x, double y, int zone)
{
 ...
}
  • Start with a one-line caption (as precise as possible) followed by a more detailed description.
  • When using a software repository, omit tags like @author, @version or @change-date.
  • Insert TODO in a comment to flag something that has to be implemented.
  • Use FIXME to flag something that is currently bogus and broken.
  • Comments should be indented relative to their position in the code.
while (true)           // NOT:  while (true)
{                               { 
  // Do something               // Do something
  something();                     something();
}                               }

 

Statements

  • Type conversions must always be done explicitly. Never rely on implicit type conversions (C/C++ only).
  • Array specifiers must be attached to the type not the variable (Java only).
  • Variables should be initialized where they are declared (C/C++ only).
  • Variables should be declared in the smallest scope possible.
  • Variables must never have dual meaning.
  • Class variables should never be declared public.
  • Variables should be kept alive for as short a time as possible.
  • Complex conditional expressions should be avoided. Consider evaluation functions or methods.
// BAD:
if ((elementNo<0) || (elementNo>maxElement)|| elementNo==lastElement) {...}

// GOOD:
if (isFinished(elementNo,maxElement) || isRepeatedEntry(elementNo,lastElement)) {...}

boolean isFinished(int num, int max) {return((num<0) || (num>max));}
boolean isRepeatedEntry(int num, int last) {return((num==last));}
  • The usage of confusing expressions with non-obvious side effects must be avoided (e.g. comma operator).
  • Floating point constants should always be written with decimal point and at least one decimal.
  • Always write { ... } to properly enclose simple statements (e.g. after for/while/then/else keywords).
  • It is a good idea to use parentheses liberally to avoid operator precedence problems. Even if it seems clear to you.
if (a==b && c==d)     // AVOID
if ((a==b) && (c==d)) // RIGHT

 

Naming Conventions

  • Use "interCaps" and leading-lowercases for all identifiers (if syntactically possible).
long updateStatusBar();
  • Use Java-Style Constants. The name should be all uppercase, with underscores between words.
const long ERROR_UNDEFINED_VARIABLE=1;
  • Abbreviations and acronyms should not be uppercase when used as name.
exportHtmlSource(); // NOT: exportHTMLSource();
  • The name of the object is implicit, and should be avoided in a method name.
line.getLength();   // NOT: line.getLineLength();
  • Complement names should be used for complement entities.
get/set, add/remove, create/destroy, start/stop, insert/delete,
increment/decrement, old/new, begin/end, first/last, up/down, min/max,
next/previous, old/new, open/close, show/hide, suspend/resume, etc.
  • Abbreviations in names should be avoided.
computeAverage();     // NOT: compAvg();
ActionEvent event;    // NOT: ActionEvent e;
  • Negated boolean variable names must be avoided.
boolean isError;   // NOT: isNoError
boolean isFound;   // NOT: isNotFound
  • Respect the projects rules for prefix characters to variable names.
g (global)   => g_DataLen       // outside of class namespaces (C/C++ only)
s (static)   => s_PrefChecked   //
m (member)   => m_Length        //
  • Associated constants (final variables) should be prefixed by a common type name.
final int COLOR_RED=1;
final int COLOR_GREEN=2;
final int COLOR_BLUE=3;