wiki:CodingStandards

Version 5 (modified by shauser, 54 years ago) (diff)

--

OpenSHA Coding Standards

Anyone working on OpenSHA should strive to write efficient, well-documented, and testable code. To encourage readability and uniform presentation, several syntactic standards to which this project adheres are outlined below. Most of the recommended syntax configurations can be set within your IDE of choice.

Syntax

Tabs : Use tabs, not spaces. This allows individuals to adjust indentation to their liking.

Line Length : Limit lines to 80 characters. Wrap long lines appropriately.

Line Wrapping : Indent wrapped lines with two tabs.

Code Blocks : methods, for-loops, if-statements, etc...

  • The opening bracket "{" of any new block should be on the same line as the start of the block
  • The closing bracket should be on its own line aligned to the opening indentation of the block.
  • The only exception is the case of where the entire block can fit on one line, e.g.:
    if (false) return;
    

Arguments/Parameters? : There shall be a single space character between the method name (or logical controller i.e. "for", "if", "while"), and the opening parenthesis "(", and additional white space between each argument. There shall not be white-space between the argument and its successive separator ("," or ";" etc...) nor shall there be white space between the enclosing parenthesis and its arguments. For example:

Good

public void foo (String str, int k) {
    for (int i = 0; i < 10; ++i) {
        System.out.println(i);
    }
    int j = 10;
    do {
        System.out.println(j--);
    } while (j>0);    
}

Bad

public void foo( String str , int k ) {
    for(int i=0;i<10;++i){
      System.out.println(i);
    }
    int j = 10;
    do{
        System.out.println(j--);
    }while(j>0);
}

Scoping Method/Member? Modifiers : All class members and methods should be fully scoped as applicable. That is, make use of "public"/"protected"/"private", "static", "final" etc... These should go in the order of (for example), public static final String CONST_MEMBER = "Foo";.

Coding for Efficiency

Pre- vs. Post- Increment/Decrement? : When using the pre-/post- increment/decrement operators, one should favor the "pre" form for byte-code efficiency unless the return value is being utilized. Most modern compilers should perform this optimization for you, but why be lazy? Example:

Good

for (int i = 0; i < 10; ++i) {
    ...
}
int j = 0;
while (j < 10) {
    int previous = j++;
    // ... Work with "previous" and "j" ...
    // Where j = previous + 1
}

Bad

for (int i = 0; i < 10; i++) {
    ...
}

Incremental Assignment : Use it. These are the "+=", "-=", "*=", "/=" operators. They can be used on any numerical primitive, and the "+=" can be used on the java.lang.String as well. These have been optimized for efficiency. Example:

Good

int i = 10;
i += 20; // "i" is now 30.

Bad

int i = 10;
i = i + 20; // "i" is now 30.