Style Guide
Even if they run correctly, your programs are expected to be easily readible by humans. Readers
may choose to deduct points from program submissions that are messy and difficult to read. If
you want to avoid losing style points, your programs must adhere to the following bare minimum
style guidelines (adapted from Google's and Professor Shewchuk's Java style guides):
- Indentation: Each time a new block or block-like construct is opened, the indent increases by four spaces. When the block ends, the indent returns to the previous indent level. The indent level applies to both code and comments throughout the block.
-
Braces are used with
if
,else
,for
,do
andwhile
statements, even when the body is empty or contains only a single statement. Braces should follow the Kernighan and Ritchie style for nonempty blocks and block-like constructs: - No line break before the opening brace.
- Line break after the opening brace.
- Line break before the closing brace.
- Line break after the closing brace if that brace terminates a statement or the body of a method, constructor or named class. For example, there is no line break after the brace if it is followed by
else
or a comma. - Braces and indentation example:
- Naming: methods, non-constant and non-final fields, parameters, and local variables have names that are lowerCamelCase. Class names are UpperCamelCase
-
Whitespace: Aside from the newline character \n, the ASCII horizontal space character (0x20) is the only whitespace character that appears anywhere in a source file. This implies that:
- All other whitespace characters in string and character literals are escaped.
- Tab characters are not used for indentation.
- One statement per line
- Methods are no longer than 100 lines of code.
- Column limit of 100, although 80 is preferred (i.e. no more than 100 characters per line).
- No extraneous debugging code (e.g. debugging print statements), commented out statements, or unused code.
- No public fields or methods that should not be public
- No meaningless variable / class names (exception: loop indices)
- No large blocks of duplicate code (create separate methods for code that is used frequently)
return new MyClass() {
@Override
public void method() {
if (condition()) {
try {
something();
} catch (ProblemException e) {
recover();
}
}
}
};
More in-depth style guides
Eclipse Autoformatting
You can set up Eclipse to autoformat your code. Go to Window > Preferences > Java > Editor > Save Actions to have Eclipse format your code whenever you save a file. Then click Formatter to choose your formatting preferences. You can use Eclipse's default format settings, customize your own, or import one (e.g. mine)