JAVA代码编写规范

来源:互联网 发布:淘宝处理图片去同款 编辑:程序博客网 时间:2024/04/30 12:14

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

@FunctionalInterfacepublic 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 excludedprivate 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";  // Compliantpublic 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);  }}


0 0
原创粉丝点击