CS 2110 Spring 2011 Code Style Guidelines

Code style will be a portion of the grade on CS 2110 assignments. Please familiarize yourself with these guidelines, some of which are standard Java practice, while others are intended to develop good coding habits.

When in doubt, choose the alternative that makes the code most obviously correct: "There are two ways of constructing a software design. One way is to make it so simple that there are obviously no deficiencies. And the other way is to make it so complicated that there are no obvious deficiencies." - C.A.R. Hoare.

1. Leave Good Comments

Remember that you're writing code for an audience. Other people are going to be reading it, trying to understand what you're doing, and you should make it as easy as possible for them to do this. This means: Leave good comments. Good comments explain the logic of what's going on. Don't make your audience strain just to figure out what your code is supposed to do. At the same time, though, it is possible to leave too many comments. Statements like "i++;" are self-explanatory. The comments should be at a higher level of abstraction than the code: Don't just translate Java into English. Summarize.

2. Naming Conventions

In CS 2110, we will adhere to Java's naming conventions. These may seem arbitrary and bizarre if you're not used to them. Nonetheless, conforming to aesthetic standards of coding is something you'll need to do in any just about any software development workplace*, so it's good practice.

Java class, field, method, and variable names are written in CamelCase. Words are smashed together, and the first letter of each word capitalized. There is no underscore or other word separator. Class and interface names begin with a capital letter:

interface AqueousHabitat { ... } class FishBowl implements AqueousHabitat { ... }

Fields and methods begin with a lowercase letter:

private List<Fish> inhabitants; public int countFish() { ... }

Additionally, method names should be verbs describing what the methods do. Sun's JDK is sometimes inconsistent about this, though, so we'll be lenient.

public Fish getNextFish() { ... } // Good public Fish nextFish() { ... } // Bad

There is one exception to CamelCase variable names: Constants. Here, we will stick to a convention borrowed from C. Constants are in all-caps with words separated by underscores. Constants should also have the keyword final, and are usually static:

public static final double SPEED_OF_LIGHT = 299792458; // in m/s

Variable names should give the reader some hint about what the variable is used for. There are a few exceptions, like i and j as counter variables or e as the Throwable in a catch block, but speaking generally variable names should be descriptive.

// These are probably bad variable names. for (int steve = 0; steve < foo; steve++) { if (flowerPot[steve] > umbrella) throw new Wombat(); } // (unless the program is actually about Steve, flower pots, // and umbrellas)

If you find yourself wanting to name a variable something likevar, data, ortemp, stop and ask, "What does this variable really mean?" Using a meaningless name gives up a chance to further document your code.

It may feel like you're a cool hacker if every variable in your program has a short, unreadable name. However, this can become a nightmare for yourself or others to read:

// What's going on here? for (xds = mid; xds < ids; xds++) { odp.ftgIdle(pwsz, xds, hmapi); } // This is a little clearer for (currentID = minID; currentID < maxID; currentID++) { database.save(username, currentID, userSettings); }

3. Package Names

Java classes are always declared within the scope of a package. Other languages call these namespaces. The goal is to prevent accidental namespace collisions, something especially important this course, where the graders will be dealing with two hundred classes with the same name. In CS 2110, we ask that your homework assignments use specific packages:

  1. cs2110.netId.assignmentN
  2. cs2110.netId.sectionN (for section assignments)

For example, cs2110.foo999.assignment3

You're welcome to create any sub-packages you find helpful. As with variable names, package names should be meaningful.

4. Code Organization

As a general rule of thumb, if a single method is getting beyond a few pages of code, you might want to consider lifting some of that method's functionality into other methods. Similarly, if you find yourself pasting the exact same chunk of code into multiple places, you might want to create a single method that does the job. The Refactor contextual menu in Eclipse can help with this.

However, it is possible to go overboard with this. Even if two blocks of code are structurally similar, don't merge them into the same method if they do different things. Each method should have only one purpose. Names like saveOrLoadAnimal() are a clue that you really need two methods:saveAnimal() and loadAnimal().

