Header Ads

  • Breaking Now

    Java Coding Standards:Layout

    In this post, some of the best practices of Layout used while coding in Java, has been enumerated. This helps better readability of code and hence better understanding for people who are going to maintain code.Some thumb rules which are nice to follow:

    -Where possible the lines of code within a method should fit on one screen (1024 resolution). If not the method should be decomposed further in a logical manner.
    -Files longer than 800 lines are cumbersome and should be avoided.
    -Use an indentation level of one tab (4 spaces).Avoid lines longer than 120 characters, since they're not handled well by many terminals and tools.Spillover indentation for breaking up long lines.
    -Give blank lines between major sections and blocks of code.
    -Do put spaces around arithmetic binary operators such as +(plus).
    -Do put spaces around assignment and conditional operators.
    -Do put one space following commas and semicolons.
    -Do put one space following keywords (if, while,for…..).
    -Do put the return type of the function on the same line as the function name.
    -Do not put space between unary and postfix operators and their operands, dot and the subscript.
    -Do Not put spaces around parenthesis used in function invocations or declarations.
    -The Tertiary Conditional Operator expression ? op1 : op2 should be avoided unless it makes the return expression more obvious / clearer. Ideally, explicit return values should be used.
    -A return statement with a value should not use parenthesis unless they make the return value more obvious in some way.

    Example:
    return;
    return myDisk.size();
    return (size>10 ? size : defaultSize);

    -No Space between a method name and the parenthesis "(" starting its parameter list
    Ideally, there should only be one return from method. Unless there is a real need for some fail fast logic. The exit path from a method should be clearly defined with only one return.
    -Open brace "{" should appear at the end of the same line as the declaration statement.
    Closing brace "}" starts a line by itself indented to match its corresponding opening statement, except when it is a null statement the "}" should appear immediately after the "{".
    -Always use braces {} in if-else and loop statements, even though the statement is a single line.
    Try-catch statements should be in the following format

    try{
    statements;
    }
    catch (ExceptionClass e) {}

    -Leave one blank line between methods between the local variables in a method and its first statement,before a block or single-line comment,between logical sections inside a method to improve readability.
    -Leave one blank space after the commas in argument lists of the methods.

    Have fun while coding. :-))

    Post Top Ad

    Post Bottom Ad