Java Development Reference Volume I

machinebrainySoftware and s/w Development

Jun 8, 2012 (5 years and 12 days ago)

307 views

G
E
N
E
R
I
C
A
C
O
U
S
T
I
C
M
O
D
E
L
I
N
G
U
N
I
V
E
R
S
A
L
T
O
O
L
K
I
T

Java Development Reference
Volume I
Style Guide
Rev 2.0
28 August 2003
Appl ied Hydro-Acoustics
Research I ncorporated

Applied Hydro-Acoustics Research, Inc.
5885 Trinity Parkway
Suite 230
Centreville, VA 20120



Prepared by:
Robert J. Blanchard





Table of Contents

1.0

Introduction
.......................................................................................................................1

1.1

Why Do We Need a Style Guide?
.................................................................................1

1.2

What is GAMUT?
...........................................................................................................1

1.3

What is Component-Based Development?
...................................................................2

1.4

How Should This Style Guide be Used?
.......................................................................2

1.5

Documentation Conventions
.........................................................................................3

1.6

Background
...................................................................................................................3

1.7

Acknowledgements
.......................................................................................................3

1.8

Point of Contact
.............................................................................................................4

2.0

Files
...................................................................................................................................5

2.1

File Length
.....................................................................................................................5

2.2

Statement Order
............................................................................................................5

3.0

General Formatting
...........................................................................................................6

3.1

Indentation
.....................................................................................................................6

3.2

Line Length
....................................................................................................................6

3.3

Line Wrapping
...............................................................................................................6

4.0

Comments
.........................................................................................................................8

4.1

Implementation Comments
............................................................................................8

4.2

Documentation Comments
..........................................................................................10

5.0

Naming Conventions
.......................................................................................................13

5.1

Packages
.....................................................................................................................13

5.2

Classes
........................................................................................................................13

5.3

Interfaces
.....................................................................................................................13

5.4

Methods
.......................................................................................................................14

5.5

Standard Variables
......................................................................................................14

5.6

Constants
....................................................................................................................15

5.7

User Interface Variables
..............................................................................................16

6.0

Declarations
....................................................................................................................18

6.1

Placement
....................................................................................................................18

6.2

Initialization
..................................................................................................................18

6.3

Assigning Values to Variables or Constants
................................................................18

7.0

Statements
......................................................................................................................21

7.1

Simple Statements
......................................................................................................21

7.2

Compound Statements
................................................................................................22

8.0

Blank Space
....................................................................................................................25

8.1

Blank Lines
..................................................................................................................25

8.2

Blank Spaces
...............................................................................................................25

9.0

Programming Practices
...................................................................................................26

9.1

Class and Instance Variables
......................................................................................26

9.2

Class Methods
.............................................................................................................26

9.3

Parentheses
................................................................................................................26

9.4

Assigning Variables
.....................................................................................................26

9.5

Constants
....................................................................................................................27

9.6

Code Normalization
.....................................................................................................27

9.7

Bug Notices
.................................................................................................................27

9.8

Debugging
...................................................................................................................28

10.0

Addenda
......................................................................................................................29

2
1.0 Introduction

Welcome to the
Java Development Reference, Volume I – Style Guide
for the Generic Acoustic
Modeling Universal Toolkit (GAMUT).

1.1 Why Do We Need a Style Guide?

It is extremely important to have well defined and documented coding standards. This allows
for improved readability of software code, and reduces the “ramp up” time for new developers to
be involved on a project. In general, about 80% of the life cycle cost of software is dedicated to
maintenance, which typically requires significant forays into the depths of the source code that
comprises it. Successful software projects should aim to maintain their source code in as
professional and polished a state as the other products created by the company.

Coding standards are not meant to stifle creativity, but to enhance it through the use of a
familiar baseline for writing and improving software. This helps to allow seamless integration of
modules and files produced by different authors at different locations. However, to work well,
these standards must be embraced by all:

“For the conventions to work, every person writing software must conform to the code
conventions. Everyone.”
-Java Code Conventions (Rev. April 20, 1999)

1.2 What is GAMUT?

GAMUT is the Generic Acoustic Modeling Universal Toolkit. The design philosophy of GAMUT
is to create a toolkit of reusable objects that can be easily interconnected to create acoustic
simulation applications.

