Jun 27, 2013

Study Notes on Java Code Conventions September 12, 1997

When I was finding some resources, I happened to find an interesting document:

Java
Code Conventions

September 12, 1997 

I was very curious about what rules our respected programmer predecessors made on how to code Java, and these rules are still the rules today. The document can be found here: http://www.oracle.com/technetwork/java/codeconventions-150003.pdf, and below is the notes that I find useful for myself, and maybe useful for you.

1. Initialization
Try to initialize local variables where they’re declared. The only reason not to initialize a

variable where it’s declared is if the initial value depends on some computation occurring first.

2. Number Per Line
One declaration per line is recommended since it encourages commenting. In other words,
    int level; // indentation level
   int size; // size of table
is preferred over
    int level, size;

3. Return Statements
A return statement with a value should not use parentheses unless they make the return value
more obvious in some way. Example:
    return;
   return myDisk.size();

   return (size ? size : defaultSize);

4. if Statements 
Always use braces {}, and avoid the following error-prone form:
    if (condition) //AVOID! THIS OMITS THE BRACES {}!
        statement;

5. switch Statement
A switch statement should have the following form:
    switch (condition) {
        case ABC:
            statements;
            /* falls through */
        case DEF:
            statements;
            break;
        case XYZ:
            statements;
            break;
        default:
            statements;
            break;
    }
Every time a case falls through (doesn’t include a break statement), add a comment where the
breakstatement would normally be. This is shown in the preceding code example with the
/* falls through */ comment.
Every switch statement should include a default case. The break in the default case is
redundant, but it prevents a fall-through error if later another case is added.

6. Casts should be followed by a blank
    myMethod((byte) aNum, (Object) x);
   myFunc((int) (cp + 5), ((int) (i + 3))+ 1);

7. Variable Assignments
Avoid assigning several variables to the same value in a single statement. It is hard to read.
Example:
    fooBar.fChar = barFoo.lchar = 'c'; // AVOID!

8.Special Comments
Use XXX in a comment to flag something that is bogus but works. Use FIXME to flag something that is bogus and broken.


No comments: