JAVA代码规范 联系客服

发布时间 : 星期日 文章JAVA代码规范更新完毕开始阅读2332996e58fafab069dc0229

第一篇 开发规范 错误!文档中没有指定样式的文字。

Chapter 第4章 . 注释

【示例】 if (foo > 1)

// Do a double-flip. ... }

else {

return false; // Explain why here. }

//if (bar > 1) { //

// // Do a triple-flip. // ... //}

//else {

// return false; //}

4.2 文档注释

更多的细节,参见\,包括使用文档注释标签(@return,@param,@see):

http://java.sun.com/products/jdk/javadoc/writingdoccomments.html

有关文档注释和javadoc,还可以参见javadoc主页: http://java.sun.com/products/jdk/javadoc/

【规则4-6】 文档注释应该用来注释每个类,接口或成员方法。这些注释应该刚好出现在声明之前。并且尽可能使用文档标签来准确进行注释。

【示例】 /**

* The Example class provides ...

*/

public class Example { ...

【示例】

/**

* What and why the member function does what it does

第13/30页

第一篇 开发规范 错误!文档中没有指定样式的文字。

Chapter 第4章 . 注释

* What a member function must be passed as parameters * What a member function returns * Known bugs

* Any exceptions that a member function throws * Visibility decisions

* How a member function changes the object * Include a history of any code changes

* Examples of how to invoke the member function if appropriate * Applicable pre-conditions and post-condition */

public someMethod(…..){ …. }

注意:文本文档不应当放在方法或构造器定义块的内部,这是因为Java把文档注释和其后的第一个声明相联系。

第14/30页

第一篇 开发规范 错误!文档中没有指定样式的文字。

Chapter 第5章 . 声明

第5章 声明

5.1 每行一个

【规定5-1】 每行只能书写一个声明,因为这有利于注释。 【示例】

int level; int size;

不推荐

// indentation level // size of table

int level, size;

int foo, fooarray[]; //WRONG!

【示例】 上面的例子中使用一个空格分隔类型和标示符。另一种方法是使用tab,如:

int level; // indentation level int size; // size of table

Object currentEntry; // currently selected table entry

5.2 初始化

【规则5-2】 试着在局部变量声明的时候进行初始化。如果不在变量声明的时候进行初始化,唯一的理由就是它的初始值首先依赖于一些计算。

5.3 位置

【规则5-3】 声明只放在代码块的开始部分。(一个代码块是指由括号\和\包围的代码。)不要等到变量使用时才声明它们。唯一的例外是在for循环语句中。

【示例】

void myMethod() {

int int1 = 0; // beginning of method block if (condition) {

第15/30页

第一篇 开发规范 错误!文档中没有指定样式的文字。

Chapter 第5章 . 声明

int int2 = 0; // beginning of \ ... } }

for (int i = 0; i < maxLoops; i++) { ... }

【规则5-4】 要避免局部变量的声明出现在比其更高的层次中。不要声明和内部代码块同名的变量

【示例】

避免

int count; ...

myMethod() {

if (condition) {

int count = 0; // AVOID! ... } ... }

5.4 类和接口的声明

【规则5-5】 当编码Java类和接口时,应当遵守下列格式化准则: ? 在方法名和开始参数列表的括号\(\之间没有空格 ? 开始的大括号\放在声明语句同一行的末尾

? 结尾的大括号\新起一行,并和相应的开始语句保持同样缩进,除非是

空语句,这时\应该紧跟在\之后 ? 各个方法用一个空行隔开 【示例】

class Sample extends Object {

int ivar1; int ivar2;

Sample(int i, int j) { ivar1 = i; ivar2 = j;

第16/30页