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 teams in many ways. One of the ways is to enforce a consistent coding style.
If everyone on the team follows the same style, the intend 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.
CS2030/S Coding Style
-
No tabs. Use only whitespace.
VIM Setting
For
vim
users, you can add the following line in your~/.vimrc
file:1
set expandtab
So that when you press Tab it is 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 configuration.
-
Exactly one blank line after import statements and 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 are always used (even if the body is empty or contains a single statement)
-
Use "Egyptian brackets":
- Opening brace have no line break before; but has 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++; }
-
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 handles 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 configuration.
-
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++;
-
Each line is limited to 80 characters in length. You can break a long 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
System.out.println("Daenerys of the House Targaryen," + "the First of Her Name, The Unburnt, Queen of the Andals," + "the Rhoynar and the First Men, Queen of Meereen," + "Khaleesi of the Great Grass Sea, Protector of the Realm," + "Lady Regnant of the Seven Kingdoms, Breaker of Chains and" + "Mother of Dragon");
Note the 4 spaces indentation at line 2 to line 6.
Bad Example
1
System.out.println("Daenerys of the House Targaryen, the First of Her Name, The Unburnt, Queen of the Andals, the Rhoynar and the First Men, Queen of Meereen, Khaleesi of the Great Grass Sea, Protector of the Realm, Lady Regnant of the Seven Kingdoms, Breaker of Chains and Mother of Dragon");
1 2 3 4 5
System.out.println("Daenerys of the House Targaryen, the First of" + " Her Name, The Unburnt, Queen of the Andals, the Rhoynar and the" + " First Men, Queen of Meereen, Khaleesi of the Great Grass Sea, P" + "rotector of the Realm, Lady Regnant of the Seven Kingdoms, Break" + "er of Chains and Mother of Dragon");
This bad example omitted the 4 spaces indentations.
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.
-
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.
-
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 appears 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
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; } }
-
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[];
-
Switch statement always include a
default
case. -
One annotation per line.
-
Always use
@Override
.1 2 3 4
@Override public boolean equals(Object o) { : }
-
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 */
-
Class modifier appears 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 writte in UpperCamelCase, method names and field names in lowerCamelCase, constant names in ALL_CAPS_SNAKE_CASE. Type parameters in single capital letter.
-
Caught exceptions should not be ignored.
-
Static fields and methods must be accessed with class name.
Using checkstyle
To automatically check for style violation, we use a tool call checkstyle
.
To run,
1 |
|
Hint: put the command into a bash
script so that you do not need to type such a long string all the time.