CS2030/S Java Style Guide
Why Coding Style is Important
One of the goals of CS2030/S is to move you away from the mindset that you are writing code that you will discard after it is done (e.g., in CS1101S missions) and you are writing code that no one else will read except you and your tutor. CS2030/S prepares you to work in a software engineering team in many ways. One of the ways is to enforce a consistent coding style.
If everyone on the team follows the same style, the intent of the programmer can become clear (e.g., is this a class or a field?), the code is more readable and less bug-prone (e.g., see the Apple goto fail
bug for an example of buggy program due to style_). Empirical studies support this:
Quote
"It is not merely a matter of aesthetics that programs should be written in a particular style. Rather there is a psychological basis for writing programs in a conventional manner: programmers have strong expectations that other programmers will follow these discourse rules. If the rules are violated, then the utility afforded by the expectations that programmers have built up over time is effectively nullified. The results from the experiments with novice and advanced student programmers and with professional programmers described in this paper provide clear support for these claims."
Elliot Soloway and Kate Ehrlich. "Empirical studies of programming knowledge." IEEE Transactions on Software Engineering 5 (1984): 595-609.
Many major companies enforce coding styles, and some have published them. For CS2030, we base our (simplified) coding style on Google's Java Coding Style. You should bookmark the link because you need to come back to it again and again.
Spacing and Indentation
-
No tabs. Use only whitespace.
VIM Setting
For
vim
users, the following setting in your~/.vimrc
file:1
set expandtab
causes Tab to be expanded to whitespace.
For CS2030S
This option is already included in the
~/.vimrc
file if you follow the Vim setup guide. In fact, we recommend you follow the Vim setup guide instead and don't manually manage your own version of your~/.vimrc
file.Most other source code editors have similar configurations.
-
Block indentation is exactly two spaces.
1 2 3 4 5 6
if (x == 0) { x++; for (i = 0; i < x; i++) { x += i; } }
VIM Setting
For
vim
users, in~/.vimrc
, add the following:1 2 3 4 5 6
set tabstop=2 set shiftwidth=2 set autoindent set smartindent " For Java: enabling this includes Java-specific indentation settings that handle annotations like @Override filetype plugin indent on
To help you with indentation.
For CS2030S
These options are already included in the
~/.vimrc
file if you follow the Vim setup guide. In fact, we recommend you follow the Vim setup guide instead and don't manually manage your own version of your~/.vimrc
file.Most other source code editors have similar configurations.
-
Each line is limited to 100 characters in length.
line into multiple lines to enhance readability, this is called line wrapping. When you do so, each continuation line is indented at least 4 spaces from the original line.Good Example
1 2 3 4 5 6
void foo(double a, double b, double c, double d double e, double f) { if ((a > b) && (b > c) && (c > d) && (d > e) && (e > f)) { } }
Bad Example
1 2 3 4 5 6
void foo(double a, double b, double c, double d double e, double f) { if ((a > b) && (b > c) && (c > d) && (d > e) && (e > f)) { } }
1 2 3 4 5 6
void foo(double a, double b, double c, double d double e, double f) { if ((a > b) && (b > c) && (c > d) && (d > e) && (e > f)) { } }
80 vs 100
While we prefer lines to be limited to 80, we are OK if the length is up to 100. Any longer, however, will be frowned upon.
-
Indent comments at the same level as the surrounding code. For multiple comments, align
*
with the previous line.Good Example
1 2 3
/* * Good style */
1 2 3
/** * Good style for JavaDoc */
Bad Example
1 2 3
/* * Not a good style */
1 2 3
/** * Not a good style for JavaDoc */
1 2 3
/** * Also not a good style for JavaDoc */
-
White space should separate Java keywords from parenthesis and braces, and be added on both sides of binary operators (
+
,-
,/
, etc) as well as:
in enhanced for-loop. Space should also appear before and after//
commentsGood Example
1 2 3 4 5 6
if (x == 0) { x++; // to make sure x is at least one. for (i = 0; i < x; i++) { x += i; } }
Bad Example
Java if(x==0){ x++;//to make sure x is at least one. for(i=0;i<x;i++){ x+=i; } }
Classes
-
Each file contains exactly one top-level (i.e., non-nested) class.
-
Each top-level class resides in a source file of its own.
-
When a class has overladed methods (e.g., multiple constructors or methods of the same name), they appear sequentially with no other code in between.
Braces
-
Braces are always used (even if the body is empty or contains a single statement)
-
Use "Egyptian brackets":
- Opening brace has no line break before; but has a line break after
- Closing brace has a line break before; and has a line break after (except when there is
else
or comma following a closing brace).
Good Example
1 2 3
if (x == 0) { x++; }
Bad Example
1
if (x == 0) { x++; }
1 2 3 4
if (x == 0) // Allman style (do not use) { x++; }
1 2 3
if (x == 0) // Pico style (do not use) { x++; }
Lines
-
Exactly one blank line after
import
statements. -
Each statement is followed by a line break, no matter how short the statement is.
Good Example
1 2
x++; i++;
Bad Example
1
x++; i++;
-
There should be a blank line between constructors, methods, nested classes and static initializers. Blank lines can be used between fields to create logical groupings.
Identifies
-
One variable per declaration.
Good Example
1 2
int x; int y;
Bad Example
1
int x, y;
-
No C-style array declaration
Good Example
1
String[] args;
Bad Example
1
String args[];
-
Class modifiers appear in the following order:
1
public protected private abstract default static final transient volatile synchronized native strictfp
Good Example
1
public static void main(String[] args)
Bad Example
1
static public void main(String[] args)
-
Class names are written in UpperCamelCase; method names and field names in lowerCamelCase; and constant names in ALL_CAPS_SNAKE_CASE. Type parameters in single capital letters.
-
Static fields and methods must be accessed with their corresponding class names.
Statements and Annotations
-
Switch statements always include a
default
case. -
One annotation per line.
-
Always use
@Override
.1 2 3 4
@Override public boolean equals(Object o) { : }
-
Caught exceptions should not be ignored.
-
Avoid
import
using wildcards*
. Always import the specific class you need. !!! success "Good Example"1 2 3 4
```Java import java.util.ArrayList; import java.util.List; ```
Bad Example
1
import java.util.*;
-
Import statement should be in alphabetical order. !!! success "Good Example"
1 2 3 4
```Java import java.util.ArrayList; import java.util.List; ```
Bad Example
1 2
import java.util.List; import java.util.ArrayList;
Using checkstyle
To automatically check for style violations, we use a tool called checkstyle
.
Example of how to run:
1 |
|
The exercises and exams may have different stylecheck configurations. See the corresponding instructions in the exercises/exam papers.
Hint: put the command into a bash
script so that you do not need to type such a long string all the time.