DECLARATIONS

[Contents] [Prev] [Next]

6 - Declarations

6.1 Number Per Line

Put only one declaration per line since it encourages commenting. In other words:

int level; // indentation level
int size;  // size of table

not:

int level, size;  // this is wrong

6.2 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.

6.3 Placement

Don't declare a variable until it is actually needed.

Avoid local declarations that hide declarations at higher levels. For example, do not declare the same variable name in an inner block:

int count;
...
myMethod() 
{
  if (condition)
  {
    int count = 0;     // AVOID!
    ...
  }
  ...
}

6.4 Class and Interface Declarations

When coding Java classes and interfaces, the following formatting rules should be followed:

  • No space between a method name and the parenthesis "(" starting its parameter list
  • Open brace "{" appears on the next line after the declaration statement
  • Closing brace "}" starts a line by itself indented to match its corresponding opening statement.
class Sample extends Object
{
  int ivar1;
  int ivar2;

  Sample(int i, int j)
  {
    ivar1 = i;
    ivar2 = j;
  }

  int emptyMethod() 
  {
  }

    ...
}
  • Methods are separated by a blank line

[Contents] [Prev] [Next]