Java checkstyle

Abbreviated Style Guide

This document covers basic style guidelines that the 15-214 course staff expects you to follow. It contains links and tips from the official Oracle coding conventions (if you have time, reading through that would be very beneficial).

Please note that these tips are compiled from common errors with homework submissions and (with the exception of the 'Additional Style Tips' section) not following these rules may result in losing points.

Table of Contents

  • Naming Conventions
    • Variables Names
  • Magic Numbers
  • Dead Code
  • Access Modifiers
  • Documentation & Comments
  • Additional Style Tips
    • Whitespace
    • String Concatenation
    • Boolean Returns
    • if... else Blocks

Naming Conventions

Source: 9 - Naming Conventions

Type Rules Examples
Packages All lowercase, ASCII letters.* edu.cmu.cs.cs214.rec01
Classes/Interfaces CamelCase with the first letter capitalized. class SpecialTile
Methods camelCase with the first letter lowercase. startGame();
Variables camelCase with the first letter lowercase. Image background;
Constants All UPPERCASE with words separated by underscores. private static final int MAX_ANSWER = 41;

* Often named after the top-level domain name of the company who owns/wrote the code.

Variables Names

Pick variable names which succinctly describe what they're used for. Here are some tips to keep in mind when you're deciding what names to use.

  • Avoid single-letter variable names.

If you call your variables a, b, c, then it will be impossible to search for instances of them using a simple text editor. Further, nobody will be able to guess what they are for.

Only use single-letter variable names when they're for 'temporary' variables (like in loops).

  • Abbreviate only when necessary.

Sure u cn rd ths sntnce but do you want to? Use abbreviations when they can't be confused with something else. For example, desc could mean "descending" or "description," but abbreviations like obj or img are not ambiguous since they always mean 'object' and 'image' respectively.

Magic Numbers

A magic number is a hardcoded value (string, int, double, etc.) used in code. For example:

for (int i = 0; i < 5; i++) {
    // Use card at position i.
}

The 5 above is fairly ambiguous since we don't know why a card's position is limited by 5. To clarify this, declare your number in a static final constant value.

private static final int HAND_SIZE = 5;

...

for (int i = 0; i < HAND_SIZE; i++) {
    // Use card at position i.
}

There are two main reasons you want to declare a constant instead of using magic numbers.

  • Values are easier to change with constants. Let's say you used the value 100 for both the hand size and the number of types of cards, and then you decide you want to use 50 for the hand size instead. With constants, it's a simple matter to change the value of the constant. With magic numbers, you'll have to find all the places where 100 is used, and try to determine whether that 100 is the hand size or something else. There is large potential for error here.

  • Code is easier to read. As in the example above, it is easier to understand why you, the programmer, chose 5 when it's in a constant named HAND_SIZE.

Dead Code

There are two types of dead code:

  • Commented-out code clutters up your submissions and looks ugly. Please destroy your commented-out System.out.println statements since your code should be finalized by the time you turn it in.

  • Code that is never used which includes never-used classes and methods and return statements that are never reached. We are more strict about never-used classes since it becomes confusing which classes are important or not.

Access Modifiers

Instance variables should be private with public getters and/or setters, if the variable needs to be accessed outside the class.

See Item 13: Minimize the accessibility of classes and members — Effective Java, 2nd Ed. by Joshua Bloch

Documentation & Comments

Source: 5 - Comments

There are two types of comments:

  • Javadoc (Documentation) comments in Javadoc format which don't contain implementation details and instead describe pure functionality of the class/method/interfaces.

  • Implementation comments which clarify complex code in the implementation.

Comments can make your code easier to understand by clarifying difficult to understand sections, but too many comments can have the opposite effect. Try not to comment things that are "obvious" from the code, such as:

//constant that describes how big the array should be
private static final int ARRAY_SIZE = 15;

...

//initializes the array to the size of ARRAY_SIZE
int[] myArray = new int[ARRAY_SIZE];

//loops through the array
for (int i = 0; i < myArray.length; i++) {
    ...
}

Javadoc Comments

You should add Javadoc comments to public classes/methods.* Javadoc comments begin with two asterisks (e.g. /** ... */) and go immediately before the class or method declaration.

/**
 * Returns an Image object that can then be painted on the screen. 
 * The url argument must specify an absolute {@link URL}. The name
 * argument is a specifier that is relative to the url argument.
 *
 * @param  url  an absolute URL giving the base location of the image
 * @param  name the location of the image, relative to the url argument
 * @return      the image at the specified URL
 * @see         Image
 */
public Image getImage(URL url, String name) {

The first sentence is a summary of the class/method and the following sentences add additional detail. You are not required to add Javadoc comments to trivial getters/setters (e.g. getName, setName, etc.).

For more information, see the Oracle Javadoc guide.

* Okay, you can add Javadoc comments to private methods too, but it is not required.

Implementation Comments

Add these comments to clarify particularly tricky code. This involves describing steps of complex algorithms or non-intuitive logic.

Generally, well-written code is self-documenting (when written with clear variables or simple steps) but when a method becomes long and unruly, it is very helpful to you (and your grader!) to add comments indicating what overall task is being accomplished in the following code block.

Java has two comment styles:

/* Multi-line comments can be written with the leading
 * slash-asterisk. Note this starts with ONE asterisk while
 * Javadoc comment start with TWO.
 */
// This style is usually reserved for single-line comments.
// ...Usually.

Additional Style Tips

The style tips in this section are not required. They are just small programming tips that help keep your code readable and/or efficient.

Whitespace

Source: 4 - Indentation

Tabs, spaces (4, 2, 8)... we don't really care. As long as it's consistent.

One tip, however, is that you should set your Eclipse environment to display the tab width as 8 spaces. This is because Github displays tabs as 8 spaces, and you may find that if you are dependent on a 4 space tab for alignment, then it will look different online.

This is how you can set your tab size:

  • Eclipse → Preferences...
  • Java → Code Style → Formatter
  • Create a new profile or edit an existing one
  • Set Tab size to 8

Pro Tip: Once you set your whitespace settings, you can tell Eclipse to auto-format your code using CTRL + SHIFT + F.

String Concatenation

Beware of the += operator on Strings. When two Strings are concatenated using the + or += operator, an entirely new String is created. As a result, concatenation of Strings in Java can result in poor performance if you aren’t careful, especially when done inside of loops.

// Creates a new String each time through the loop. O(N^2) performance.
String result = "";
for (int i = 0; i < num; i++) {
    result += "aoeu";
}

To achieve better performance, use a java.lang.StringBuilder instead. StringBuilders allocate a large char[] internally and perform String concatenation in-place.

// Performs String concatenation in place. O(N) performance.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < num; i++) {
    sb.append("aoeu");
}
String result = sb.toString();

Boolean Returns

Unlike in C (where booleans are traditionally represented as integer flags), booleans are given their own primitive type in Java. Thus, you can (and should) return a boolean to indicate success on a method rather than returning and parsing an integer.

if... else Blocks

Source: 7 - Statements

We recommend that you always add braces to your if-else blocks. Why? It keeps your code blocks clearly separated and is less prone to oversights due to indentation.

if (condition)
    count++;
    roads = max - count; // looks like it's part of the if block but isn't!

With the block, this error is easily rectified.

if (condition) {
    count++;
    roads = max - count;
}

你可能感兴趣的:(Java checkstyle)