or... what it should look like when you hand it in
Employing good and consistent coding conventions is very important. It helps make the programs readable and improves productivity (not to mention the fact that it is very helpful for your TAs). For these reasons, it is in your best interest that all assignments meet the standards described below. Following the proper style and conventions listed in this document is usually worth about 10 points in all assignments.
Don't worry if you are not sure what the terms below mean; you will soon get to know them thoroughly. After reading this document, make sure you keep it by your side when you code to answer your questions about format and style.
Names
Using the following naming conventions will keep code ambiguities to a minimum.
-
Package Names
Example:
ToyStoryorswing -
Packages are groups of classes that make up an application. The name of the package will usually be the name of the program you are writing. Package names can be either all lowercase or start with a capital letter with all subsequent word starting with a capital letter.
-
Class Names
Examples:
SlinkyDog -
Classes should be named using nouns which describe what the class models. Class names should always begin with a capital letter. All new words within the name should start with a capital letter.
-
Method Names
Examples:
fly()orgoToTheStore() -
These usually perform some kind of action and/or return a value, so we use verbs to indicate what they do. Method names should always begin with a lowercase letter, and all new words within the name should start with a capital letter.
-
Accessor Methods
Example:
getToyOwner() -
Methods that retrieve or send information from or to an instance variable are often called accessor methods. Accessors that retrieve the value of an instance are named after the variable they are going to retrieve and prefixed with the word "get".
-
Mutator Methods
Example:
setToyOwner(String ownerName) -
A method whose purpose is to change the value of one or more instance variables is named after the variable it is going to change and prefixed with the word "set". These methods are sometimes called mutators. Most of the time mutators take the new value of the variable they are changing as a parameter.
-
Instance and Local Variables
Examples:
_numGreenArmyMenandnumToys -
Instance and local variables store state information about the object. Their names should be comprised of nouns describing the information they store. A variable name such as
numSodasis better thanstuff. All instance and local variable names begin with a lowercase letter and each new word begins with a capital letter. In addition, all instance variables should be prefaced by an underscore '_'. This allows you to easily differentiate between instance and local variables, which is very handy.Note: You should generally avoid using one letter variable names, as they are not descriptive and will make your code more difficult to read. The only exceptions are: if the usage agrees with an established naming convention, such as the use of
iorjfor a simple loop index which is not used in the body of the loop. Also,xandyfor coordinates are acceptable. Don't feel constrained by traditional naming conventions, though. You can always make up some more descriptive names for loop variables, especially with multiple and nested loops. -
Constants
Example:
DORYS_IQ -
Constants should have names consisting of nouns describing their content. In Java, constants are just instance variables of classes. You will learn how to make a constant in the first few weeks of class. In order to distinguish them from just plain instance variables, we use only capital letters in their names and separate different words with underscores.
-
Using Predefined Classes
Example:
cs015.prj.LiteBrite.Palette -
When you use predefined classes (like classes from
cs015.prj) we prefer that you do not import the whole package but prefix the classes with package names instead (use scoping). This should minimize name clashes in your code. (If you don't know what this means, don't worry about it.)
Indentation and Skipping Lines
Java consists of nested blocks of code. For example if statements
can be contained in for loops, which are contained in methods,
which are contained in classes. One way to show this nesting is by indentation.
This allows the person reading your code to easily see the major sections of
code and main flow-of-control in methods. You'll notice that Emacs does most of
the indentation for you. As you edit your program, however, you may need to
reindent your code. You can get Emacs to reindent a line of code by placing the
cursor at the beginning of that line and pressing tab. If Emacs does not indent
the line correctly, there is probably a syntax error in your code, like a
missing brace or semicolon. The following is the CS15's indentation
conventions.
- Nested code should be indented.
-
Claw theClaw = new Claw(); for (int i=0; i < theClaw.getNumAliens(); i++) { Alien currentAlien = theClaw.getAlien(i); if (currentAlien.hasBeenChosen()) { currentAlien.sayFarewell(); currentAlien.goOffToABetterPlace(); } } - Braces
-
Braces indicate the beginning and end of blocks of code. Class definitions, methods, and loops all have braces around them. The opening brace should be on the same line as the beginning of the block; i.e., if the braces are around the class, the opening brace is on the same line as the name of the class; if the braces are around the method, the opening brace is on the same line as the name of the method, etc. The closing brace should be aligned with the beginning of the line with the opening brace. (Again, Emacs will do this for you automatically.)
public class Alien { private Eye _leftEye, _centerEye, _rightEye; public void blink() { _leftEye.blink(); _centerEye.blink(); _rightEye.blink(); } } - Skipping Lines
-
Another way of making major sections of your code easy to see is by skipping lines. You should skip about two lines between methods. You should also separate logical chunks of code within a method with one or two blank lines.
Internal Documentation (a.k.a. Comments)
"Internal documentation" simply refers to the comments in your program. No matter how simple a program is to its author, it is almost always confusing to another person reading it (i.e, the TAs who will be grading your programs). Comment well, and you will have a happy TA. Comment poorly, and the TA will have trouble understanding what you are doing (and you may not get the benefit of the doubt).
There are two ways to make a comment in Java.
Comments that only span one line are indicated by a double slash (//).
Example:
// This is a one line comment
This style of comments is useful when you want to add a comment to a line that already has code on it.
Example:
if (owner == "Andy") { // Check to see if the toy is owned by Andy
Comments that span several lines are enclosed by /* */.
Example:
/* Comments that are several lines long must be enclosed in special symbols. */
In CS15, we like to use a variation on this type of comment.
Example:
/** * Comments that are several lines long * must be enclosed in special symbols. */
This style of comments, included right before classes and methods, allows a
program called "javadoc", to automatically generate documentation for your
code. The documentation would look very similar to the Java and cs015 packages
documentation available off of the CS15 homepage. You don't need to worry about
this now, but if you are interested in creating a reusable, distributable, Java
package, it's a good idea to use the special, javadoc tags. Type "man
javadoc " in a shell for more information.
Comments are used for adding information to your code. Your comments should not just repeat the code that you have written, as such comments are useless. Comments should be added whenever an explanation or clarification is needed for some section or line of code, such as a difficult sequence of commands, an unusual or atypical design pattern, or a very brief synopsis of what a particular method call might do or return.
Comment as you go along, do not leave all your commenting until the end of the project. Commenting done later takes more time because you have to remember or figure out what the code is doing instead of just writing down what you are already thinking about.
- Header Comments
-
Header comments describe methods and classes. They consist of a block of information placed before the code they explain. Use multiline commenting style (
/** */) for header comments. You should describe each class and its design in the header comment. Since you use one file for each class, remember to put your login name and your name at the top of each file.Every method should have a header which contains a comment describing its purpose, how it achieves its purpose, and a list of variables passed to and/or modified by the method. If the method returns a value, the importance of this value should be described in the header as well.
Bad Example of a Method Header:
/** * This method adds a graphic. */ public void addGraphic(ShapeInterface s) { ... }Good Example of a Method Header:
/** * This method adds an object which implements the ShapeInterface * to the GraphicsCollection. This will cause this shape to be * displayed the next time the paintAllGraphics() method is * called (by calling repaint().) */ public void addGraphic(ShapeInterface s) { ... } - Glossary Comments
-
Glossary comments explain the purpose of each constant and variable, and should only appear when it is unclear why a certain variable is needed. They appear to the right of the identifier they describe. If the comment does not fit to the right of the identifier, it should be on the line immediately above the identifier. In a list of identifiers, glossaries should be left or right aligned for easier reading. Use
//commenting style for glossaries.public class BuzzLightyear { private Wings _wings; //Buzz needs wings for rescuing planes public void fly() { int flightSpeed; // speed at which Buzz will fly Direction direction; // direction of Buzz's flight ... } } - Inline Comments
-
Inline comments appear in code clarifying its workings. Use
//commenting style for inline comments.A closing brace that appears away from the matching open brace should be commented to say which block of code it is ending.
public void playWithToy(Toy newToy) { ... } // playWithToy(...)Lines should be commented to describe what they are doing. Note that this comment should not just repeat what the Java code does, but should elaborate on the code. This should be done for every section and logical chunk of code.
_time++; // add one to time<- useless _time++; // update clock to current hour<- useful
Sample Program
Here is a sample program complete with examples of good commenting practice.
Read it over to get a good idea of what ought to be commented, and what
shouldn't, and what should be contained in the comments when they are needed.
(Note: the character "@" as it appears in the header comments has special
meaning to the program javadoc that is used to generate program
documentation. This isn't something you'll need to worry about.)
package SnowPerson;
/**
* This class models a SnowPerson's head. It contains references to
* a face shape, two eyes, a nose, a mouth, and a hat because each of those
* things are part of a head, and should be a part of every SnowHead.
* The eyes and the nose of the SnowHead are special, because they are
* able to animate. The SnowPerson is able to make the eyes and mouth
* animate using a special method called animate().
*
* @version Thu Jul 11 18:04:42 2002
* @author ng
*/
public class SnowHead {
/**
* The following instance variables are all self-explanatory, so
* glossary comments are unnecessary. (Note that this is just for
* teaching purposes; this comment would not appear in a program!)
*/
private cs015.prj.SnowPerson.SquareEyes _eyes;
private cs015.prj.SnowPerson.SquareNose _nose;
private cs015.prj.SnowPerson.CoalMouth _mouth;
private cs015.prj.SnowPerson.TopHat _hat;
/**
* This is needed so the face parts will appear to be inside the
* shape of a face, and not just float in the air
*/
private cs015.prj.SnowPerson.SnowFace _head;
/**
* This is a method comment for the constructor of the SnowHead
* class. Since the SnowPerson contains all its face parts, they
* are instantiated in the constructor.
*/
public SnowHead() {
/**
* Instantiate head first, so it will appear beneath the face
* parts.
*/
_head = new cs015.prj.SnowPerson.SnowFace();
_eyes = new cs015.prj.SnowPerson.SquareEyes();
_nose = new cs015.prj.SnowPerson.SquareNose();
_mouth = new cs015.prj.SnowPerson.CoalMouth();
_hat = new cs015.prj.SnowPerson.TopHat();
} // SnowHead()
/**
* This method starts the head's animation. It tells the eyes and the mouth
* to start animating, which will make the eyes blink and the mouth open and
* close.
*/
public void animate() {
_eyes.startAnimate();
_mouth.startAnimate();
} // animate()
} // class SnowHead
/**
* This class models the application. The application contains an instance
* of the head that it initializes and animates until the user quits
* the program. The SnowHead contains all the appropriate parts of a
* face, including special eyes and mouth which know how to animate on
* their own. There are no special patterns used in this program, but
* it does utilize encapsulation and the idea of containment- that is,
* a Snowhead contains eyes, nose, mouth, etc.
*
* @version Thu Jul 11 18:08:28 2002
* @author ng
*/
public class SnowPerson {
/**
* This instance variable represents a SnowPerson's head.
*/
private SnowHead _head;
/**
* This method starts the program. It initializes the Snowhead,
* and then starts its animation.
*/
public SnowPerson() {
_head = new SnowHead();
_head.animate(); // This will continue until the program quits.
} // SnowPerson()
} // class SnowPerson
