您的位置:首页 > 编程语言 > Java开发

Java代码编码规范(1)

2015-09-17 17:16 555 查看
Java代码编码规范

第一部分:Convention(编码约定)

1.右括号放在一行的开始

Noncompliant Code Example

if(condition) {

doSomething();}

Compliant Solution

if(condition) {

doSomething();

}

2.抽象类命名规范

抽象类命名以Abstract开头

abstract class MyClass { // Non-Compliant

}

class AbstractLikeClass { // Non-Compliant

}

abstract class AbstractClass { // Compliant

}

3.抽象类不应该仅仅含有抽象方法,如果是是这种情况使用接口实现。

//Noncompliant Code Sample

public abstract class Animal {

abstract void move();

abstract void feed();

}

public abstract class Color {

private int red = 0;

private int green = 0;

private int blue = 0;

public int getRed(){

return red;

}

}

//Compliant Solution

public interface Animal {

void move();

void feed();

}

public class Color {

private int red = 0;

private int green = 0;

private int blue = 0;

private Color (){

}

public int getRed() {

return red;

}

}

public abstract class Lamp {

private boolean switchLamp=false;

public abstract void glow();

public void flipSwitch() {

switchLamp = !switchLamp;

if (switchLamp) {

glow();

}

}

}

4.数组的标示符号[]应该放在类型的后边。

public int getVector()[] { /* … */ } // Non-Compliant

public int[] getVector() { /* … */ } // Compliant

public int[] getMatrix()[] { /* … */ } // Non-Compliant

public int[][] getMatrix() { /* … */ } // Compliant

5.类命名规范,首字母大写,并且只能是字母和数字的组合。

6.命名为xxxException的类应该继承至Exception或其子类。

7.右大括号和else,catch和finally应该在同一行。

public void myMethod() {

if(something) {

executeTask();

} else if (somethingElse) { // Compliant

doSomethingElse();

}

else { // Noncompliant

generateError();

}

try {

generateOrder();

} catch (Exception e) { // Compliant

log(e);

}

finally { // Noncompliant

closeConnection();

}

}

8.注释放在一行代码的上边,不要放在后边。

Noncompliant Code Example

int a1 = b + c; // This is a trailing comment that can be very very long

Compliant Solution

// This very long comment is better placed before the line of code

int a2 = b + c;

9.常量命名要大写字母和数字的组合。

10.在每个文件的头部必须包含copyright和license信息。

11.类Field的命名规范:首字母小写,字母和数字的组合。

12.每个文件底部增加一个空行。

13.接口命名规范,首字母大写,数字和字母的组合。

14.代码行的长度不要太长(120个字符)。

15.局部变量和方法参数的命名规范:数字和字符的组合,首字母小写。

16.Logger声明为private static final

原因:private保证不被其子类使用, static保证类级别的,不要每个实例创建一个,final保证一个类创建一次。

Noncompliant Code Example

public Logger logger = LoggerFactory.getLogger(Foo.class);

Compliant Solution

private static final Logger LOGGER = LoggerFactory.getLogger(Foo.class);

17.Long类型的变量初始化以“L”作为后缀。

long n = 10l; // Non-Compliant - easily confused with one zero one

should be refactored into:

long n = 10L; // Compliant

18.修饰符的声明顺序:

Annotations public protected private abstract static final transient volatile synchronized native strictfp

19.多个变量不要在一行声明

Noncompliant Code Example

class MyClass {

private int a, b;

public void method(){

int c; int d;

}

}

Compliant Solution

class MyClass {

private int a;

private int b;

public void method(){

int c;

int d;

}

}

20.包命名规范:小写,字母和数字的组合。

21.包下面需要包含一个package-info.java的文件。

/**

* This package has non null parameters and is documented.

**/

@ParametersAreNonnullByDefault

package org.foo.bar;

22.公开的常量和变量声明为public static final

23.公开的Api增加Javadoc注释

• Parameters, using @param parameterName.

• Method return values, using @return.

• Generic types, using @param

24.代码缩进一致。

25.每行一条语句,可读性更好。

Noncompliant Code Example

if(someCondition) doSomething();

Compliant Solution

if(someCondition) {

doSomething();

}

26.接口或类的成员变量定义顺序:变量 构造函数 其他方法



第二部分:PITFALL(陷阱)

1.indexOf 不要做正数校验

Noncompliant Code Example

String color = “blue”;

String name = “ishmael”;

List strings = new ArrayList();

strings.add(color);

strings.add(name);

if (strings.indexOf(color) > 0) { // Noncompliant

// …

}

if (name.indexOf(“ish”) > 0) { // Noncompliant

// …

}

if (name.indexOf(“hma”) > 2) { // Noncompliant

// …

}

Compliant Solution

String color = “blue”;

String name = “ishmael”;

List strings = new ArrayList();

strings.add(color);

strings.add(name);

if (strings.indexOf(color) > -1) {

// …

}

if (name.indexOf(“ish”) >= 0) {

// …

}

if (name.indexOf(“hma”) > -1) {

// …

}

2.不要显式的抛出 NullPointerException,对参数增加校验。

Noncompliant Code Sample

public void doSomething (String aString) throws NullPointerException

{}

Compliant Solution

public void doSomething (@NotNull String aString)

{}