The initial implementation set of GAMUT will consist of functionality replacements for the Multi-
Static Active System Model (MSASM). MSASM is capable of estimating the performance of
active sonar systems for multiple source, receivers, and targets. It simulates target motion
including such features as normal and uniform probability distributions, various speed and
course distributions, as well as target evasion modeling to a limited degree. GAMUT will further
improve upon the capability of MSASM by adding additional active and passive detection
algorithms and functionality provided by such products as the Active System Performance
Estimate Computer Tool (ASPECT) and the Passive Radiation Estimated Detection Interactive
Computer Tool (PREDICT).

Additional information about the GAMUT baseline can be found in the Functional & Operational
Requirements Documents (FORDs) written in support of the GANIMEADE (GAMUT-based
Acoustic Netcentric Interactive Multistatic Engineering & Analysis Development Environment)
and ASPECT-PLUS (ASPECT Passive & Localization Upgraded Software) projects.
GANIMEADE will be built using GAMUT tools to create an application that borrows some
functionality from ASPECT, but extends certain capabilities for specific use in the laboratory and
research environment. ASPECT-PLUS is the next generation of ASPECT, which will
1
incorporate the passive capabilities of PREDICT, in addition to providing coordinated passive
and active detection processing.

1.3 What is Component-Based Development?

Structured programming languages (Fortran, Pascal, C, etc) allow for an application to be
broken up into constituent elements or routines, however, this is usually only effective for small-
scale applications. Object-oriented programming languages such as C++, Java, SmallTalk, and
Eiffel not only allow a program to be broken up into elements, but force the designer to consider
the notion of objects that encapsulate both self-contained data and functionality elements.
Object-oriented programming (OOP) creates a level of abstraction, where the design easily
exists on two planes: one of interacting objects and the other of the actual object definitions
which would encompass interaction of data and method members. This separation does add
additional overhead to the design stage of a software development project, however, it does
make both the design and coding of applications more convenient and efficient than structured
programming, as well as allow for greater code reusability.

A natural extension to object-oriented programming (OOP) is the concept of component-based
software development. While using OOP creates the notion of modular programming, truly
reusable code requires the ability to package these modules as components to physically
separate them from the entire code base of an application and allow for their manipulation as
self-supporting entities. Components provide an additional abstraction layer that allows a
software designer to create an application using a builder tool by connecting components
together without needing to know any of the underlying code behind their creation. Components
typically use some form of introspection, which allows a builder tool to identify information about
the properties, events, and methods of a component. Once a toolkit of components has been
created, the builder tool allows for rapid application development using these components.
Upgrading an application developed with components is a straightforward procedure of
disconnecting the old component and connecting the new.

Therefore, GAMUT will be both object-oriented and use the component-based software
development model. This will maximize the efficiency with which it will be developed,
implemented, reused, and upgraded.

An evaluation of the two most widely used methods of implementing component-based
software, ActiveX and JavaBeans, can be found in the Design Considerations document,
produced by Applied Hydro-Acoustics Research, Incorporated, dated February 15, 2001.

1.4 How Should This Style Guide be Used?

This documentation is intended as a specification for proper formatting and methodologies for
coding modules that will be used as part of GAMUT. All Java coding performed in support of
GAMUT development should conform to the conventions outlined in this document. Coding in
other languages should borrow from these guidelines as applicable.

2
1.5 Documentation Conventions

Much of the information contained in this Style Guide has been adapted from the Code
Conventions for the Java Programming Language, Revised April 20, 1999. The latest version of
this documentation is available from Sun Microsystems, Inc. at the following address:

http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html

Another primary resource for this Style Guide is
The Elements of Java Style
, written by Allan
Vermeulen, Scott W. Ambler, Greg Bumgardner, Eldon Metz, Trevor Misfeldt, Jim Shur, and
Patrick Thompson.

Code samples in this document are formatted using a monospaced Courier font. Pseudocode
within a sample is designated by using an italicized monospaced Courier font.

1.6 Background

As mentioned earlier, GAMUT is a next-generation modeling and simulation toolkit, designed to
replace and extend the functionality of the MSASM model.

MSASM was originally developed by the Science Applications International Corporation (SAIC)
and the Center for Naval Analysis (CNA). The current version of MSASM is controlled by the
Naval Air Warfare Center at the Patuxent River Naval Air Station in southern Maryland.

ASPECT and PREDICT were developed by the Modeling and Simulation Team of Applied
Hydro-Acoustics Research, Incorporated.

GANIMEADE and ASPECT-PLUS will be designed and developed by the Modeling and
Simulation Team of Applied Hydro-Acoustics Research, Incorporated, and will be based on
components created as part of GAMUT.

1.7 Acknowledgements