5. Formatting

Be consistent with your code formatting, and indent code blocks. Don't write huge lines of code that wrap around the screen. Eclipse can help with this: Try the Format option under the Source menu (Shift+Ctrl F), and the Correct Indentation feature (Ctrl I).

6. Avoid Deprecated Patterns

Depending on where you learned Java, you may have picked up some out-dated habits. Habits that are going to raise eyebrows at a job interview. In CS 2110, our goal is to make you into the best programmers we can, and that means using certain new syntax and features added in Java 1.5, and avoiding patterns used in earlier versions of Java or carried over from other languages like C.

6.1 Use Type Parameters

When using collections like those derived from List, Map, and Set, use appropriate type parameters:

List<Fish> dinnerMenu = new LinkedList<Fish>(); // Good List dinnerMenu = new LinkedList(); // Bad

We'll cover generics later in class, so if you don't know all the theory behind type parameters, that's okay for now. Just use them.

Eclipse will give warnings if these type parameters are ignored.

6.2 Java 1.5 For-Loop Syntax

When you're writing a for loop that iterates over an array or an Iterable (such as ArrayList, etc), please use the new for-loop syntax when possible:

private List<Fish> inhabitants; // Good (Java 1.5 style) public void feedFish(int foodAmount) { for (Fish fish : inhabitants) { fish.feed(foodAmount); } // Bad (Java 1.1 style) public void feedFish(int foodAmount) { Iterator i = inhabitants.iterator(); while (i.hasNext()) { Fish fish = (Fish) i.next();


} }

There are cases when you might want to explicitly create an iterator, such as if you want to remove elementsin situ. That's all right, but leave comments explaining why you've decided not to use Java 1.5's for-loop syntax.

6.3 Avoid Integer Indexing

Similarly, don't use an integer counter variable to index into an array or List if you really just want to iterate:

// Bad (C style) public void feedFish(int foodAmount) { for (int i = 0; i < inhabitants.size(); i++) { inhabitants.get(i).feed(foodAmount);

} }

Of course, there are exceptions to this rule. Numerical algorithms, such as factoring a matrix, will certainly want to use integer indices for arrays.

7. Public/Private Access Levels

Java defines four levels of access: Public, private, protected, and default (i.e., no modifier specified). Your methods and fields should be private unless there is a reason for them to be otherwise. However, when grading, we will not be pedantic about the nuances between public and protected. Please don't use default unless you leave a comment justifying it.

8. Code To Interfaces Instead Of Implementations

In most cases, client code doesn't care about the implementation of the list - it just wants to know what operations are supported. Specifying a linked list is needlessly providing a detail that makes future changes harder.

// Good List<String> users = new LinkedList<String>(); // Bad LinkedList<String> users = new LinkedList<String>();

9. Always Use Brackets For Control Flow Structures

The following is just begging for a bug:

if (flag) validate();

Can you spot the bug here?

if (flag) validate(); update();

Always use brackets:

if (flag) { validate(); update(); }

(This applies to other structures as well, like else while, for, etc.)

It is also recommended to put a space between the keyword and the parenthesis, to differentiate control structures from method calls:

// Good if (username == null) { loadUser(username); } // Less good if(username == null) { loadUser(username); }

9. Crediting Sources

9.1 Coauthors

For group projects, be sure to credit co-authors in your README assignment write-up. For all assignments, please credit any classmates or friends that you talked with ("Talked with Thorsten, he showed me the right way to use a HashMap"). For non-group projects, other students should not help you with your assignments, but helping each other with general class material is acceptable. You don't need to credit TAs or consultants for their help.

9.1 Crediting the Internet

In general, it is acceptable to copy short snippets of code from the internet, as long as they only serve a peripheral function in your assignment. But you have to credit the source. Include a URL and the author's name (if known) in the comments.