Java Reference
In-Depth Information
Spacing
Statement formatting
Variable declaration formatting
Most of these formatting rules have been designed so that people reading your code can
do so using the IDE, editor, screen resolution, and so forth of their choice. If you were to
choose a nonstandard formatting convention, then others may find your code hard to read.
Caution Do not ever forget that you will be submitting your source code to an unknown assessor for
review. You really need to write your code so that it is a pleasure for them to assess. This also applies in your
real job—you should always be writing code that your coworkers are happy to use.
Indentation
The Sun Coding Conventions contain the following indentation requirement: “Four spaces
should be used as the unit of indentation. The exact construction of the indentation (spaces
vs. tabs) is unspecified. Tabs must be set exactly every 8 spaces (not 4)” (Sun Coding Conven-
tions, http://java.sun.com/docs/codeconv/html/CodeConventions.doc3.html , 1999).
This description seems to cause a great deal of confusion when first read, so an example
is in order:
1 public class IndentationExample {
2 /* this line is indented once */
3 public IndentationExample() {
4 /* this line is indented twice */
5 }
6 }
Lines 2, 3, and 5 all have one indentation, so you should prefix them with four spaces.
Line 4 has two indentations, so you should prefix them with eight spaces. However, eight
spaces are also equivalent to a tab, so you could use a tab instead of the eight spaces for line 4.
To avoid confusion, we recommend that you use eight spaces instead of a tab.
Tip Many IDEs and editors give you the option to insert a specified number of spaces whenever you press
the Tab key (and even handle backspacing over the indentation/reformatting entire blocks of code). We rec-
ommend you check whether your IDE/editor provides this functionality and turn it on when available.
Line Lengths/Wrapping
As mentioned earlier, you cannot know what sort of an editor or what screen size your asses-
sor will be using. Limiting line lengths to 80 characters will ensure that your code should be
readable in most cases.
Search WWH ::




Custom Search