The article is to familiar yourself with basic Java coding styles, which improves readability and thereby the understanding and maintainability of your code. For a more complete explanation, please refer to Oracle (Sun)'s Java coding conventions.
Improve readability by making the location of each class element predictable. In addition, include a program description and the author's identity in the header section of the main .java file.
/**
* Program: CS1020 Lab 1, <program name>
*
* <program description>
*
* <comments to grader, if any>
*
* @<matric number>
*/
public class <name>
{
// Static variables declarations
// Instance variables declarations
// Constructors
// Methods (no specific order)
// public static void main(...)
}
Keeping the operations on a variable within a small scope, it is easier to control the effects and side effects of the variable. Furthermore, when reading the program, referring to the type declaration of the variable is also made easier.
For example,
// AVOID double x,y; ... ... <many lines of statements unrelated to x,y> ... ... x = 0; y = 1;
Variables should be declared at the point where they first become relevant:
// PREFERRED ... ... <many lines of statements unrelated to x,y> ... ... double x = 0; double y = 1;
As another example, loop variables should be declared and initialized immediately before the loop:
// PREFERRED
boolean done = false;
while (!done) {
...
}
Where there are deeply nested blocks, variables which only apply to the inner block(s) should be declared within, for example:
// PREFERRED
for (i=...) {
for (j=...) {
for (k=...) {
double tmp = computeResult(i,j,k);
}
}
}
// tmp not needed here...
Counter variables of for statements which are not used outside the loop should be declared within the for statement.
// PREFERRED
for (int i=0; i<100; i++) {
...
}
For example,
// PREFERRED double x,y,z; // Coordinates of a particle
As opposed to:
// AVOID double x; double y; double z;
Avoid direct use of magic numbers for those literal constants of special meaning. Constant literals which have special meanings should be named and its named identifier should be used in its place. The exception to this rule is the use of numeric constants in well-defined mathematical formulas (for instance, 4/3*Math.PI*r*r).
Example:
// AVOID
for (int i=0; i<100; i++) {
...
}
// PREFERRED
public static final int MAX_LEN = 100; // static class variable
...
for (int i=0; i<MAX_LEN; i++) {
...
}
Code should be properly and neatly indented to emphasize the nested logical structure of the program. Following Sun's convention, an indentation of 4 spaces is recommended (8 is too wide and 2 is too cramp).
Every method block and statement block that follows a for, while, if/else, switch, do/while statement must be indented from its enclosing block.
Comments within a block should follow the indentation level of its enclosing block.
For example,
for (int i=0;i<3;i++) { // Trailing open-braces is OK
// Comments should be indented too
while (true) // Leading open-braces OK as well
{
// More indented comments
System.out.println("Hello");
}
}
An "if" block with a complex condition or an expression that's hard to understand should have explanatory comments. For example,
// Check and reject out-of-bounds indices
if (k < 0 || k >= MAX_LEN) {
return -1;
}
Instance and class variables whose purpose are not immediately clear should be trailed with a brief comment at its point of declaration:
class DelayedPriorityQueue {
int nsize; // length of queue
int npending; // number of nodes awaiting insertion
...
}
Collection variables should have a trailing comment stating the common type of the elements of the collection:
ArrayList pointList; // Variable array of Point objects Set shapeSet; // Unorder set of Shape objects
A comment such as:
i++; /* add one to i */
serves no purpose, adds clutter to a program and does more harm than good.
Line, LabProgram1, EmployeeRecord, Point, ColoredPoint, TaxCheatException
Naming convention by Sun and used by all Java core packages. Uses typographic conventions to distinguish identifier types.
debitAccount(), binarySearch(), isValid(), getName(), setName(), computeScore()
Naming convention by Sun and used by all Java core packages.
line, inputLine, i, j, currNode, prevNode, nextNode, lastName
Naming convention by Sun and used by all Java core packages.
MAX_ITERATIONS, MAX_LEN, GOLDEN_RATIO, COLOR_DEFAULT, PI
Naming convention by Sun and used by all Java core packages.
The scope of class and instance variables spans all methods in the class. It is best to use descriptive names for them so that their meanings are immediately clear when they appear within a method. For example, "Node currNode;" is an appropriate instance variable but not "Node n;". The latter, however, is perfectly appropriate if it is a transient variable (see 2.6).
For a similar reason, class names should also have descriptive names (nouns).
In contrast to the above (2.5), transient variables such as loop counters, temporary references, iterators etc, should have short and easy to recall names as their usage is frequent and their purpose is usually clear.
For example,
// AVOID
for (int theElementIndex=0; theElementIndex<numberOfElements; theElementIndex++) {
array[theElementIndex] = theElementIndex;
}
is much less readable than:
// PREFERRED
for (int i=0; i < numberOfElements; i++) {
array[i] = i;
}
For example,
employee.getName();
employee.setName("Tom");
For example,
isVisible, isFinished, isFound, isOpen, hasLicense shouldAbort(), canEvaluate(), isInsideBounds(), isValid()
Negated variables often results in hard-to-read double-negatives in an expression like !isNotError.
// AVOID isNotError, isNotFound, isNotValid, cannotOpenFile
// PREFERRED isError, isFound, isValid, canOpenFile
This convention is the standard in Sun's Java core packages.
class OutOfBoundsException {
...
}
As programs get more complex, program design becomes increasingly important. Decomposing a complex program into smaller, more manageable units and the design of the interfaces between the units are fundamental to good programming. Generally, the constituents of a program unit should be highly cohesive (3.1), and the coupling between program units should be clean and minimal (3.2). Algorithmic logic should be easy to understand (3.3). The program should also be easy to setup and its usage should be intuitive.
Each method or class should consist of closely related elements. If a class or method consists of a mixed-bag of unrelated elements, it often indicates a need to modularize the code into further cohesive program units.
As a general rule, each function/method should do only one thing. This should be done so that the conceptual unit can be understood easily. Sometimes it will be convenient to do two things in a function because you're working on the same data. Try to resist this temptation. Make two functions if you reasonably can.
Often the naming of the method indicates its cohesiveness. Does the method only do what its name says, or does it do more than that? If you find that a complete name for one of your method is like openInputAndReadVectorAndComputeSum(..), it is time to break the multitasked method into sub-constituents.
Segments of code which are repeated should be abstracted into a method. This not only results in shorter programs but also makes it easier to maintain and read. The abstracted method then forms a cohesive unit by itself.
If changing one class in your program requires changing another class, then a coupling exists between the two classes. One indicator of program quality is the amount of coupling between your program units.
Coupling indicates a dependency between source codes. Reducing this dependency improves the quality and maintainability of your program. If your application consists of more than one class, some coupling must exists; otherwise the objects can't communicate with one another. The rule of thumb in building Java programs with multiple classes is for each class to provide a minimal and well-defined set of public methods while limiting the accessibility of everything else (using the private modifier).
Simplicity is a virtue. Wherever possible, your program should be simple, compact, and easy to read. For example, long chains of nested if/else statements can often be replaced with a more compact form for evaluating the logic. If you find that the logic in your code is getting very unwieldy, rethink and rewrite it.
For instance, if all the inputs to a problem are integers, the program should refrain from introducing any variables of floating-point type. Similarly, it should refrain from invoking any methods which involve floating-point types.
Other examples including using while instead of for when the number of iterations is easily determined before the loop.