Skip to content

Code style guide

Alexandre Chatiron edited this page Jun 24, 2015 · 1 revision

Unless it contradicts a rule written here, Oracle's Code Conventions for the Java Programming Language are used.

Whitespace

  • Use spaces, not tabs
  • Use 4 space characters to indent
  • A line should not exceed 100 characters
  • Lines should not contain trailing spaces.

Symbols

  • Always use braces around blocks, even single line blocks.
  • The opening brace is always on the same line as the if statement, except when you have multiple arguments.
if (arg1 ||
    arg2 < arg1 ||
    arg3)
{
  doSomething();
}
  • When breaking logic, || and && at the end of the line.
  • One instruction per line.
  • Always put else on its own line.

Function and variable names

  • Use US English for function and variable names.
  • Use full English words for variable names. Examples: documentProvider but not docProv, feedElement but not fdElt. Variable names reduced to a single letter should not be used, unless in indexes such as in for loops.
  • Do not prefix interface types with I, and do not prefix abstract types with Abstract

Comments

  • Comments should be in grammatically-correct US English, with full sentences that include punctuation.
  • Javadoc comments before classes or methods are not mandatory.
  • Don't include empty javadoc. Either the javadoc provides information and it's good to have it, or it doesn't and shouldn't be there.
  • Do not leave commented-out code in source files. If the code is no longer used, just delete it. We can always use the Git history to get it back if necessary. Similarly, delete any dead code.

General Java Guidelines

  • Do not use raw types: List<String> rather than simply List.
  • Do not leave useless import statements in the code.
  • Use the Override annotation whenever possible (but not for interface implementations as it breaks Java 5 compatibility).
  • Do not ignore exceptions (no @try@ with an empty @catch@ block). If you don't handle a checked exception you can either add a throw to your method declaration (if you believe the exception is worth staying checked) or throw it again as a RuntimeException if it's rare enough so users of your method shouldn't have to care.
try {
   // Code with a checked exception that shouldn't be checked
} catch(Exception e) {`
   throw new RuntimeException(e); // This will propagate to the controller,
                                  // and the developer will see the exception in his web browser
                                  // (or it will be logged if in production mode)
}
  • Prefer enum to int constants.