3.private方法不要访问私有的静态变量(”private” methods that don’t access instance data should be “static” )

private methods that don't access instance data can be static to prevent any misunderstanding about the contract of the method.


Noncompliant Code Example

class Utilities {

private static String magicWord = “magic”;

private String getMagicWord() { // Noncompliant

return magicWord;

}

private void setMagicWord(String value) { // Noncompliant

magicWord = value;

}

}

Compliant Solution

class Utilities {

private static String magicWord = “magic”;

private static String getMagicWord() {

return magicWord;

}

private static void setMagicWord(String value) {

magicWord = value;

}

}

4.序列化的类增加序列化版本serialVersionUID字段

每一个序列化类都需要serialVersionUID字段,如果没有compiler会为计算一下为你提供一个。如果代码发生变化,serialVersionUID值也可能发生变化,会出现不能反序列化的错误。

Compliant Solution

public class Raspberry extends Fruit

implements Serializable {

private static final long serialVersionUID = 1;

private String variety;

public Raspberry(Season ripe, String variety) { …}

public void setVariety(String variety) {…}

public String getVarity() {…}

}

5.静态成员变量通过静态方式访问(通过实例访问也没什么坏处,容易让人误解)

Noncompliant Code Example

public class A {

public static int counter = 0;

}

public class B {

private A first = new A();

private A second = new A();

public void runUpTheCount() {

first.counter ++; // Noncompliant

second.counter ++; // Noncompliant. A.counter is now 2, which is perhaps contrary to expectations

}

}

Compliant Solution

public class A {

public static int counter = 0;

}

public class B {

private A first = new A();

private A second = new A();

public void runUpTheCount() {

A.counter ++; // Compliant

A.counter ++; // Compliant

}

}

(“StringBuilder” and “StringBuffer” should not be instantiated with a character。)

Noncompliant Code Example

StringBuffer foo = new StringBuffer(‘x’); //equivalent to StringBuffer foo = new StringBuffer(120);

Compliant Solution

StringBuffer foo = new StringBuffer(“x”);

7.不要在构造函数中启动线程

Noncompliant Code Example

public class MyClass {

Thread thread = null;

public MyClass(Runnable runnable) {

thread = new Thread(runnable);

thread.start(); // Noncompliant

}

}

8.引用类的时候尽量少用星号(wildcard)

Noncompliant Code Example

import java.sql.*; // Noncompliant

import java.util.*; // Noncompliant

private Date date; // Date class exists in java.sql and java.util. Which one is this?

Compliant Solution

import java.sql.Date;

import java.util.List;

import java.util.ArrayList;

private Date date;

9.非线程安全的对象不要做静态初始化

像Calendars,DateFormats,HttpGet 等都是非线程安全的

Noncompliant Code Example

public class MyClass {

static private SimpleDateFormat format = new SimpleDateFormat(“HH-mm-ss”); // Noncompliant

static private Calendar calendar = Calendar.getInstance(); // Noncompliant

Compliant Solution

public class MyClass {

private SimpleDateFormat format = new SimpleDateFormat(“HH-mm-ss”);

private Calendar calendar = Calendar.getInstance();

10.同时重写equals 和 hashCode 方法

首先两个对象相等(equal),那么这两个对象的hashCode一定一样;

其次如果两个对象不等(not equal),这两个对象的hashCode不要求必须不一样;

最后:为了提高hashtables的性能,最好让不同对象的hashCode不一致。

11.不要调用数组实例的toString和hashCode方法,返回的的结果是对象的Hash code值。

Noncompliant Code Example

public static void main( String[] args )

{

String argStr = args.toString(); // Noncompliant

int argHash = args.hashCode(); // Noncompliant

Compliant Solution

public static void main( String[] args )

{

String argStr = Arrays.toString(args);

int argHash = Arrays.hashCode(args);

12.非null判断用:object==null,而非:object.equals(null)

Noncompliant Code Example

if (variable.equals(null)) { /* … */ } // Noncompliant - “variable” is really null, a NullPointerException is thrown

Compliant Solution

if (variable == null) { /* … */ } // Compliant

13.return 语句不要出现在finally中

Returning from a finally block suppresses the propagation of any unhandled Throwable which was thrown in the try or catch block.

Noncompliant Code Example

public static void main(String[] args) {

try {

doSomethingWhichThrowsException();

System.out.println(“OK”); // incorrect “OK” message is printed

} catch (RuntimeException e) {

System.out.println(“ERROR”); // this message is not shown

}

}

public static void doSomethingWhichThrowsException() {

try {

throw new RuntimeException();

} finally {

/* … */

return; // Non-Compliant - prevents the RuntimeException from being propagated

}

}

public static void main(String[] args) {

try {

doSomethingWhichThrowsException();

System.out.println(“OK”);

} catch (RuntimeException e) {

System.out.println(“ERROR”); // “ERROR” is printed as expected

}

}

public static void doSomethingWhichThrowsException() {

try {

throw new RuntimeException();

} finally {

/* … */

}

}

14.想在jvm执行关闭程序之前做一些事情,不要试图调用两个丢弃的方法,System.runFinalizersOnExit 或Runtime.runFinalizersOnExit,可以通过下面的方法实现:

public static void main(String [] args) {

Runtime.addShutdownHook(new Runnable() {

public void run(){

doSomething();

}

});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: