Coding Standards for Java Programs
Version 1.10.4
This document gives some rules of thumb for writing programs
in good style. No set of rules can cover all possible situations;
use common sense always. The purpose of good style is to make
programs easily readable and intelligible. This has at least
two important benefits: it helps us avoid errors when writing
the program initially, and we or others
who subsequently need to revise the program won't be confused.
How to Develop Programs
- Begin by making sure you understand the problem,
then design the algorithm. Do not begin by coding,
i.e., writing Java statements, except for extremely simple problems.
- Test your algorithm with pencil and paper before coding it.
- Develop and test incrementally. That is, write a little bit of code
and test it. Fix the errors.
Then write a little more code and test it.
Fix the errors again. And so on.
The alternative is to develop and test monolithically--writing many
lines of code before testing any of it.
Typically, monolithic development will result in a huge and bewildering
number of error messages from the compiler and/or run-time errors.
Standards are listed under the chapter where they first
become applicable.
Chapter 1: Basics
-
Each source code file should begin with a header comment
which shows the file name, author's name and email address,
course, date,
and purpose of the program.
Example:
/* File: Hello.java
Author: Jane Doe (janedoe@example.edu)
Course: INFO-I211
Date: January 1, 2010
Purpose: This program prints the message "Hello, Java!"
ten times.
*/
Alternatively, the header comment may be written using the
// or
/** ... */ comment notation.
- Indent code to show program structure. For example,
all but the first line of a class definition should be
indented, and all but the first line of a method definition
should be further indented. See Listings 1.1-1.3 in
Java Software Solutions for examples of good
and bad formatting.
Indent with two or four spaces for each level of structure,
and be consistent.
Do not use the TAB character to indent. (But you may use
the TAB key if it inserts spaces instead of tabs.)
Hint: Some text editors and most IDEs can help you indent.
In Emacs:
(a) TAB indents the current line.
(b) C-j starts a new line and indents it.
(c) For Emacs in Java mode, the
Java menu has an "indent line or region" command.
- Write no more than one statement per line.
- No line should exceed 80 characters, which is the standard
width of a terminal or printed page.
Lines longer than 80 characters will either "wrap around"
or be cut off when viewed or printed at the standard width,
making them ugly and/or unintelliglble.
Split complex statements across lines at sensible breaking points,
and indent the continuation lines.
Chapter 2: Data and Expressions
- Code should be clear, simple, and straightforward to the extent
possible.
Avoid obscure and bizarre usages and unnecessary complexity.
- Code that is (nevertheless)
not self-explanatory should be documented
with comments.
- Use meaningful and appropriate variable names.
Variable names like
x are suitable only for
abstract numbers (e.g., a program that computes the square root
of x)
and geometric coordinates. Variable names should accurately
suggest what the variable represents. A variable that represents
a person's age, for example, should be named
age
rather than weight.
- Use spaces to separate the parts of expressions and lists.
For example,
5 * (x + 1)
is better than 5*(x+1).
- Use parentheses if they will help to clarify complex expressions.
Chapter 3: Using Classes and Objects
- Use blank lines to separate distinct sections of code.
But do not overuse blank lines.
For example, don't double space a section of your
program, or double space your entire program,
Use blank lines to separate what needs to be
separated.
-
Use "CamelCase" for class names: begin with a capital letter
and capitalize every subsequent word in the class name.
Do not use underscores.
Examples:
PrettyGoodScanner,
AverageGuy, DecimalFormat.
-
Use "camelCase" for variable names: begin with a
lower-case letter
and capitalize every subsequent word in the variable name.
Do not use underscores.
Examples:
width, conversionRate,
inchesOfRain.
Chapter 4: Writing Classes
- Organize the class structure in this way:
field declarations first, followed by constructors,
then methods.
-
Use "camelCase"
for method names, and continue using it for
variables — both local variables and fields
(instance and class variables), except
for variables declared
final.
Examples: getHeight,
setHeight, inchesToMeters.
-
Use "UPPER_CASE" names for constants,
i.e., variables declared
static.
Use underscore characters to separate words within the name.
Examples: VERSION, TAX_RATE,
SPEED_OF_LIGHT.
-
Variables that are used only by one method should be declared
as local variables, within the method,
rather than instance variables.
-
Avoid using the same name for a local variable and an instance
variable (shadowing).
-
Use encapsulation. Normally, instance variables should be declared
private and should be accessible
only through the methods
provided by the class. Use an accessor method to provide read access,
and/or a mutator method to provide write access. Some instance
variables may not need access from outside the class.
- If a method is getting too complex, divide it into subproblems,
and define a helping method for each of the subproblems.
Generally, several short methods are better than
a single long method.
- Use methods to avoid code repetition.
It is hard to give strict rules about this, but here are some rules of
thumb:
- One complex line repeated two or more times.
- Two or more simple lines repeated two or more times.
- Use methods to improve code clarity.
Sometimes the meaning of a few lines, or even one line, of code
can be made clearer by wrapping it in a method definition and giving
it a name. This may be true even if the lines are unrepeated.
- Declare methods that are part of the class's interface
public;
declare other, helping methods private.
- Use meaningful and appropriate method names, just as you would use
meaningful and appropriate variable names.
- Write a comment above each method (a "header comment") that explains
what its parameters are, what it does, what value it returns,
unless this information is perfectly obvious from reading the
method's name, return type, and parameter list.
The header comment should also explain what conditions must be
true before the method is called (preconditions), and what
conditions the method guarantees to be true when it returns
(postconditions).
- Indent the statements within the body of a method.
Hint: use the TAB key in Emacs to
indent a line,
or use C-M-\ to indent a region.
- Use blank lines to separate methods.
Chapters 5–6: Conditionals and Loops
- Indent statements in the body of control structures
(
if, while, for, do/while,
and switch
statements).
(See the indenting hint under chapter 1.)
- Avoid the
continue and
break
statements, except for break
statements required
in a switch statement.
- Avoid redundant tests in
if statements.
For example,
if (size > 100)
System.out.println("Large");
else if (size > 50)
System.out.println("Medium")
else
System.out.println("Small");
is preferable to
if (size > 100)
System.out.println("Large");
else if (size > 50 && size <= 100)
System.out.println("Medium")
else if (size <= 50)
System.out.println("Small");
- Use boolean variables and expressions outside of the
context of an
if statement to simplify code.
For example,
return (x == y);
is preferable to
if (x == y)
return true;
else
return false;
Chapter 8: Arrays
- Use named constants, instead of just numbers,
to specify array sizes.
Example:
final int NUM_STUDENTS = 35;
Student [] scholar = new Student[NUM_STUDENTS];
- Don't space between the name of an array and its subscript.
For example, write
scholar[i],
not scholar [i].
- Use array initialization lists if the
initial values of elements are known
when an array is created and the number of elements
is small. Examples:
int [] nums = new int[] {1, 3, 7, 12, 19}; // recommended
int [] nums = {1, 3, 7, 12, 19}; // alternate
Chapter 9: Inheritance
- Use
private,
protected, and
public qualifiers to strike a balance
between encapsulation and accessibility.
- Design of class hierarchies:
- Keep common features as high in the hierarchy as possible.
This maximizes software re-use and minimizes the needs of
software maintenance.
- Only use subclasses when there is an "is-a" relationship.
- There is no one best class hierarchy for all purposes;
think carefully about what design works best
for the application.
- Override methods to make exceptions to general rules.
- In particular, routinely override the
equals and
toString methods.
- Use abstract classes or interfaces to specify behaviors that are
required but not (yet) defined.
- Avoid shadowing inherited instance variables.
- Let each class manage its own data, using constructors, accessors,
and mutators.
Chapter 10: Polymorphism
- Use polymorphic references (either by inheritance or by interfaces)
to increase flexibility of methods. This means using a supertype
(superclass or interface) as the declared type of a variable
and using subtype (subclass or implementing class) objects
for the actual values.
- Polymorphic parameters of methods.
- Polymorphic array elements.
References
For further reading. Some of these references
provide dull summaries of common industry practices.
Others are gems of reflective insight.
The recommended reading may or may not agree with the
rules listed above.
If you find yourself inclined to dissent, please discuss
it with me. — Gregory D. Weber
Summary of Recent Revisions
- Version 1.10.4, 2017 Jan 20. Don't over-use blank lines.
Link to archived Oracle/Sun document.
- Version 1.10.3, 2016 Mar 14. Reformat and rephrase some
rules for chapter 9.
- Version 1.10.2, 2016 Mar 5. Specify "small" for array
initialization lists.
- Version 1.10.1, 2015 Feb 6. Add class structure rule.
- Version 1.10, 2014 Feb 19. Add "References" section.
- Version 1.9.1, 2012 Mar 4. Optional "new" in array
initialization.
- Version 1.9, 2012 Jan 8. Revise for online submissions,
additional details about indenting.
- Version 1.8, 2010 Feb 1. Add rules for names of
classes, interfaces, constants, methods, and variables.
- Version 1.7, 2010 Jan 18. Trivial revisions including
course number and date.
- 1.6, 2008 Jan 19. Trivial revisions
- 1.5, 2006 Apr 22.