CS 307 and 305J Coding Standards
These standards are derived from the Java Coding Standards. Writing code that is easy for others to read and modify is an important part of programming. Learning to program does not just mean getting the program to work. The program should be easy to read and understand. It should be decomposed as the problem itself is decomposed and solved. In the "real world" and on the later assignments you simply will not be able to write all the code at once. You will have to code in pieces and if you do not use good style you will spend a large amount of time asking yourself, "what was I trying to do here?"
The following are the rules of style I can explain easily. There are others I cannot, such as a good decomposition or an elegant algorithm. In some cases I cannot define bad style, but I know it when I see it. Please remember that half of your assignment grade is based on the style of your program, which means following the standards below, but most importantly, making the program easy to understand.
Length of methods. In order to help keep methods easy to
understand they should be no more than 20 lines of code. This does not
include whitespace, closing braces, or comments. If a method gets much
longer than 20 lines of code then it is either the algorithm is too
convoluted or the method is trying too to do to much. You
should search for a more elegant solution to the problem or break the method
up into two or more sub methods.
Length of classes. Classes should provide a definite
service. You do not want to be creating Swiss Army Knife classes that try to
do everything. It is much better to have several classes each of which
provides a definite service. In general classes should be no more than 3
pages long. If the class is more than 3 pages long that is an indication the
class may be trying to do too much. This is more of an educational guideline
than an industrial one. If you look at classes from the java standard
library you will notice they are long, but realize that much of this is
comments.
Complexity of algorithms. There are many, many ways to solve
problems via programs. Try to find the simplest solution you can. If your
algorithm is extremely complex and hard to follow, it probably means you
went with the first solution you thought of instead of trying different
approaches and using the simplest. Code and algorithms that are poorly
thought out tend to be very complex, hard to understand, and hard to
implement in code. You should strive to make your
solutions simple and easy to understand. This means you should be willing to
seek help if you think your solution is too complex and to consider
alternatives instead of sticking with your initial solution no matter how
convoluted it becomes.
Using classes from the Java standard library. On many of the
assignments I will be very clear about what you can or cannot use from the
Java standard library. The reason certain classes or methods are sometimes
restricted is because I want you to solve a particular problem that the
library makes trivial. Remember, the primary goal of this class is not to
learn the ins and outs of the Java standard library; it is to help you
become a better programmer by having you solve challenging problems for
yourself. Another skill I hope you learn in this class is being able to use
pre existing code. So their will assignments where I provide you with
classes or you are free to use one or more classes from the Java standard
library and you must read the documentation for that class in order
to use it.
Using code from other sources. In general you should create
and implement the algorithms required for the assignments. If you use an
algorithm from another source I expect you to credit and cite the source of
the algorithm. There will be times when you can use source code from other
sources. (lecture, textbook, etc.) If you do you must cite the source of the
code. In general the algorithms you create and the code you implement should
be your own. The purpose of this class is to learn how to think and solve
problems. It is not to learn how to search the web for code.
Style Guidelines for Source Code:
Object variable and primitive variable names will be
meaningful. The name of variable shall help describe its purpose in
the program and / or what it is an abstraction of from the real world. Of
course you can go to far:
numberOfMembersOnTheOlympicTeam - too long
n - too short
numMembers - just right
And of course some short variable names are used so much they have a clear
meaning even though they are very short
i, j, k - loop counters
n, len, length - length of array or String
x, y - Cartesian coordinates
Variable and method names shall be lower case except for
internal words whose first letter shall be capitalized. No underscore
or $ characters will be included in variable and method names.
Constants shall be declared and used for all values in your
program that model real world constants or for numbers that are not to
change in the program. The only exceptions are when using the numbers
-1, 0, 1, and 2.
Constant names shall be meaningful and help describe what
the constant represents. The name shall be all capital letters with
underscore characters used to separate internal words. A good constant
name would be DAYS_PER_YEAR. A bad constant name would be
THREE_HUNDRED_SIXTY_FIVE.
Class names shall start with an uppercase letter and
internal words shall start with a capital. All other letters shall be
lowercase. For example ClassName
There shall be a space surrounding all
binary operators.
// bad
int x=12;
int y=x+5;
// good
int x = 12;
int y = x + 5;
Indent
style. Oh what people get worked up about. Braces should be lined up vertically.
This includes braces for a class, a method, and braces that contain a code
block for if/else statements. (The only time braces may be lined horizontally are for methods that contain
a single line of code). The Hacker's Dictionary refers to this as the "`Allman
style' -- Named for Eric Allman, a Berkeley hacker who wrote a lot of the
BSD utilities in it (it is sometimes called `BSD style'). Resembles normal
indent style in Pascal and Algol. It is the only style other than K&R in
widespread use among Java programmers. Basic indent per level shown here is
eight spaces, but four (or sometimes three) spaces are generally preferred
by C++ and Java programmers." (from the Hackers Dictionary)
if( <condition> )
{ statement1;
statement2;
statement3;
...
statementN;
}
If you like feel the need to be different or express your individuality or
simply like this style, you may use the "`K&R style' -- Named after
Kernighan & Ritchie, because the examples in K&R
are formatted this way. Also called `kernel style' because the Unix kernel
is written in it, and the `One True Brace Style' (abbrev. 1TBS) by its
partisans. In C code, the body is typically indented by eight spaces (or one
tab) per level, as shown here. Four spaces are occasionally seen in C, but
in C++ and Java four tends to be the rule rather than the exception."
(from the Hackers Dictionary)
if( <condition> ) {
statement1;
statement2;
statement3;
...
statementN;
}
Statements in the same program block shall lined up
vertically. To ensure this is correct no matter what editor is being
used to view your code, use either all tabs or all spaces. Mixing tabs
and spaces may cause the code to look good in your editor, but it may look
bad in another editor if the tabs are set differently.
Code shall be indented to show the code block it belongs
to. For example other than the class header and class braces, all code
in a class shall be indented one tab. So the header for the main
method is indented one tab, as well as the braces for the main method.
The program statements and code inside the main method shall be indented two
tabs. Code shall be indented to show the code block it belongs
to. For example other than the class header and class braces, all code
in a class shall be indented one tab. So the header for the main
method is indented one tab, as well as the braces for the main method.
The program statements and code inside the main method shall be indented two
tabs.
Code in classes shall be in the following order:
Part of Class/Interface Declaration | Notes | |
0 | import statements | |
1 | Class/interface documentation comment (/**...*/ ) |
See "Documentation Comments" on page 9 for information on what should be in this comment. (Note page 9 refers to a page from the Sun Java Coding Standards, not the required textbook of the class. Click on the link on the website to see the information on what to include in comments.) |
2 | class or interface
statement |
|
3 | Class/interface implementation comment
(/*...*/ ), if necessary |
This comment should contain any class-wide or interface-wide information that wasn't appropriate for the class/interface documentation comment. |
4 | Class (static ) variables |
First the public class
variables, then the protected , then package level (no
access modifier), and then the private . |
5 | Instance variables | First public , then protected ,
then package level (no access modifier), and then private . |
6 | Constructors | |
7 | Methods | These methods should be grouped by functionality rather than by scope or accessibility. For example, a private class method can be in between two public instance methods. The goal is to make reading and understanding the code easier. |
All private instance variables should be prefixed
with my as in myBox or myDirection. Alternatively you
can use the this keyword to refer to instance variables: Examples:
private int iMyCount:
private int iCount:
// in some method
{ iMyCount++;
this.iCount++;
}
All private static variables will start with the prefix our
as in ourRandomNumGenerator.
private instance variables that are primitives should start
with a prefix indicating the type of primitive:
y: byte
s: short
i: int
l: long
f: float
d; double
b: boolean
c: char
so if myDirection is a private instance variable with type integer the
correct name is iMyDirection. Note, this
naming convention applies only to primitives, not to objects. So an instance
variable that is a String and represents a first name would simply be myFirstName
not sMyFirstName.
Leave at least one blank line after every method
Each class and method shall have a comment explaining what
it does. At a minimum comments for methods will list pre and post
conditions.
The things that must be true when calling the method and the things that
will be true when the method is done assuming the preconditions were met.
The pre and post conditions should be stated in mathematical terms if
possible and in
terms of the public interface of the class whenever possible.
Booleans: Booleans are great and they add readability to a
program, but it helps to use them correctly. A lot of beginning programmers
use booleans in very awkward ways:
if (flag == true) // GACK!!
if (flag) // much better
if( matches > 0 )
found = true;
else
found = false; // DOUBLE GACK!!!
found = ( matches > 0 ); // so nice
if( hadError == false)
return true;
else
return false; // DOUBLE DOG GACK!!
return !hadError; // a thing of beauty
Complex boolean expressions. If you have a complex boolean
expression it may be useful to encapsulate that in a separate boolean
method. Example:
// complex boolean expression embedded in another complex method
// is year a leap year?
boolean isLeapYear = year > 0 &&( (year % 4 == 0 &&
year % 100 != 0) || year % 400 = 0 );
//better to put this condition in a function / method
private boolean isLeapYear(int year)
{ return year > 0 &&( (year % 4 == 0
&& year % 100 != 0) || year % 400 = 0 );
}
//elsewhere
boolean leapYear = isLeapYear(year);