The Modeling and Simulation Team of Applied Hydro-Acoustics Research, Incorporated is
responsible for the primary coding and implementation of GAMUT. GAMUT team members are:

Brian Samuels, Director of Modeling and Simulation
Robert Blanchard, Software Development Lead
David Brown, Quality Assurance
Phat Tran, Programmer
Alex Taylor, Programmer
David Yu, Programmer

Special thanks to the sponsors of the GAMUT program, including the GANIMEADE and
ASPECT-PLUS projects, and those who have contributed to the creation of this document.

3
1.8 Point of Contact

For more information on the GAMUT program, please contact:

Applied Hydro-Acoustics Research, Inc.
Attn: Brian C. Samuels
5885 Trinity Parkway
Suite 230
Centreville, VA 20120

Phone: 703-968-8040
Fax: 703-968-8101
Email:
samuels@aharinc.com


For feedback specific to this document, or any other GAMUT Java Developer’s Reference
document, please contact:

Applied Hydro-Acoustics Research, Inc.
Attn: Robert J. Blanchard
5885 Trinity Parkway
Suite 230
Centreville, VA 20120

Phone: 703-968-8040
Fax: 703-968-8101
Email:
robert@aharinc.com


Please also visit our web site at
http://gamut.aharinc.com
.



4
2.0 Files

Java source files should use the class or interface name being referenced as their filename,
with a “.java” extension. Bytecode files are always referenced with the same name as the
source file, but with a “.class” extension.

2.1 File Length

Files should be limited to approximately 2000 lines where feasible. Methods and the like should
be limited to approximately 500 lines. A file will contain the entire complement of code required
by a particular class or interface (variables, constructors, methods, as well as useful comments).

2.2 Statement Order

The first non-comment line of a source file is a package statement followed by a blank line.
Import statements should follow the package declaration.

2.2.1 Classes and Interfaces

The following list contains the order that segments of a class or interface definition should
appear:

• Documentation comment (“/** …. */”) – see section 4.2 for definition
• Class/Interface statement
• Implementation comment – see section 4.1 for definition
• Class/Interface variables
o Public (“public” access modifier)
o Protected (“protected” access modifier)
o Package level (no access modifier)
o Private (“private” access modifier)
• Instance variables
o Public (“public” access modifier)
o Protected (“protected” access modifier)
o Package level (no access modifier)
o Private (“private” access modifer)
• Constructors
• Methods (grouped by functionality)
5
3.0 General Formatting

All code should conform to the following general formatting specifications.

3.1 Indentation

Four spaces is the unit of indentation (an accepted industry standard). Most Integrated
Development Environments (IDEs) have the capability to set automatic indentation for this
amount. Indents should be made using spaces, or tabs if your IDE can convert them to spaces
when saved (NetBeans-based IDEs do this by default, and can be set in the Indentation Engine
properties).

3.2 Line Length

All lines must be less than 120 characters. 80 characters per line, or fewer, is optimal.

3.3 Line Wrapping

Lines that exceed 120 characters must be wrapped. Wrapped lines should be broken at the
following points:

• After a comma
• Before an operator

3.3.1 Expressions and Argument Lists

Expressions should be broken at higher levels versus lower levels, if possible:

x = (-0.5F * spacingX * (postsPerRow – 1))
+ (spacingX * (thisPost – 1)); // acceptable break

x = (-0.5F * spacingX * (postsPerRow
– 1)) + (spacingX * (thisPost – 1)); // avoid: harder to read

If space permits, wrapped expressions or arguments lists should be aligned with the beginning
of the previous line’s expression segment or arguments:

nseLoss(passiveMode, thisBand, Processor,
transientMinFrequency, transientMaxFrequency,
transientDuration); // preferred for arg lists

If there is not enough room to reasonably wrap lines with the preferred alignment convention, a
single indent from the level of the first line should be used:
6

environmentInterpolateAmbientNoiseFromFrequencyTable(frequencyArray,
noiseArray, frequency); // otherwise it’d be squished right

3.3.2 Conditional Clauses

Wrapped conditional clauses (as part of if statements and the like) should be indented past the
left parenthesis of the beginning of the clause to declutter the statement block that follows:

if ((condition1 && condition2)
|| !(otherCondition1 || otherCondition2)
|| (condition3 && condition4)) {
statement; // hard to see statement; avoid
}

if ((condition1 && condition2)
|| !(otherCondition1 || otherCondition2) // preferred
|| (condition3 && condition4)) {
statement;
}

