Saturday, 14 September 2013

Java Best Practice – White Spaces


Blank Lines
Blank lines improved readability by setting off sections of code that are locally related.
Two blank lines should always be used in the following circumstances:
  1. Between sections of source file
  2. Between class and interface definitions
One blank line should always be used in the following circumstances:
  1. Between methods
  2. Between the local variables and its first statement
  3. Before a block or single line comment
  4. Between logical sections inside a method to improve readability
Blank Space
Blank space should be used in the following circumstance:
  • A keyword followed by parenthesis should be separated by a space.Example:
while (true) {



}
Note that a blank space should not be used between a method name and its opening parenthesis.This helps to distinguish keyword from method calls
  • A blank space should appear after commas in argument lists.
  • All binary operators expect “.” should be separated from their operands by pace.Blank space should never separate unary operators such as unary minus, increment(“++”), and decrement(“—”) from their operands.Example:
a += c + d;

a = (a + b) / (c * d);

while (d++ == s++) {

n++;

}

prints(“size is ” + foo + “\n”);
  • The expressions in a for statement should be separated by blank space. Example
 for (expr1; expr2; expr3) 
  • Casts should be followed by blank space. Examples:
methodName1((byte) aNum, (Object) x);

methodName2((int) (cp + 5), ((int) (i+3))

+1);

0 comments

Post a Comment