Indentation and White Space


[Page 813]

The use of indentation and white space helps to improve the readability of the program. White space refers to the use of blank lines and blank space in a program. It should be used to separate one program element from another, in order to draw attention to the important elements of the program.

  • Use a blank line to separate method definitions and to separate a class's instance variables from its methods.

  • Use blank spaces within expressions and statements to enhance their readability.

  • Be consistent in the way you use white space in your program.

Code should be indented in a way that shows the logical structure of the program. You should use a consistent number of spaces as the size of the indentation tab. The Java Language Specification recommends four spaces.

In general, indentation should represent the contained in relationships within the program. For example, a class definition contains declarations for instance variables and definitions of methods. The declarations and definitions should be indented by the same amount throughout the class definition. The statements contained in the body of a method definition should be indented:

public void instanceMethod() {     System.out.println("Hello");     return; } 


An if statement contains an if clause and an else clause, which should be indented:

if (condition)     System.out.println("If part");   // If clause else     System.out.println("Else part"); // Else clause 


The statements contained in the body of a loop should be indented:

for (int k = 0; k < 100; k++) {      System.out.println("Hello " + 'k'); // Loop body } 


Finally, indentation should be used whenever a statement or expression is too long to fit on a single line. Generally, lines should be no longer than 80 characters.




Java, Java, Java(c) Object-Orienting Problem Solving
Java, Java, Java, Object-Oriented Problem Solving (3rd Edition)
ISBN: 0131474340
EAN: 2147483647
Year: 2005
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net