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

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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,717评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,501评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,311评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,417评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,500评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,538评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,557评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,310评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,759评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,065评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,233评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,909评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,548评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,172评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,420评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,103评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,098评论 2 352

推荐阅读更多精彩内容