Good Java Practices
Good Java Practices
Content
Introduction..........
Objectives...
Nomenclature conventions..........
General naming conventions.............
Specific naming conventions...........
Files..............
General conventions...........
Sentences............
Sentences package eimport.........
Classes and interfaces...
Methods...............
Types.................
Variables.............
Repetitions..........
Conditionals.........
Miscellaneous............
Organization and comments.........
Organization..........
Blank spaces.....
Comments............
Bibliography...
Introduction
Objectives
The purpose of this document is to establish the standards.
of programming and nomenclature of programming objects in
Java to be used in class sessions and projects
software development.
Conventions of
nomenclature
General naming conventions
Package names should be entirely in lowercase.
This is based on the convention specified by Sun for the nomenclature.
of packages.
mypackage, com.company.application.ui
The initial domain name of the package must be fully in
lowercase.
2. The names that represent types must be nouns and must
Write in uppercase and lowercase starting with an uppercase letter.
Line, AudioSystem
This is a common practice in the Java development community.
even the naming convention for types that Sun uses in the
predefined packages of Java.
3. Variable names must use uppercase and lowercase letters
starting with lowercase.
line
It is a common practice in the Java development community and also the
naming convention for variable names used by Sun
for the predefined packages of Java. This makes the variables be
easy to distinguish from the types and resolves from
effectively the possible name collisions as in the
line declaration;
4. The names that represent constants (final variables) must
BEING TOTALLY IN UPPERCASE USING UNDERSCORES (_)
to separate the words.
MAX_ITERATIONS
It is a common practice in the Java development community and also
the naming convention of names used by Sun for the
predefined packages of Java. In general, the use of should be minimized
said constants. In many cases, it is a better option to implement the
value as a method.
int getMaxIterations() // NOT: MAX_ITERATIONS = 25
{
return 25;
}
This way is easier to read and ensures a uniform interface towards the
values of the class.
5. The names that represent methods must be verbs and
write in uppercase and lowercase starting with lowercase.
getName(), computeTotalWidth()
It is a common practice in the Java development community and also the
naming convention used by Sun for
predefined packages of Java. It is identical to the case of the names of
variables, but methods in Java are already distinguished from variables by their
particular form.
6. Abbreviations and acronyms should not be in uppercase.
when used as a name.
exportHtmlSource(); // NOT: exportHTMLSource();
openDvdPlayer(); // NOT: openDVDPlayer();
Using all uppercase for the base name would conflict with the
previous conventions. A variable of this type should be named dVD,
HTML, etc., which is obviously not readable. Another problem is illustrated in the
previous example. When the name connects to another, it is seriously reduced
the readability. The word following the acronym does not remain as it should.
7. Class private variables. Class private variables should
have an underscore (_) as a prefix.
class Person
{
private String _name;
...
}
Besides its name and type, the scope of a variable is its characteristic
more important. Indicating the scope of the class using an underscore makes it easy
distinguish class variables from disposable variables. It is important.
given that class variables are considered to have a more significant meaning
higher than method variables, and should be treated with special
careful by the programmer.
A side effect of the underscore naming convention is that it resolves
the problem of finding variable names for the set methods.
void setName (String name)
{
name
}
8. Generic variables should have the same name as their type.
void setTopic (Topic topic) // NOT: void setTopic (Topic
value
1. NOT: void setTopic (Topic aTopic)
2. NOTE: void setTopic (Topic x)
void connect (Database database)
1. NOT: void connect (Database db)
2. NOTE: void connect(Database oracleDB)
This reduces complexity by reducing the number of terms and names.
used. It also makes it easy to deduce the type just by counting on the name of
the variable. If for some reason this convention does not seem to fit, this is a
strong indicator that the type name is poorly chosen. The variables do not
Generics have a role. These variables can often be named.
combining the role and the type.
Point startingPoint, centerPoint;
Name loginName;
All names should be written in English.
fileName
English is the preferred language for international development.
10. Variable names with a broad scope should have
long names, variables with small scope should have
small names. The disposable variables used for the
temporary storage or indices should be short. A
a programmer reading these variables should be able to assume their value
is not used beyond a few lines of code. The variables
Common disposable variables for integers are i, j, k, m, n and for the
characters c and d.
10. The name of the object is implicit and should be avoided in a
method name. line.getLength(); // NOT:
line.getLineLength();
The use of the object's name may seem natural in the declaration of
the class, but it becomes superfluous when used, as shown in the
example.
Specific naming conventions
1. The terms get/set should be used when an attribute is accessed.
directly.
employee.getName();
matrix.getElement
(2, 4);
employee.setName
(name);
matrix.setElement
(2, 4, value);
This is the naming convention for accessor methods.
used by Sun in the predefined packages of Java. When you write
Java Beans this convention is actually mandatory for the methods.
2. The prefix 'is' should be used for boolean variables and methods.
isSet
This is the naming convention for variables and methods
booleans used by Sun in Java's predefined packages.
When writing Java Beans, this convention is actually mandatory.
for the methods.
The use of the prefix solves the problem of choosing names poorly.
booleans like status or flag. isStatus or isFlag just don't fit and
the programmer is forced to choose another name with more meaning.
There are a few alternatives that fit better than the prefix is in
some situations. These are the prefixes has, can, and should.
boolean
hasLicense();
boolean
canEvaluate();
boolean
shouldAbort
false
3. The term compute can be used in methods where something is
calculate.
valueSet.computeAverage();
matrix.computeInverse();
It gives the reader the immediate impression that it is a possible operation of
time consumption, and that if it is used repeatedly, he should
consider storing the result. A consistent use of the term improves the
legibility.
4. The term find can be used in methods where it is being
looking for something.
vertex.findNearestVertex();
matrix.findMinElement();
It gives the reader the immediate impression that this is a simple method of
search with a minimum of calculation involved. The consistent use of the term
increase readability.
5. The term initialize can be used where a concept is established or
object.
printer.initializeFontSet();
The American English 'initialize' should be used instead of the 'initialise' from
British English. The abbreviation init should be avoided.
6. The JFC (Java Swing) variables should have the type suffix
element.
widthScale, nameTextField, leftScrollbar, mainPanel
fileToggle
printerDialog
This improves readability as the name gives the user the impression
immediate type of variable and consequently the available resources of
object.
7. The plural form should be used in names that represent a
collection of objects.
Collection points;
// of Point int[]
values;
This improves readability, as the name gives the user immediate insight.
of the type of variable and the operations that can be performed on the object.
8. The prefix n should be used for variables that represent a
number of objects.
nPoints, nLines
The notation is taken from mathematics, where it is a convention for
indicate a number of objects. Note that Sun uses the prefix num in the
predefined Java packages for such variables. This probably should
It signifies an abbreviation of number of, but it seems more like number.
see the strange and deceptive variable. If 'number of' is the preferred statement,
then numberOf should be used instead of just n. The
Number prefix should not be used.
The suffix should not be used for variables that represent
entity numbers.
tableNo
The notation is taken in mathematics where there is a convention.
established to indicate an entity number. An elegant alternative is
place i as a prefix in those variables: iTable, iEmployee. This makes them
effective way named iterators.
10. Iterator variables should be called i, j, k, etc.
while (Iterator i = points.iterator(); i.hasNext(); ) {
:
}
for (int i = 0; i < nTables; i++) {
:
}
This notation is taken from mathematics where there is a convention.
established to indicate the iterators. The variables with names j, k, etc.
they should only be used for nested iterations.
11. Complementary names must be used for the entities
complementary.
get
insert/delete, increment/decrement, old/new
begin
next
This reduces complexity based on symmetry.
12. Abbreviations in names should be avoided.
computeAverage(); // NOT:
compAvg(); ActionEvent event; //
NOT: ActionEvent e;
There are two types of words to consider. First, there are the types of words.
common listed in a language dictionary. These should never be
abbreviated. Never write:
cmd instead of command
comp instead of compute
cp instead of copy
and instead of exception
init instead of initialize
instead of point
etc.
On the other hand, there are specific phrases that are more widely known for their
acronym or abbreviation. These phrases should remain abbreviated.
Hypertext Markup Language instead
of
html
Central Processing Unit
time
of the cpu
Price Earnings Ratio
time
from
etc.
13. Negated boolean variables should be avoided.
boolean isError; // NOT:
isNotError boolean isFound;
NOT: isNotFound
The problem arises when the logical operator is not used and a double emerges.
negation. The meaning of !isNotError is not very clear initially.
14. The constants (final variables) associated must be prefixed with a
common type name.
final int COLOR_RED =
1;
final int COLOR_GREEN = 2;
final int COLOR_BLUE =
3;
This indicates that the constants are related and the concept that the constants
They represent. An alternative to this proposal is to place the constants within
from an interface and thus prefix their names with the name of the interface.
interface Color
{ =
final int RED 1;
final int GREEN = 2;
final int BLUE =
3;
}
15. Exception classes should have the suffix Exception.
class AccessException
{
:
}
The Exception classes are not really part of the main design of the
program and name them like this makes them independent with respect to others
classes. This standard is followed by Sun in the basic Java library.
16. The default implementations of interfaces must have
as a prefix
Default.
class
DefaultTableCellRenderer
implements
TableCellRenderer
{
:
}
It is not uncommon to create a simplistic implementation class of a
interface, which provides default behavior for the methods of
the interface. The convention of prefixing these classes with Default has been
adopted by Sun for the Java libraries.
17. Functions (methods that return an object) should be named
after what they return and the procedures (void methods) afterwards
of what they do.
This increases readability. It clarifies what the unit should do.
and all the things that it is not supposed to do. This again facilitates the
keep the code clean of side effects.
Files
General conventions
Java source files should have the .java extension.
Point.java
This is reinforced by the Java tools.
2. Classes should be declared in individual files with a
file name that matches the class name. The
private secondary classes can be declared as inner classes and
to reside in the file of the class to which they belong. This is supported by
the tools of Java.
2. The content of the file must be kept within 80 columns. 80
columns is the common dimension for editors, emulators of
terminal, printers, and debuggers; the files that are shared between
Several developers should align with these restrictions. When the
the file goes through several programmers, readability improves when
line breaks are avoided unintentionally.
2. Special characters such as TAB and line breaks should be avoided.
page. These characteristics tend to cause problems in editors,
printers, terminal emulators, or debuggers when used in
multi-platform and/or multi-programmer environments.
2. It must be evidenced when a line is incomplete due to being
game.
totalSum
=a+b+c+d+
e;
function
(param1,
param2,
param3);
setText
line
split
+
into
two
parts.
for (tableNo = 0;
tableNo <
maxTable
+= tableStep)
Line partitioning occurs when a statement exceeds the limit of
80 columns specified above. It is difficult to give strict rules on how
The lines should be split. But the examples can provide a clue.
general.
Cut after a comma.
2. Cut after an operator.
3. Align the new line with the start of the expression in the previous line.
Sentences
Package and import statements
1. The package statement must be the first statement of the file.
All files belong to a specific package. The location of
The package statement is supported by the Java language. Allowing that
all files belong to a real package (instead of Java for
defect) reinforces object-oriented programming techniques of
Java.
2. The import statement must follow the package statement. The
import statements must be ordered by placing the fundamental package first
first, by grouping the associated packages, and placing a line in
white space between groups.
import
java.io.*;
import
java.net.*;
import java.rmi*
import java.rmi.server.*;
import
javax.swing.*;
import
javax.swing.event.*;
import org.linux.apache.server.*;
The location of the import statement is supported by the Java language.
sorting makes it easy to list when there are many imports, and makes it easy to
determine the dependencies of the present packages. The grouping
reduce the complexity by condensing the related information into one
common unit.
Classes and interfaces
1. Class declarations should be organized. This should
to be done in the following way:
1. Documentation of the Class/Interface.
2. Class or interface statement.
3. Class variables (static) in the order public, protected, package (without
access modifier), private.
4. Instance variables in the order public, protected, package (without
access modifier), private.
5. Builders.
6. Methods (no specific order).
Reduce the complexity by making the location of each predictable.
class element.
Methods
1. Method modifiers should be given in the following order:
static abstract synchronized final native. The
modifier <access> (if it exists) must be the first modifier.
<access> is public, protected, or private while <unusual>
includes volatile and transient. The most important thing here is to maintain the
access modifier as the first modifier. Among the possible ones
modifiers, this is by far the most important and should be at the beginning in
the method declaration. For other modifiers, the order is less
important, but it is advisable to have a fixed convention.
Types
Type conversions must always be explicit. Never
fall into implicit conversions.
floatValue = (float) intValue; // NOT: floatValue =
intValue;
The programmer must indicate that they are aware of the different types
involved and that the mixture is intentional.
Variables
1. Variables should be initialized where they are declared and should
declare in the smallest possible scope. This ensures that the
Variables are valid at all times. Sometimes it is impossible to initialize.
a variable with a valid value where it is declared. In those cases
it should be left uninitialized instead of giving it a meaningless value.
2. Variables should never have dual meanings. This improves the
legibility ensuring that all concepts are represented by
unique way. It reduces the chances of errors resulting from the
duality.
3. Class variables should never be declared public. The concept
the concealment of information and encapsulation of Java is violated by
the public variables. Use the private variables and access those instead
to the functions. An exception to this rule is when the class is
basically a data structure, without behavior (equivalent to the
C++ struct). In this case, it is appropriate to make the variables of
instance of the "class" public.
4. Related variables of the same type can be declared in
a common sentence. Unrelated variables should not
declare in the same statement.
float x, y, z;
float revenueJanuary, revenueFebruary, revenueMarch;
The common requirement of having statements on separate lines does not
it is useful in the examples. This improves readability by grouping variables.
Note that however when possible, the variables should
initialize where they are declared (see rule 4.5.1), in case this
situation does not occur.
5. Arrays should be declared with brackets next to the type.
double[] vertex; // NOT: double vertex[];
int[] count; // NOT: int count[];
public static void main (String[] arguments)
public double[] computeVertex()
This has a double reason. First, the characteristic of being an arrangement is of the
class, not of the variable. Second, when an array is returned in a
method, it is not possible to have the brackets anywhere other than with the
type (as shown in the example).
6. The variables should be kept alive for the shortest time.
possible. Maintain the operations on a variable within a
small scope, it is easier to control effects and side effects of the
variable.
Repetitions
Only the flow control statements should be included in the
construction of the for()
sum = 0;
for (i = 0; i < 100; i++) sum += value[i];
1. NOT: for (i=0, sum = 0; i < 100; i++)
2. sum += value[i];
This increases readability and maintainability. It makes a clear distinction.
what controls and what is contained in repetition.
2. The loop variables should be initialized immediately
before the repetition.
boolean isDone = false; // NOT: isDone = false;
while (!isDone) { // :
// while (!isDone) {
} // :
}
2. The use of do...while loops should be avoided. There are two reasons for this.
this. First, the construction is superfluous. Any sentence
what can be written as a do...while can also be written
like a while loop or a for loop. The complexity is reduced
if the least amount of constructions is used. The other reason is
Legibility. A loop with the conditional part at the end is harder to read.
that one with the conditional above.
2. The use of break and continue should be avoided in the
repetitions. These statements should only be used if they demonstrate
to provide more readability than their structured counterparts.
Conditionals
1. Conditional expressions should be avoided. Instead, introduce
temporary boolean variables.
if ((elementNo < 0) ||
(elementNo > maxElement) ||
elementNo == lastElement) {
:
}
It should be replaced by:
boolean isFinished = elementNo < 0 || elementNo >
maxElement; boolean isRepeatedEntry = elementNo ==
lastElement;
if (isFinished || isRepeatedEntry) {
:
}
When assigning boolean variables to the expressions, the program obtains
documentation automatically. The construction will be easier to read,
debug and maintain.
2. The nominal case should be placed in the if part and the exception in the
else part of an if statement.
boolean isError =
readFile (fileName);
if (!isError) {
:
}
else {
:
}
Make sure that exceptions do not detract from the normal route of
execution. This is important for both readability and for the
performance.
3. The conditional should be placed on a separate line.
if (isDone) // NOT: if
(isDone) doCleanup();
doCleanup();
This is for debugging purposes. When written in a single
line is not visible when the evaluation is true or false.
4. Executable statements should be avoided in conditionals.
file = openFile(fileName); // NOT: if ((file =
openFile (fileName)) != null) {
if (file != null) { // :
: // }
}
Conditionals with executable statements are difficult to read. This is
particularly true for Java programmers.
Miscellaneous
The use of magic numbers in the code should be avoided.
different numbers than 0 and 1 can be considered instead,
declared as named constants.
private static final int TEAM_SIZE = 11;
:
Player[] players = new
Player[TEAM_SIZE]; // NOT:
Player[] players = new
Player[11];
If the number does not have an obvious meaning in itself, readability will
improve by introducing a named constant instead.
2. Floating point constants should always be written with
decimal point and with at least one decimal.
double total = 0.0; // NOT: double
total = 0; double speed = 3.0e8; //
NOT: double speed = 3e8;
double sum;
:
sum = (a + b) * 10.0;
This emphasizes the different nature of integers and floating point.
floating. Mathematically the two model different concepts and not
compatible. Also, as in the example, this emphasizes the type of variable
assigned (sum) to the point in the code where it may not be evident.
3. Floating point constants should always be written with
one digit before the decimal point.
double total = 0.5; // NOT: double total = .5;
The number and expression system in Java is taken from conventions.
mathematics for syntax as much as possible. Likewise, 0.5 is more readable than
There is no way it can be confused with the whole number 5.
4. Static variables or methods should always be referred to by the
class name and never by the name of an instance.
Thread.sleep(1000); // NOT: thread.sleep(1000);
This emphasizes that the referenced element is static and independent.
from any particular instance. For the same reason, the class name
it should be included when a variable or method is accessed from within the
same class.
Organization and
comments
Organization
The basic indentation should be 2.
for (i = 0; i <
nElements; i++)
a[i] = 0;
Indentation is used to emphasize the logical structure of the code.
an indentation of 1 is too small to reach it. The greater indentation
4 makes the code very deep and difficult to read and increases the
probability that the lines break. Choosing among the indentations
of 2, 3, and 4; 2 and 4 are the most common, and 2 is chosen to reduce the
possibilities of breaking the lines of code. Note that the
Sun's recommendations at this point are 4.
2. Block Organization. The organization of blocks should be like
it is illustrated in example 1 below (recommended) or example 2, but not
as shown in example 3. The blocks of class, interface, and method
They should use the block organization from example 2.
while (!isDone) { while (!isDone) while (!isDone)
doSomething(); { {
isDone
moreToDo();
doSomething(); = doSomething(); =
isDone
moreToDo(); moreToDo();
} }
Example 3 introduces an extra level of indentation that does not emphasize the
logical structure of the code as clearly as example 1 and 2.
3. Class and interface declaration. Class and interface declarations.
interfaces should be in the following form.
class SomeClass extends
AnotherClass implements
SomeInterface
AnotherInterface
{
...
}
This follows the general block rule specified above. Note that it is
It is common in the Java developer community to have open keys.
at the end of the line of the reserved word class. This is not recommended.
4. Method declarations. Method declarations should have
the following form.
public
void
someMethod
() throws
SomeException
{
...
}
See the comments in the class statements above.
5. If-else. The if-else statements should have the following form.
if (condition) {
statements;
}
if (condition) {
statements;
}
else {
statements;
}
if (condition) {
statements;
}
else if (condition) {
statements;
}
else {
statements;
}
This partly follows the general rule of blocks. However, it should
to discuss whether the else clause should be on the same line as the closing of
brackets of the previous if or else clause.
if (condition) {
statements;
}
else if (condition) {
statements;
}
else {
statements;
}
This is equivalent to Sun's recommendation. The chosen style is considered
better in the sense that each part of the if-else statement is written on separate lines
separated from the file. This would make it easier to manipulate the statement, for
example when moving the else clauses.
6. For statement. The for statement should have the following form.
for (initialization;
condition; update) {
statements;
}
This is consistent with the general rule of blocks.
7. Empty for statement. An empty for statement should have the following form.
for (initialization; condition; update)
;
This emphasizes the fact that the for statement is empty and makes it obvious for the
reader who is intentional.
8. While statement. The while statement should have the following form.
while
(condition)
{
statements;
}
This follows the general rule of blocks.
9. do-while statement. The do-while statement should have the following form.
do
s
tatements;
} while (condition);
This follows the general rule of blocks.
10. Switch statement. The switch statement should have the following form.
switch
(condition)
{ case
ABC :
statements;
//
Fallthrough
case
DEF :
statements;
break;
case
XYZ
:
statements;
break;
default
:
statements;
break;
}
This differs from Sun's recommendation both for indentation and for
spaced. In particular, each reserved word case is indented relative to the
switch statement as a whole. This makes the entire statement consistent.
switch. Note the extra space before the character. The comment
Explicit // Continuing execution should be included when there is a statement
case without a break clause. Leaving the break statement out is a mistake
common and it should be clear that it is intentional when it is not there.
11. Try-catch statement. A try-catch statement should have the following
form.
try
{
statements;
}
catch (Exception
exception) {
statements;
}
try
{s
tatements;
}
catch (Exception
exception) {
statements;
}
finally
s
tatements;
}
This is part of the general rule of blocks. This form differs from the
recommendation from Sun in the same way as the if-else statement described
above.
12. Simple if-else, for or while statements. The if-else, for or
while should be written without braces.
if
condition
statement;
while
(condition)
statement;
for (initialization;
condition; update)
statement;
It is a common recommendation (including Sun's recommendation) that the
keys should always be used in all cases. However, the keys
They are generally a construction of language that groups several statements.
Keys are by definition superfluous in a simple statement. A
the argument against this syntax is that the code
it will cut off if a statement is added without adding the braces. In general without
embargo, the code should never be written to accommodate changes that
could arise.
Blank spaces
1. General rules. The following rules should be followed:
Operators should be surrounded by a space character.
2. Java reserved words should be followed by a space
in white.
3. Commas should be followed by a space.
4. The two colons should be surrounded by whitespace.
5. The semicolons in for statements should be followed by a
blank space.
a = (b + c) *
d;
NOT: a=(b+c)*d
while (true) { b, c, d); // NOT: while(true) ...
doSomething (a, // NOT: doSomething (a,b,c,d);
case 100 : 10; i++) { // NOT: case 100:
for (i = 0; i
<
// NOTE: for(i=0;i<10;i++){
Make the individual components of the sentences consistent and improve it.
legibility. It is difficult to provide a complete list of the suggested use of space in
blank in the code in Java. The examples above should however give a
general idea of intentions.
2. Function Names. Function names should be
followed by a blank space when followed by another name.
doSomething(parameter); // NOT: doSomething(parameter);
doSomething(); // OK
This makes individual names consistent and improves readability.
When it is not followed by any name, the space can be omitted since
there is no doubt about the name in this case. An alternative to this
the proposal is to require a space after opening the parenthesis. Those who
They usually leave a space before closing this standard.
the parenthesis. This makes individual names consistent as it is the
intention, but the space before the closing parenthesis is somewhat artificial, and
without this space, the sentence looks asymmetrical.
3. Logical units. Logical units should be separated by a
blank line.
Matrix4x4 matrix = new Matrix4x4();
double cosAngle =
Math.cos(angle); double
sinAngle = Math.sin
(angle);
matrix.setElement (1, 1,
cosAngle);
matrix.setElement(1, 2,
sinAngle);
matrix.setElement (2, 1,
-sinAngle);
matrix.setElement (2, 2,
cosAngle);
multiply (matrix);
This improves readability by introducing a blank space between the
logical units of a block.
4. Methods. The methods should be separated by 3-5 blank spaces.
Making the space larger than the space within a method, the
methods will be differentiated within the class.
5. Variables. The variables in the statements should be aligned to the
left, thus improving the readability of the code.
TextFile file;
int nPoints;
double x, y;
Variables are easier to distinguish from types by aligning them.
6. Sentences. The sentences should be aligned where improvement is made.
readability.
if (a == lowValue) computeSomething();
else if (a ==
mediumValue)
computeSomethingElse();
else if (a == highValue) computeSomethingElseYet();
value = (potential * oilDensity) / constant1 +
(depth * waterDensity) / constant2 +
(zCoordinateValue * gasDensity) / constant3;
computeDistance(min, x, y, z);
computeDistance(average, x, y, z);
Oil
case PHASE_OIL
Water
Gas
}
There are several places in the code where whitespace can be included
to improve readability even if it violates common rules. Many of
the cases are related to code alignment. The general rules for
the code alignments are difficult to provide, but the examples above should
give a general idea of the idea. In simple terms, any construction
that improves readability should be allowed.
Comments
1. Confusing code. Confusing code should not be commented but
rewrite. In general, the use of comments should be minimized.
making the self-documenting code with appropriate choices of
explicit names and logical structures.
2. Language. All comments should be written in English. In a
In the international environment, English is the preferred language.
3. Use //. Use // for all comments that are not JavaDoc.
including multiline comments.
1. Comment spanning
2. more than one line
Since multi-level comments are not supported, the use of the
comments // ensures that it is always possible to comment on sections
enter parts of a file using /* */ for debugging purposes, etc.
4. Indentation of comments. Comments should be indented.
related to their position in the code.
while (true) { // NOT: while (true) {
// Do something // // Do something
something(); // something();
} // }
This helps prevent comments from breaking the logical structure of the
program.
5. Collections. The declaration of collection variables should be
followed by a comment that establishes the common type of the elements
from the collection.
private Vector points_; // of Point
private Set shapes_; // of Shape
Without the extra comment, it can be difficult to imagine what the collection consists of.
and how to handle the elements of the collection. In methods that take as
input variable collection, the common type of the elements should
specify in the associated JavaDoc comment.
6. Classes and functions. All public classes and public functions and
protected within public classes should be documented
using Java documentation conventions (javadoc). This
makes it easier to keep the online documentation of the code up to date.
Bibliography
1. Java Programming Style Guidelines
The provided text is a URL and cannot be translated.
2. Java Code Conventions
Invalid input for translation. Please provide text for translation.