Coding.net 自动分析Android代码错误集合

来源:互联网 发布:淘宝情趣泳衣买家秀 编辑:程序博客网 时间:2024/06/05 05:54

一. 注释代码不应该保留而应该使用版本控制工具查找.

二. 使用System.exit()会造成应用重启,因为操作系统会以为是不正常退出.

三. 各种Stream应该正确的关掉.

模板为:

private void readTheFile() throws IOException {  Path path = Paths.get(this.fileName);  BufferedReader reader = Files.newBufferedReader(path, this.charset)) {  // ...  reader.close();  // Noncompliant}private void doSomething() {  OutputStream stream = null;  try {    for (String property : propertyList) {      stream = new FileOutputStream("myfile.txt");  // Noncompliant      // ...    }  } catch (Exception e) {    // ...  } finally {    stream.close();  // Multiple streams were opened. Only the last is closed.  }}

四. 一些多次使用的字符串应该写为静态变量防止出错

错误写法为:

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}

正确写法为:

private static final String ACTION_1 = "action1";  // Compliantpublic void run() {  prepare(ACTION_1);                               // Compliant  execute(ACTION_1);  release(ACTION_1);}

五. 深度嵌套的”if”,”for”,”while”,”switch”,”try”不推荐使用.

比如:

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;      }    }  }}

六. 函数的认知复杂度过高.

每个if +1每个判断+1等等,相关文档

七. 未完待续