3.3.3 Ternary Clauses

A special case of conditional clause, expressions involving the ternary operator, which must be
wrapped, should align the then (“?”) and else (“:”) operators:

postsInRow = (thisRow % 2 == 1) ? postsInFirstRow
: (postsInFirstRow + 1); // ok

postsInRow = (thisRow % 2 == 1)
? postsInFirstRow
: (postsInFirstRow + 1); // ok, too





7
4.0 Comments

Java supports two different types of comments: implementation comments (which are standard
to all programming languages), and documentation comments. Documentation comments are
also referred to as “doc comments”, and can be extracted using the javadoc utility.

In general, comments should not be enclosed in “boxes” drawn with asterisks or other
characters, as shown below:

/************************************************************
* *
* Please do not make comments that look like this. *
* *
************************************************************/

Do not use special characters, such as control characters, in comments.

Always keep comments up to date. Code should be commented as it is written, not afterwards
(or, better yet, write the comments first, then fill in the code).

If a licensing specification is created, or copyright notice is required, it should be specified as a
block comment and be located at the beginning of the source file.

4.1 Implementation Comments

Implementation comments should be used to provide information about code that may not be
obvious from cursory examination. Do not use comments where the code is clear, as in:

x = 6; /* set x to 6 */

Implementation comments can appear in four different varieties:

• Block
• Single-Line
• End-of-Line
• Code

4.1.1 Block Comments

Block comments should be used to provide descriptions of algorithms, methods, or data
structures. They should be placed at the beginning of files and methods, and indented to the
same level as the code they are explaining.

Block comments should be set off from code with a blank line before the block. The “/*”
comment style should be used as opposed to “//” comments. Each line of text should be
preceded with an asterisk, as shown below:
8

/* Create drop information for drop plan list box
* in Patterns section of main screen.
*/

A block comment can be started with “/*-“, versus “/*”, which signals to external reader programs
and pretty formatters that the text within the block should not be reformatted:

/*-First, find the |\ triangles
* | \
* ---
*
* If I didn’t protect the format, my ASCII triangle might look wrong
*/

4.1.2 Single-Line Comments

Brief comments pertaining to a particular code segment can be placed on a single line, indented
to the level of the code which it describes. They can use either the “/*” or “//” format. However,
if it takes longer than one line, it should follow the formatting convention for a block comment
(and use “/*”). A blank line should precede the comment to improve readability. A trailing blank
line is not necessary.

4.1.3 End-of-Line Comments

End of line comments should only be used when a very brief statement can be made on the
same line as code it explains. These comments should be shifted right of the code far enough
to appear truly separate. The “//” format is used for end of line comments.

End of line comments should be used to label closing braces in highly nested code segments,
as in:

for (thisRadial... ) {
for (thisInclination...) {
for (thisSample...) {
statement;
} // end for thisSample
} // end for thisInclination
} // end for thisRadial

4.1.4 Code Comments

When code is commented out for any reason, the entire block should use the “//” comment
delimiter. The delimiters should appear at the beginning of every line within the block,
regardless of indentation level, blank lines, or previous comment delimiters. This is because
NetBeans provides a code-comment feature that can be turned on by highlighting the section of
9
code to comment out and pressing Shift+Ctrl+T. The code block can be uncommented by
highlighting the entire section and pressing Shift+Ctrl+D.

A comment should precede the commented out code that explains the reason for the section
being commented. This comment may be either a single line or block comment, but must be set
off from the commented code with a blank line (even for a single line comment).

4.2 Documentation Comments

Documentation comments contain specific tags for use with the javadoc program, which is used
to generate code documentation. Documentation comments can appear immediately before
any of the following:

• Class
• Interface
• Constructor
• Method
• Field Declaration

4.2.1 Class/Interface Doc Comments

All classes and interface will contain a documentation comment that contains:

• Description of the class/interface
• List of authors
• Initial implementation date
• Version history

The format of the class/interface doc comment is shown below:

/**
* Description of class or interface.
*
* @author Robert J. Blanchard
*
* @since 30 MAY 2001
*
* @version 001 – Initial code.<BR>
* 002 – Added different functionality.<BR>
*/

Each author that works on the code should be listed with their own @author tag. The @since
tag is used denote when the file was first created.

The @version tag provides a brief history of the changes made in different versions of the code.
Note that the <BR> HTML tag at the end of each line in the version history is necessary for
proper layout when parsed by the javadoc generator. It may be useful to note that
10
documentation comments can make use of any HTML tags to provide custom formatted
information.

