What follows here is a set of reasonably widely used Java
programming style conventions. Whenever you move into a new programming
environment, any conventions you have been using previously may or may
not agree with the ones you are required to use in the new environment,
so you should examine the new conventions closely to see what is the
same, and what is different, from what you are used to. For the sake of
brevity, only a few specific examples to illustrate the style
conventions described here are given on this page, but the code you
will see in the source code examples of the course will illustrate this
style, for the most part, and any deviations will be pointed out as and
when they occur. You should take the style conventions you are required
to use very seriously, because your instructor and your marker(s) (and,
eventually, your employer) will surely do so.
Part A: Program Readability (Source Code Readability)
The "Big Three" of Programming Style (according to Scobey)
- Name things well, using the specified style conventions.
- Be consistent.
- Format continually, and re-format whenever necessary.
The importance of choosing a good name for each programmer-named
entity, thereafter spelling and capitalizing that name appropriately
and consistently, and continuing to position these names properly
within well-formatted code, cannot be overemphasized.
Rules for naming and capitalization of programmer-chosen
identifiers
Naming
-
Names must be meaningful within their given context whenever
possible, which is most of the time. Two exceptions to this rule
are:
- The use of single-letter loop control variables such as
i in those situations where no particular meaning
attaches to the variable.
- Use of a generic variable name such as x for reading
in values (real numbers, say) to which no particular meaning
applies.
-
Variables and value-returning functions are generally noun-like, as
in:
length
numberOfStudents
averageScore()
Boolean variables and functions, however, are usually
adjective-like, as in:
valid
isFinished()
Special (sometimes global, if permitted) boolean variables that act
as a switch to turn testing or debugging on or off begin with the
word testing or the word debugging, as
appropriate:
testingTextItems
debuggingDisplayOutput
When one is faced with the choice between long variable names and
clearer code, and short variables names and less clear code, the
choice should be obvious.
-
The name of every void function must begin with a
verb, as in:
time.incrementHours()
time.display()
But ... occasionally value-returning functions may begin
with a verb. One particular example of this is any "getter" and/or
"setter" member functions that appear in a class:
time.getHours()
time.setHours()
Capitalization
Names must always be capitalized consistently, according to whatever
conventions are being used for each category of name. Here are some
examples that illustrate our capitalization conventions:
-
Constants (all capital letters, with the words in multi-word names
separated by underscores)
final int SIZE = 100;
final double TAX_RATE = 0.15;
-
Variables ("camel" notation, which means that names start with a
lowercase letter, and all subsequent words in the name, if any,
begin with an uppercase letter}
double cost;
int numberOfGuesses;
-
Member functions names always start with a lowercase
letter:
int getHours();
void setHours();
void display();
-
Types start with a capital, use the "camel" notation described
above, and names for classes should be nouns that are usually
singular (but not always, as in TextItems}:
Menu
TextItems
RandomGenerator
String80
Rules for indentation and alignment
- Use an indentation level of 4 spaces, and always use
actual spaces, never the tab character.
-
Indent and align each of the following:
- Statements in the body of a function (with respect to the
corresponding function header)
- Statements in the body of a loop (with respect to the loop
keyword(s))
- Statements in the body of an
if
and, if the
else
is present, in the body of the
else
(The statements in the body of an
if
should always align with those in the body of the
corresponding else
, and the if
and
else
must themselves align, unless the entire
if..else construct is a short one on a single
line.)
- Member definitions in the definition of a
class
- Each level of nesting requires another level of indentation.
-
Align enclosing braces with each other, and also align:
- The braces enclosing a function body with the function
header
- The braces enclosing a loop body in a
while
,
do
or for
loop
- The braces enclosing the body of an
if
,
else
or switch
with the corresponding
if
, else
or switch
- The braces enclosing the body of a
struct
or
class
with the keyword struct
or
class
and with the access specifier(s)
public
, private
and/or
protected
(if present)
- Align comments with the thing commented (unless, of course, it is
an in-line comment.
- If a statement extends over more than one line, indent and align
the second and any subsequent lines for readability (which will
sometimes mean ignoring the 4-space-indentation rule for those
lines).
Use of whitespace
- Use vertical spacing to enhance readability. For example, use one
or more blank lines to separate logically distinct parts of a
program. In general, don't be afraid to use more vertical whitespace,
rather than less.
- Use horizontal spacing to enhance readability. For example, it is
usually a good idea to place a blank space on each side of an
operator such as
<<
or +
, though this
rule can be relaxed in a long complex expression where the enclosing
spaces may be removed from some of the operators to show more clearly
which operands are associated with particular operators.
-
Some programmers prefer to use a style that is almost "functional"
in nature in their writing of selection and looping statements, by
omitting the space between the selection or looping keyword and the
following left parenthesis, as in
if(condition) ...
while(condition) ...
for(int i=0; ... )
and so on. This is also permissible if used consistently.
Comments
- When commenting your code, you should strive to be informative
without being excessive. Your goal is to have readable code, and too
many comments can often be nearly as bad as, and sometimes worse
than, too few.
- At the beginning of a file, always have a comment containing the
name of the file, followed by a comment containing the purpose of the
code in that file. These two comments can often be one line each. You
may also want, or need, additional comments in this location, such as
the code author's name, the version number, the date of this version,
and even a list of modifications included in this version.
-
For each function, include the following information in the given
order:
- One or more comment statements describing in summary form (or
more detailed form if necessary) what the function does.
- The return value of the function.
- A list of the function's parameters in the same order as they
appear in the parameter list, with a description of each.
- The function's pre-conditions and post-conditions.
In the actual parameter list of any function, always place comments
(//in, //out, or //inout) to indicate
the conceptual nature of each parameter with respect to the
direction of information flow. For class member functions, these
comments must appear in both the class header file and the class
implementation file.
- Be sure to follow whatever rules may be given for inserting the
necessary comments into your source code to identify correctly any
submission for evaluation. This may require putting much of your
commenting in a form required by some kind of external
documentation-generation system, such as Doxygen. If so, the details
will be given elsewhere.
Program Structure
-
When your entire program is contained in a single source code file,
that file should have the structure obtained by placing the
following code sections in the given order:
- Comments indicating the name of the file, purpose of the code
in that file, and anything else that may be required in these
initial comments for the particular occasion
- The necessary "imports" for the required header files (Also,
each group of includes that requires a using declaration or one
or more using statements, must be followed by the necessary using
declarations/statements.)
- When you have a multi-file program, each file should follow the
above guidelines, except of course that only one file will have a
main
function in it. The contents of any one file should
form a logical grouping of some kind within the context of the
overall program.
Maximum Length of Source Code Lines
Choose a maximum length for the lines of text in your source code file
in order to ensure that your lines of code do not "wrap" in an
unsightly fashion, either on the screen or on the printed page. It is
your responsibility to choose and insert good line breaks to prevent
this from happening, while at the same time ensuring that your code
remains as readable as possible. A maximum line length value between 72
and 76 characters is recommended, but whatever value you choose must be
stricly less than 80.
No TAB Characters in Source Code
Your source code must not contain any TAB characters. Most
modern editors have an easy way to ensure that this requirement is met.
You should find out what the necessary procedure is in your case, and
use it consistently. Having only spaces in your source code file means
that its indentation and aligment will remain the same, no matter where
that file may be printed.
Miscellaneous
- Put each program statement on a separate line, unless you can
make a very good argument to explain why you didn't. One such
argument might be that you used a one-line-but-multi-statement Java
"idiom" of some kind.
- Use named constants whenever appropriate.
- Always protect header files, and other files to be included,
against multiple inclusion.
Part B: User Interface and Program Output
Self-identification and programmer identification
Each program should identify both itself and its author(s) when it
runs. Exactly how this is to be done for submissions for evaluation
will be specified by your instructor.
Self-description and/or on-line help
Each program should at a minimum describe briefly what it does when it
runs. Such information may appear automatically when the program runs,
in simple cases. In more complex programs this information and much
else may be available via an on-line help system of some kind. Once
again, for submissions for evaluation, your instructor will provide
details on the kind of information to be displayed.
Prompting for input
Every program must prompt properly for all input that it requires.
Echoing input in the output
It is always good programming style to have a program echo its input
somewhere in its output, so the user can verify that what was thought
to be entered was in fact entered.
Organization and formatting of output
All output must be organized, aligned, and formatted for maximum
readability by the user.
Spelling and punctuation
The appearance of misspellings and bad punctuation in program output is
not only bad style, but is bound to raise questions in the mind of a
user about the care taken in other aspects of program development.