JAVA代码编写规范

本文介绍了Java编程中的一些最佳实践,包括非嵌套枚举不应声明为静态、使用@FunctionalInterface注解标记SAM接口、按照标准顺序声明修饰符、避免函数过于复杂、限制控制流语句的嵌套深度、避免在循环中使用字符串连接、消除字符串字面量的重复、限制方法参数数量、合并catch块、返回空数组或集合而非null,以及避免重新赋值方法参数、捕获的异常和foreach变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Nested “enum”s should not be declared static squid

Noncompliant Code Example

public class Flower {
  static enum Color { // Noncompliant; static is redundant here
    RED, YELLOW, BLUE, ORANGE
  }

  // ...
}

Compliant Solution

public class Flower {
  enum Color { // Compliant
    RED, YELLOW, BLUE, ORANGE
  }

  // ...
}



@FunctionalInterface annotation should be used to flag Single Abstract Method interfaces

Noncompliant Code Example

public interface Changeable<T> {
  public void change(T o);
}

Compliant Solution

@FunctionalInterface
public interface Changeable<T> {
  public void change(T o);
}



Modifiers should be declared in the correct order

The Java Language Specification recommends listing modifiers in the following order:

  1. Annotations

  2. public

  3. protected

  4. private

  5. abstract

  6. static

  7. final

  8. transient

  9. volatile

  10. synchronized

  11. native

  12. strictfp

Not following this convention has no technical impact, but will reduce the code’s readability because most developers are used to the standard order.

Noncompliant Code Example

static public void main(String[] args) {   // Noncompliant
}

Compliant Solution

public static void main(String[] args) {   // Compliant
}



Functions should not be too complex

maximumFunctionComplexityThreshold

The maximum authorized complexity in function
Default Value: 10


Control flow statements “if”, “for”, “while”, “switch” and “try” should not be nested too

Noncompliant Code Example

With the default threshold of 3:

if (condition1) {                  // Compliant - depth = 1
  /* ... */
  if (condition2) {                // Compliant - depth = 2
    /* ... */
    for(int i = 0; i < 10; i++) {  // Compliant - depth = 3, not exceeding the limit
      /* ... */
      if (condition4) {            // Noncompliant - depth = 4
        if (condition5) {          // Depth = 5, exceeding the limit, but issues are only reported on depth = 4
          /* ... */
        }
        return;
      }
    }
  }
}



Strings should not be concatenated using ‘+’ in a loop

Noncompliant Code Example

String str = "";
for (int i = 0; i < arrayOfStrings.length ; ++i) {
  str = str + arrayOfStrings[i];
}

Compliant Solution

StringBuilder bld = new StringBuilder();
  for (int i = 0; i < arrayOfStrings.length; ++i) {
    bld.append(arrayOfStrings[i]);
  }
  String str = bld.toString();



String literals should not be duplicated

Noncompliant Code Example

With the default threshold of 3:

public void run() {
  prepare("action1");                              // Noncompliant - "action1" is duplicated 3 times
  execute("action1");
  release("action1");
}

@SuppressWarning("all")                            // Compliant - annotations are excluded
private void method1() { /* ... */ }
@SuppressWarning("all")
private void method2() { /* ... */ }

public String method3(String a) {
  System.out.println("'" + a + "'");               // Compliant - literal "'" has less than 5 characters and is excluded
  return "";                                       // Compliant - literal "" has less than 5 characters and is excluded
}

Compliant Solution

private static final String ACTION_1 = "action1";  // Compliant

public void run() {
  prepare(ACTION_1);                               // Compliant
  execute(ACTION_1);
  release(ACTION_1);
}



Methods should not have too many parameters

Noncompliant Code Example

With a maximum number of 4 parameters:

public void doSomething(int param1, int param2, int param3, String param4, long param5) {
...
}

Compliant Solution

public void doSomething(int param1, int param2, int param3, String param4) {
...
}



Catches should be combined

Noncompliant Code Example

catch (IOException e) {
  doCleanup();
  logger.log(e);
}
catch (SQLException e) {  // Noncompliant
  doCleanup();
  logger.log(e);
}
catch (TimeoutException e) {  // Compliant; block contents are different
  doCleanup();
  throw e;
}

Compliant Solution

catch (IOException|SQLException e) {
  doCleanup();
  logger.log(e);
}
catch (TimeoutException e) {
  doCleanup();
  throw e;
}



Empty arrays and collections should be returned instead of null

Noncompliant Code Example

public static List<Result> getResults() {
  return null;                             // Noncompliant
}

public static Result[] getResults() {
  return null;                             // Noncompliant
}

public static void main(String[] args) {
  Result[] results = getResults();

  if (results != null) {                   // Nullity test required to prevent NPE
    for (Result result: results) {
      /* ... */
    }
  }
}

Compliant Solution

public static List<Result> getResults() {
  return Collections.emptyList();          // Compliant
}

public static Result[] getResults() {
  return new Result[0];
}

public static void main(String[] args) {
  for (Result result: getResults()) {
    /* ... */
  }
}



Method parameters, caught exceptions and foreach variables should not be reassigned

Noncompliant Code Example

class MyClass {
  public String name;

  public MyClass(String name) {
    name = name;                    // Noncompliant - useless identity assignment
  }

  public int add(int a, int b) {
    a = a + b;                      // Noncompliant

    /* additional logic */

    return a;                       // Seems like the parameter is returned as is, what is the point?
  }

  public static void main(String[] args) {
    MyClass foo = new MyClass();
    int a = 40;
    int b = 2;
    foo.add(a, b);                  // Variable "a" will still hold 40 after this call
  }
}

Compliant Solution

class MyClass {
  public String name;

  public MyClass(String name) {
    this.name = name;               // Compliant
  }

  public int add(int a, int b) {
    return a + b;                   // Compliant
  }

  public static void main(String[] args) {
    MyClass foo = new MyClass();
    int a = 40;
    int b = 2;
    foo.add(a, b);
  }
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值