4.2.2 Constructor/Method Doc Comments

All constructors and methods of a class or interface will contain a documentation comment that
contains:

• Description of the constructor/method
• List of parameters and definitions of parameters
• Return information (if method is not declared “void”)
• List of exceptions thrown
• Initial implementation date

The format of the class/interface doc comment is shown below:

/**
* Description of method.
*
* @param x1 x location of first coordinate
* @param y1 y location of first coordinate
* @param x2 x location of second coordinate
* @param y2 y location of second coordinate
*
* @return Cartesian distance between coordinates
*
* @exception Some exception
*
* @since 30 MAY 2001
*/

Each parameter should have its own @param tag. Parameters should be listed in the order
they are declared for the method. If the method returns anything other than void, an @return
tag should be used to indicate what value is being returned. All exceptions that are capable of
being thrown should be listed using the @exception tag. The @since tag is used denote when
the method was first created.

4.2.3 Field Declaration Doc Comments

All class variables and instance variables of a class should contain a documentation comment
that explains what the variable refers to, and what units it expects, if applicable. This comment
can be either a single line or block doc comment (a single line is preferred if the information fits
within a single line):

11
/** Center latitude of area of interest (AOI) in float degrees. */

private float latitude;

/**
* Windspeed in knots.
*/

private float windspeed;




12
5.0 Naming Conventions

All names for identifiers should use alphanumeric characters (“A-Z”, “a-z”, “0-9”). Constant
identifiers are permitted to use the “_” character. Abbreviations and acronyms in names should
be avoided, unless it is more common to use the shortened form of the word (e.g. “EER”,
“HTML”, “MODAS”). Names should be meaningful.

• Packages
• Classes
• Interfaces
• Methods
• Standard Variables
• Constants
• User Interface Variables
• Beans

5.1 Packages

Packages should be named with nouns. Package names should use lowercase. The reverse
domain name of the contributing group should be used to specify the beginning of the name of
the package, with “gamut” as the subpackage identifier, followed by the remainder of the
package specification:

package com.aharinc.gamut.databases; // package created by AHA

package mil.navy.navair.gamut.databases; // package created NAVAIR

5.2 Classes

Classes should be named with nouns. Class names should use mixed case, with the first letter
only of each word capitalized. This applies to accepted abbreviations and acronyms, as well.
Examples are:

class Source;
class ModasField;
class HtmlPage;

5.3 Interfaces

Interfaces can be named with nouns or adjectives. Interface names should use mixed
case, with the first letter only of each word capitalized. This applies to accepted
abbreviations and acronyms, as well. Examples are:

public interface ThreatListener {
13
statement;
}

public interface Runnable {
statement;
}

5.4 Methods

Methods should be named with verbs, or predicate clauses. Method names should use mixed
case, with the first letter of the first word lowercase and all subsequent words in the method
name with their first letter capitalized. This applies to accepted abbreviations and acronyms, as
well. Examples are:

public float getSoundSpeed() {
statement;
}

private void parseModasEofMessage() {
statement;
}

Methods that are defined within JavaBeans relating to retrieving and modifying the value of a
specific field are called accessor and mutator methods. Accessor methods should always be
named by using the word “get” and appending the variable name (capitalizing the first letter in
the variable name). Similarly, mutator methods should prefix the variable name with “set”.

int rotationAngle;

public int

5.5 Standard Variables

The selection of names for regular variables should attempt to briefly convey the intent of use of
the variable. Variable names should use mixed case, with the first word in lowercase and all
subsequent words in the variable name with their first letter capitalized. This applies to
accepted abbreviations and acronyms, as well.

5.5.1 Loop Counters

Variables that are used as loop counters should use the word “this” as the first word of the
variable name. If it is necessary to use embedded loops with the same counter name, each one
should be suffixed with an increasing ordinal (starting at 1):

for (int thisAngle = 0; ...) {
statement;
}
14

for (int thisPost1...
for (int thisPost2...
for (int thisPost3...
...
}
}
}

5.5.2 Total Specifiers

When using a variable within a class to represent a cardinal total of items, use the word “num”
as the first word of the variable name, and make the remainder of the name plural:

float angle;
int numAngles;

5.6 Constants

All constant names should be in uppercase, with words separated by underscore (“_”)
characters. Abbreviated forms of some words are acceptable, such as MIN for
minimum and MAX for maximum. Identifiers for units should be used where more than
one unit might commonly apply. Constants should always be declared as “static final”.
Examples:

