All source code that you produce for this course must conform to the following style guide, adapted from the textbook's Appendix A.
Introduction
This coding style guide is a simplified version of one that has been used with good success both in industrial practice and for college courses.
A style guide is a set of mandatory requirements for layout and formatting. Uniform style makes it easier for you to read code from your instructor and classmates. You will really appreciate that if you do a team project. It is also easier for your instructor and your grader to grasp the essence of your programs quickly.
A style guide makes you a more productive programmer because it reduces gratuitous choice. If you don't have to make choices about trivial matters, you can spend your energy on the solution of real problems.
In these guidelines, several constructs are plainly outlawed. That doesn't mean that programmers using them are evil or incompetent. It does mean that the constructs are not essential and can be expressed just as well or even better with other language constructs.
If you already have programming experience, in Java or another language, you may be initially uncomfortable at giving up some fond habits. However, it is a sign of professionalism to set aside personal preferences in minor matters and to compromise for the benefit of your group.
These guidelines are necessarily somewhat dull. They also mention features that you may not yet have seen in class. Here are the most important highlights:
- Indentation levels should be in increments of three or four spaces.
- Variable and method names are lowercase, with occasional upperCase characters in the middle.
- Class names start with an Uppercase letter
- Constant names are UPPERCASE, with an occasional UNDER_SCORE.
- There are spaces after keywords and surrounding binary operators.
- Braces must line up horizontally or vertically.
- No magic numbers may be used.
- Every method, except for
main
and overridden library methods, must have a comment. - At most 30 lines of code may be used per method.
- All non-
final
instance variables should be private.
Source Files
Each Java program is a collection of one or more source files. The executable program is obtained by compiling these files. Organize the material in each file as follows:
package
statement, if appropriateimport
statements- A comment explaining the purpose of this file
- A
public
class - Other classes, if appropriate
The comment explaining the purpose of this file should be in the
format recognized by the javadoc
utility. Start with
a /**
,
and use the @author
and @version
tags:
/** |
Classes
Each class should be preceded by a class comment explaining the purpose of the class.
In general, you should first list all private features, then all public features.
Within the public and private sections of the class, use the following order:
- Static/Final Fields (public/private)
- Instance Fields (private)
- Constructors (public)
- Instance Methods (public/private)
- Static Methods (public/private)
- Inner classes (public/private)
Leave a blank line after every method.
All non-final
variables should be private. (However,
instance variables of a private
inner class may be
public.) Methods and final variables can be either public or private,
as appropriate.
All features must be tagged public
or private
.
Do not use the default visibility (that is, package visibility) or
the protected
attribute.
Avoid static variables (except final
ones) whenever
possible. In the rare instance that you need static variables, you are
permitted one static variable per class.
Methods
Every method (except for main
) starts with a comment
in javadoc
format.
/** |
Methods must have at most 30 lines of code. The method signature, comments, blank lines, and lines containing only braces are not included in this count. This rule forces you to break up complex computations into separate methods.
Variables and Constants
Do not define all variables at the beginning of a block:
{ |
Define each variable just before it is used for the first time:
{ |
Do not define two variables on the same line:
int dimes = 0, nickels = 0; // Don't |
Instead, use two separate definitions:
int dimes = 0; // OK |
In Java, constants must be defined with the keyword final
.
If the constant is used by multiple methods, declare it as static
final
. It is a good idea to define static final variables as private
if no other class has an interest in them.
Do not use magic numbers! A magic number is a numeric constant embedded in code, without a constant definition. Any number except -1, 0, 1, and 2 is considered magic:
if (p.getX() < 300) // Don't |
Use final
variables instead:
final double WINDOW_WIDTH = 300; |
Even the most reasonable cosmic constant is going to change one day. You think there are 365 days per year? Your customers on Mars are going to be pretty unhappy about your silly prejudice. Make a constant
public static final int DAYS_PER_YEAR = 365; |
so that you can easily produce a Martian version without trying to find all the 365s, 364s, 366s, 367s, and so on, in your code.
When declaring array variables, group the [] with the type, not the variable.
int[] values; // OK |
When using collections, use type parameters and not raw types.
ArrayList<String> names = new ArrayList<String>(); // OK |
Control Flow
The if
Statement
Avoid the "if
... if
... else
"
trap. The code
if ( ... ) |
will not do what the indentation level suggests, and it can take
hours to find such a bug. Always use an extra pair of {
... }
when dealing with "if
... if
... else
":
if ( ... ) |
The for
Statement
Use for
loops only when a variable runs from somewhere
to somewhere with some constant increment/decrement:
for (int i = 0; i < a.length; i++) |
Or, even better, use the "for each" loop:
for (int e : a) |
Do not use the for
loop for weird constructs such as
for (a = a / 2; count < ITERATIONS; System.out.println(xnew)) |
Make such a loop into a while
loop. That way, the
sequence of instructions is much clearer.
a = a / 2; |
Nonlinear Control Flow
Avoid the switch
statement, because it is easy to fall
through accidentally to an unwanted case. Use if
/else
instead.
Try to avoid the break
or continue
statements in loops. Use another boolean
variable to
control the execution flow.
Exceptions
Do not tag a method with an overly general exception specification:
Widget readWidget(Reader in) throws Exception // Bad |
Instead, specifically declare any checked exceptions that your method may throw:
Widget readWidget(Reader in) |
Do not "squelch" exceptions:
try |
Beginners often make this mistake "to keep the compiler happy". If
the current method is not appropriate for handling the exception,
simply use a throws
specification and let one of its
callers handle it.
Lexical Issues
Naming Convention
The following rules specify when to use upper- and lowercase letters in identifier names.
- All variable and method names and all data fields of classes are
in lowercase (maybe with an occasional upperCase in the middle); for
example,
firstPlayer
. - All constants are in uppercase (maybe with an occasional
UNDER_SCORE); for example,
CLOCK_RADIUS
. - All class and interface names start with uppercase and are
followed by lowercase letters (maybe with an occasional UpperCase
letter); for example,
BankTeller
. - Generic type variables are in uppercase, usually a single letter.
Names must be reasonably long and descriptive. Use firstPlayer
instead of fp
. No drppng of vwls. Local variables that are
fairly routine can be short (ch
, i
) as long
as they are really just boring holders for an input character, a loop
counter, and so on. Also, do not use ctr
, c
,
cntr
, cnt
, c2
for variables in
your method. Surely these variables all have specific purposes and can
be named to remind the reader of them (for example, current
,
next
, previous
, result
, . . .
). However, it is customary to use single-letter names, such
as T
or E
for generic types.
Indentation and White Space
Use indentation stops every three or four columns. Use spaces instead of actual tab characters. (An IDE like Eclipse probably already has this handled for you. Otherwise, you may need to change the tab stop settings in your editor!)
Use blank lines freely to separate parts of a method that are logically distinct.
Every line must fit on 80 columns. If you must break a statement, add an indentation level for the continuation:
a[n] = .................................................. |
Start the indented line with an operator (if possible).
If the condition in an if
or while
statement must be broken, be sure to brace the body in, even if it
consists of only one statement:
if ( ......................................................... |
If it weren't for the braces, it would be hard to separate the continuation of the condition visually from the statement to be executed.
Braces
Opening and closing braces must line up, either horizontally or vertically:
while (i < n) { System.out.println(a[i]); i++; } |
Some programmers don't line up vertical braces but place the {
behind the key word:
while (i < n) { // ALTERNATE |
You may use this style, but note that doing so makes it hard to check that the braces match. Whichever style you use, do so consistently.