static final int MIN_FREQUENCY = 5
static final int MAX_DEPTH_FT = 40000

5.6.1 Acceptable Constant Abbreviations

The following abbreviations are acceptable for use in constant names:

MIN
minimum
MAX
maximum
M
meters
FT
feet
KM
kilometers
NMI
nautical miles
SEC
seconds
DEG
degrees
RAD
radians
LAT
latitude
LON,LONG
longitude
HORZ,HORIZ
horizontal
15
VERT
vertical

5.7 User Interface Variables

All user interface (UI) variables should attempt to briefly convey the intent of use of the variable.
Variable names should use mixed case, with the type identifier in lowercase and all subsequent
words in the variable name with their first letter capitalized. This applies to accepted
abbreviations and acronyms, as well.

5.7.1 Type Identifiers

Java supports many user interface components in its Swing library. These should be specified
using the following type identifier prefixes:


Command Button
btn
Toolbar Button
btn
Checkbox
chk
Checkbox Menu Item
mnc
Combobox
cmb
Dialog
dlg
Frame
fra
Label
lbl
List
lst
Menu
mnu
Menu Bar
mnb
Menu Item
mni
Panel
pnl
Password Field
pwd
Popup Menu
mnp
Progress Bar
prg
Radio Button
rdo
Radio Button Menu Item
mnr
Scrollbar
scb
Scroll Pane
scp
Separator
sep
Slider
sld
Spinbox
spn
SplitPane
spp
Tabbed Pane
tab
Table
tbl
Text Area
txa
Text Field
txt
Text Pane
txp
Toggle Button
tog
Tool Bar
tbr
Tool Tip
tip
16
Tree View
tre
Window
win

Examples:

JButton btnClose;
JButton btnOpen;
JCheckBox chkEvasion;

17
6.0 Declarations

Only one declaration should appear per line. A single space or a tab is acceptable for use
between the type identifier and the variable.

6.1 Placement

Declarations should be placed at the beginning of code blocks (a block of code is any segment
that is surrounded by curly braces) and should appear at the lowest scope possible. For
example:

void sonarEquationTargetStrength(float signalExcess, float aspect) {

// variable used throughout function

float tempSignalExcess = signalExcess;

if (activeTargetStrength) {
float targetStrength = 0F; // just used in this block

targetStrength += Threat.getActiveTargetStrength(aspect);
tempSignalExcess += targetStrength;
}
tempSignalExcess += Threat.getSomeTargetStrengthCorrection();
}

A special case of declaration is in for loops. The initialization clause can include declarations, if
the variable is only used within the scope of that particular for loop. If the variable will be used
in other loops within the same method, it should be declared at a higher scope.

6.2 Initialization

Local variable declarations should always contain initializations, unless the initial value
depends on some computation occurring later in the code.

6.3 Assigning Values to Variables or Constants

Java requires that certain primitive types be assigned values using a particular notation to
identify the literal value as the same type as the primitive type.

18
6.3.1 Characters

Characters should be assigned using either the literal enclosed in single quotes, or an escape
sequence enclosed in single quotes, or a Unicode sequence (all Unicode sequences consist the
Unicode escape sequence, “\u”, followed by a 4-digit hexadecimal number). Unicode numbers
must be 4-digits, using 0s as needed. Do not assign characters by using an integer value for
the literal:

char middleInitial = ‘A’;
char season = ‘4’;
char backslash = ‘\\’; // backslash escape sequence
char space = ‘\u0020’; // unicode for SPACE (ASCII value of 32)
char space = 32; // also a space, but should not be used

6.3.2 Bytes, Shorts, Integers

These data types should be assigned using either base 10 notation, octal notation (uses a
single leading “0”), or hexadecimal notation (“0x” followed by the hex-representation of the
number). Hexadecimal notation should use lowercase letters for the a-f characters. Only use
octal and hexadecimal when appropriate.

byte maskValue = 0xff; // hexadecimal 255
short shippingLevel = 8;
int distance = 67333;

6.3.3 Long Values

Longs are similar to bytes, shorts, and integers, in that they can be assigned values using base
10, octal (leading “0”), or hexadecimal notation (leading “0x”). Long values, however, must have
a trailing “L” to be properly interpreted. Hexadecimal notation should use lowercase letters for
the a-f characters. Only use octal and hexadecimal when appropriate.

long maskValue = -12345678L;
long address = 0xaab54cd32;

6.3.4 Floats and Doubles

Floating point values, either floats or doubles, must be specified using base 10. Exponents can
be assigned using a capital “E” followed by a “+” or “-“, and the appropriate power. Floats must
have a trailing “F” to be properly interpreted. Doubles must have a trailing “D” to be properly
interpreted:

float detectionThreshold = 3.4F;
float avogadro = 6.02E+23F; // molecules per mole
double power = 7.3E-23D; // very small number

19
6.3.5 Boolean Values

Boolean values in Java are truly binary, not just integers interpreted as boolean. The only
values that booleans can take are “true” or “false”, which can also be assigned using a
conditional statement:

boolean activeSensor = true;
boolean evadingTarget = false;
boolean notTrue = (6 > 7); // silly example, but evaluates as false




20
7.0 Statements

Each line of code should contain one statement, at most (obviously, more than one line may be
necessary to complete a statement).

Two types of statements exist: simple and compound. Compound statements are actually
groupings of individual (“simple”) statements that are enclosed in curly braces.

7.1 Simple Statements

Each line of code should contain one statement, at most (obviously, more than one line may be
necessary to complete a statement).

7.1.1 Return Statements

Return statements should only use parentheses if this makes the return value more obvious:

return (6); // unnecessary parens

return (status ? status : error); // parens make operation clearer

7.1.2 For Loops

Empty for loops are considered simple statements, and should appear as follows:

for (initialization clause; continue condition; update clause) ;

Note that there is a single space between the right parenthesis and the semicolon.

For loops should never have more than three comma-separated entries in the initialization
clause or update clause. Additional initializations should occur before the loop and additional
updates should occur at the end of the loop (the latter resulting in a compound statement,
described in Subsection 8.2.2).

7.1.3 While Statements

Empty while statements are considered simple statements, and should appear as follows:

while (condition) ;

Note that there is a single space between the right parenthesis and the semicolon.

Non-empty while statements are covered in Subsection 7.2.3.

21
7.2 Compound Statements

Compound statements should have their “sub-statements” indented one more level than the
heading statement:

if (condition) {
statement; // this statement is indented one level
statement; // and so forth...
}

Opening braces should always appear at the end of the line that begins the compound
statement, not on the next line as shown below:

if (condition)
{ // Please do NOT do this!
statement;
}

The closing brace should appear on a line, by itself, indented to the same level as the beginning
line of the compound statement.

Braces should always be used around blocks of sub-statements, even if there is only one. For
example:

if (condition) {
x = 4;
}

is acceptable, while the following is NOT:

if (condition)
x = 4;

The reason for this is that it will eliminate the possibility of bugs if this code is modified in the
future and additional statements are added to the compound statement block.

7.2.1 If Statements

All if statements are considered compound statements, and the aforementioned conventions are
applicable. If statements should take one of the following forms:

if (condition) {
statement;
}

if (condition) {
statement;
} else {
statement;
22
}

if (condition) {
statement;
} else if (condition) {
statement;
} else {
statement;
}

7.2.2 For Loops

For loops should never have more than three comma-separated entries in the initialization or
update clauses. Additional initializations should occur before the loop and additional updates
should occur at the end of the loop. An example of a compound for loop:

for (initialization clause 1, initialization clause 2;
continue condition;
update clause 1, update clause 2, update clause 3) {
statement;
}

7.2.3 While Statements

Compound while statements should appear as follows:

while (condition) {
statement;
}

7.2.4 Do-While Statements

All do statements are considered compound statements. An example of proper formatting is
shown below:

do {
statement;
} while (condition);

7.2.5 Switch Statements

All switch statements should contain a default case. The default case should appear last in the
case list and contain a break statement. All cases that “fall through” should contain a “falls
through” comment where the break statement would normally be. A properly formatted switch
statement would look like:

23
switch (condition) {
case 1:
statement;
break;
case 2:
statement;
/* falls through */
case 3:
statement;
break;
default:
statement;
break;
}

7.2.6 Try-Catch Statements

Try-catch statements should appear as follows:

try {
statement;
} catch (ExceptionClass e) {
statement;
}

try {
statement;
} catch (ExceptionClass e) {
statement;
} finally {
statement;
}

The finally block is optional, and will be executed regardless of the try outcome.
24
8.0 Blank Space

Blank space can be used to improve the readability of code by breaking it up into logical
groupings, as well as setting off important information, such as comments.

8.1 Blank Lines

One blank line should be used to:

• Separate methods within a class
• Separate variable declarations from code
• Set off comments from code (around block and single line comments)
• Separate logical blocks of code within a method
• Separate logical blocks of declarations

Two blank lines should be used to:

• Separate sections of a source file
• Separate class and interface definitions

8.2 Blank Spaces

A single blank space should be used:

• To separate binary operators (except for the . operator) from their operands
• To separate keywords followed by a parenthesis
• After commas in argument lists
• After semicolons in for loop statements
• Following casts (such as (int) x)

Blank space should never be used to separate:

• Unary operators from their operands (e.g. x++)
• Method names and their opening parenthesis
25
9.0 Programming Practices

Always aim to write code that is clear. While there may be a clever way to write a particular
section of code, if the meaning cannot be conveyed either through the code itself, or through
associated comments, it is better to write it in a clear fashion that may take more steps or be a
little slower.

9.1 Class and Instance Variables

Most instance or class variables should not be made public, but instead should use the concept
of data hiding and provide accessor methods for reading and writing internal data.

9.2 Class Methods

Class methods should never be called from an instantiated object, but instead from the class
name itself.

9.3 Parentheses

Parentheses should be used in expressions that involve mixed operators, so that the operator
precedence is clear to anyone viewing the code. The following statement may not be obvious to
some in its interpretation:

if (valueA == valueB && valueC == valueD) {
statement;
}

The preferred form should be:

if ((valueA == valueB) && (valueC == valueD))
statement;
}

Parentheses should always be used when evaluating a binary expression as part of a ternary
statement:

(value >= 0) ? value : -value; // parens improve readability

9.4 Assigning Variables

Multiple variable assignment within a single statement should not be used:

valueX = valueY = valueZ = 0; // avoid this
26

This also includes embedded assignments, which may be intended to speed up
performance of a code segment:

value1 = (value2 = value3 + value4) + value5; // hard to follow

value2 = value3 + value4;
value1 = value2 + value5; // compiler will optimize this on its own

9.5 Constants

Except for –1, 0, and 1, numerical literals (“hardwires”) should be avoided except to initialize a
variable when it is declared. Typically, there should be either a constant variable or a method
that will contain the value required:

for (angle = 0; angle < 90; angle++) { // where did 90 come from?
statement;
}

numAngles = beamPattern.getNumAngles(); // preferred
for (angle = 0; angle < numAngles; angle++) {
statement;
}

9.6 Code Normalization

Code should be simplified where possible. Obfuscations should be avoided:

if (booleanValue) { // is there an easier way?
return true;
} else {
return false;
}

return booleanValue; // yes there is

9.7 Bug Notices

If a particular class is determined to not work properly, but the exact location of the problem is
unknown, the code should contain a single line comment at the top of the source file (before the
class/interface statement, but after the documentation comment):

/* FIXME */

If a more specific location within the class file is identified as the problem, the comment should
be placed in that location.
27

A block comment can be used after the “FIXME” comment to explain the problem further.

9.8 Debugging

It is recommended that the IDE’s debugging front end or just jdb (Java debugger) be used for
investigating code execution. If you must add print statements that are intended for use with
debugging activities, you should use the following procedure:

Create an interface called Debuggable, if there is not one already available in the current
package (you could likewise import the Debuggable interface from another package, if it is
defined there). Declare debugging constants as necessary and set their initial values:

public interface Debuggable {
public static final boolean DEBUG = true;
}

Then, implement the interface in any class that you wish to debug, and use conditional
statements around the print statements:

class MyClass implements Debuggable {

void main(String args[]) {

if (DEBUG) {
System.out.println(“In MyClass”);
}
}
}

When through debugging, reset appropriate constant values in the interface (in this case, just
set DEBUG to false).

The reason for this entire procedure is threefold. First, it simulates conditional compilation
because the compiler will ignore the code in the conditional if it is a constant that evaluates to
false. Second, this provides an easy means of searching for classes that are being debugged,
by searching for the implementation of the interface. Third, it consolidates the definition of
debugging flags in a central location.

28
10.0 Addenda

This document may be revised with additional code conventions, as long as they do not conflict
with or negate previously established conventions. All revisions will be so marked in the text
along with the date they were established. The baseline set of conventions was established
June 12, 2001, with minor revision made to the publicly released Rev 2.0 on August 28, 2003.

To be placed on a mailing list to receive an electronic copy of revisions to this Style Guide,
please email:

robert@aharinc.com


with the subject “Subscribe: AHA Java Development Style Guide”.

The latest version of this document is also available through the GAMUT web site at
http://gamut.aharinc.com
.


29