新版sonar代码审查问题总结

2023-11-18

主要问题列表:

格式:问题名字+问题出现的次数

Resources should be closed2

资源未关闭,打开发现有两处用到的IO流没有关闭


Conditions should not unconditionally evaluate to "TRUE" or to "FALSE"1

if/else判断里出现了重复判断,比如在if(a>10)的执行体里面又判断if(a<0),而后者肯定不会是true


Exception handlers should preserve the original exception13

处理异常的时候应该保留原始的异常情况,不要直接来个catch(Exception e)了事


Throwable.printStackTrace(...) should not be called7

不应该直接调用e.printStackTrace(),而是用Loggers来处理(就是打Log)。

Loggers的优势是:Users are able to easily retrieve the logs.

The format of log messages is uniform and allow users to browse the logs easily.


Instance methods should not write to "static" fields6

不要用实例方法改变静态成员,理想情况下,静态变量只通过同步的静态方法来改变


"public static" fields should be constant1

公共静态成员应该加上final,也就是public static final 一般不分家


Thread.run() and Runnable.run() should not be called directly1

不应该直接调用Thread和Runnaale对象的run方法,直接调用run会使得run方法执行在当前线程,失去了开启新线程的意义。但有时候可能会这样做,下面有个例子。


Generic exceptions should never be thrown1

不太理解,大意是说不要直接抛Error,RuntimeException/Throwable/Exception这样的通用的异常。我的具体应用是:throw new Error("Error copying database"),给出的建议是:Define and throw a dedicated exception instead of using a generic one(定义并抛出一个专用的异常来代替一个通用的异常)


Class variable fields should not have public accessibility64

类变量不要设置为public,而是设为private,再提供get和set方法。


Sections of code should not be "commented out"30

不要再注释中出现大量的代码段,会使代码可读性变差


Package declaration should match source file directory19

这个没理解,包的声明应该与源文件目录匹配。


Utility classes should not have public constructors16

工具类不应该有公共的构造器,也就是说至少要有一个private的构造器,如果没有,默认的构造器是public的。


The diamond operator ("<>") should be used12

在定义集合的时候,等号右边的<>内不需要再写上元素类型,直接空着就行。


Lambdas and anonymous classes should not have too many lines9

Lambdas表达式和匿名内部类不要写太多行,一般最多写20行。


Anonymous inner classes containing only one method should become lambdas8

只包含一个方法的匿名内部类应该写成Lambdas表达式的形式,增强代码可读性


Try-with-resources should be used8

用Try-with-resources的形式取代try/catch/finally的形式,这个有待于以后学习。


Methods should not be empty7

不要写空方法,除非这种情况:An abstract class may have empty methods, in order to provide default implementations for child classes.


Source files should not have any duplicated blocks7

源文件中不要出现任何重复的代码段或行或字符串等。没理解。


"switch case" clauses should not have too many lines6

"switch case" 每个case里面的代码不要太长,太长的话可以考虑写个方法代替,主要是为了增强代码可读性


Nested blocks of code should not be left empty6

嵌套代码块不要是空的,比如 if( a > 0 ) {  doSomething()  } else { },这时候应该把后面的else{}去掉。


Methods should not be too complex6

方法不要太复杂,否则难以理解和维护。


Unused private fields should be removed5

没有使用的private的成员变量应该移除掉。


Dead stores should be removed5

没有用到的本地变量或其他死存储应该移除掉,也就是写方法的时候,定义的变量如果后来发现根本用不到,要记得删掉那行代码。


"switch" statements should end with a "default" clause4

switch语句应该以default结束,这是一种defensive programming思想


Unused method parameters should be removed4

没有用到的方法参数应该移除掉


Control flow statements "if", "for", "while", "switch" and "try" should not be nested too deeply4

if /for/while/try这样的嵌套不要太复杂


Useless parentheses around expressions should be removed to prevent any misunderstanding3

没有意义的括号不要随便加,以免造成误解,比如"="两边对象类型是相同的,就不要强转。


"for" loop stop conditions should be invariant3

for循环的结果条件不能是变量,而应该是常量


"static" members should be accessed statically2

static成员是与类、静态方法相联系的。


Catches should be combined2

具体参考下面的18,我还没理解


Primitives should not be boxed just for "String" conversion2

不要使用 4+" "这样的方式将int值转变为字符串,而是使用 Integer.toString(4)这样的方式。

就像Integer.parseInt("我是字符串")这样,不要偷懒。


Classes should not be empty2

不要写空类


Unused local variables should be removed2

没有用到的本地变量要删掉


"entrySet()" should be iterated when both the key and value are needed2

直接看英文更直接:When only the keys from a map are needed in a loop, iterating the keySet makes sense. But when both the key and the value are needed, it's more efficient to iterate theentrySet, which will give access to both the key and value, instead.

也就是说,如果只需要Map的Key,那么直接iterate这个Map的keySet就可以了,但是如果Key和value都需要,就iterate这个Map。具体看下面的19.


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

方法参数/捕获的异常/foreach的变量不应该被重新赋值。


Collection.isEmpty() should be used to test for emptiness2

当判断集合是否为空的时候,不要使用if (myCollection.size() == 0) 这样的方式,而是使用if (myCollection.isEmpty()这样的方式,后者性能更高。


Standard outputs should not be used directly to log anything2

标准输出不直接打印任何东西,也就是打log的时候,不要使用System.out.println("My Message")这样的方式,而是使用logger.log("My Message")这种方式。


Generic wildcard types should not be used in return parameters1

通配符不应该出现在返回声明中。比如这句:List <? extends Animal>getAnimals(){...}, 我们无法知道“是否可以把a Dog, a Cat 等加进去”,等之后用到这个方法的时候,我们没必要去考虑这种问题(前面引号里面的)。


Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used1

不要使用同步的Vector/HashTable/Stack/StringBuffer等。在早期,出于线程安全问题考虑,java API 提供了这些类。但是同步会极大影响性能,即使是在同一个线程中使用他们。

通常可以这样取代:

ArrayList  or  LinkedList   instead of  Vector

Deque  instead of  Stack

HashMap  instead of  Hashtable

StringBuilder  instead of  StringBuffer

Exit methods should not be called

尽量不要调用system.exit()方法。


Local Variables should not be declared and then immediately returned or thrown7

本地变量如果赋值之后直接return了,那就直接return本地变量的赋值语句。


Field names should comply with a naming convention6

命名要规范


Local variable and method parameter names should comply with a naming convention6

命名要规范


String literals should not be duplicated5

字符串不应该重复,如果多次用到同一字符串,建议将该字符串定义为字符串常量,再引用。


Return of boolean expressions should not be wrapped into an "if-then-else" statement3

不要写if (  a > 4  ) {  return false  } else { return true }这样的代码,直接写return a > 4。


Static non-final field names should comply with a naming convention2

命名要规范


Modifiers should be declared in the correct order2

修饰符等要按约定俗成的顺序书写 ,例如,写成public static 而不是static public 


The members of an interface declaration or class should appear in a pre-defined order2

与前面的一个问题类似,根据Oracle定义的Java代码规范中,不同代码的出现位置应该如下所示:

class and instance variables--Constructors--Methods


Array designators "[]" should be on the type, not the variable2

数组的括号要写在类型后面,而不是变量后面,例如 int[] a 而不是int a[]


Multiple variables should not be declared on the same line1

不要在同一行定义多个变量


"switch" statements should have at least 3 "case" clauses1

当至少有3种或者3种以上的情况时,才考虑用switch,否则用if/else的形式。


Overriding methods should do more than simply call the same method in the super class1

既然在子类中重写了父类的某个方法,那就再这个方法中做些与父类方法不同的事情,否则没必要重写。


Statements should be on separate lines1

不要把这样的代码写在同一行:if(someCondition)    doSomething();而是应该写成下面的形式

if(someCondition) {

doSomething()

}


Method names should comply with a naming convention1

命名要规范


"TODO" tags should be handle    TODO标签要及时处理,该做的事情不要忘了做


部分规则详细说明

1.The members of an interface declaration or class should appear in a pre-defined order


正确的顺序如下所示:静态成员变量→成员变量→构造器→方法

public class Foo{

public static final int OPEN = 4;  //Class and instance variables

private int field = 0;

public Foo() {...}    //Constructors

public boolean isTrue() {...}    //Methods

}

2.The diamond operator ("<>") should be used

Noncompliant Code Example:不规范的示例

List<String>  strings = new ArrayList<String>();  // Noncompliant

Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();  // Noncompliant

Compliant Solution :规范的示例

List<String> strings = new ArrayList<>();

Map<String, List<Integer>> map = new HashMap<>();

3.Sections of code should not be "commented out"

代码片段不应该出现在注释中,这样会bloat程序,可读性变差

Programmers should not comment out code as it bloats programs and reduces readability.

Unused code should be deleted and can be retrieved from source control history if required.

4.Utility classes should not have public constructors

工具类不应该有public的构造器,也就是工具类至少要定义一个non-public的构造器

Utility classes, which are a collection of static members, are not meant to be instantiated. Even abstract utility classes, which can be extended, should not have public constructors.

Java adds an implicit public constructor to every class which does not define at least one explicitly. Hence, at least one non-public constructor should be defined.

class StringUtils { // Noncompliant Code Example

    public static String concatenate(String s1, String s2) {

          return s1 + s2;

    }

}

class StringUtils { //Compliant Solution

    private StringUtils() {

    }

    public static String concatenate(String s1, String s2) {

    return s1 + s2;

    }

}

5."public static" fields should be constant

公共的静态成员应该加上final来修饰

There is no good reason to declare a field "public" and "static" without also declaring it "final". Most of the time this is a kludge to share a state among several objects. But with this approach, any object can do whatever it wants with the shared state, such as setting it to null.

public static Foo foo = new Foo();//不规范的

public static final Foo FOO = new Foo();//规范的

6.Class variable fields should not have public accessibility

public class MyClass {

public static final int SOME_CONSTANT = 0;    // Compliant - constants are not checked

public String firstName;                      // Noncompliant

}

public class MyClass {

public static final int SOME_CONSTANT = 0;    // Compliant - constants are not checked

private String firstName;                      // Compliant

public String getFirstName() {

return firstName;

}

public void setFirstName(String firstName) {

this.firstName = firstName;

}

}

7.Static non-final field names should comply with a naming convention

public final class MyClass {//Noncompliant Code Example

      private static String foo_bar;

}

class MyClass {//Compliant Solution

private static String fooBar;

}

8."switch" statements should have at least 3 "case" clauses

当有3种或3种情况以上的时候,才用switch,否则用if/else

switch statements are useful when there are many different cases depending on the value of the same expression.

For just one or two cases however, the code will be more readable with if statements.

9.String literals should not be duplicated

prepare("action1");     // Noncompliant - "action1" is duplicated 3 times

execute("action1");

release("action1");


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

prepare(ACTION_1);                                            // Compliant

execute(ACTION_1);

release(ACTION_1);

10.Return of boolean expressions should not be wrapped into an "if-then-else" statement

if (expression) {//Noncompliant Code Example

      return true;

} else {

     return false;

}


return expression;//Compliant Solution

return !!expression;

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

方法参数,捕获的异常,foreach里的变量,都不应该重新赋值


class MyClass {//Noncompliant Code Example:不规范代码示例

    public String name;

    public MyClass(String name) {

            name = name;          // Noncompliant - useless identity assignment

    }

    public int add(int a, int b) {

        a = a + b;                // Noncompliant

        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

    }

}


class MyClass {//Compliant Solution:规范代码示例

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

     }

}

12.Local Variables should not be declared and then immediately returned or thrown

Noncompliant Code Example:不规范代码示例

public long computeDurationInMilliseconds() {

long duration = (((hours * 60) + minutes) * 60 + seconds ) * 1000 ;

return duration;

}

public void doSomething() {

RuntimeException myException = new RuntimeException();

throw myException;

}


Compliant Solution:规范代码示例

public long computeDurationInMilliseconds() {

return (((hours * 60) + minutes) * 60 + seconds ) * 1000 ;

}

public void doSomething() {

throw new RuntimeException();

}

13.Thread.run() and Runnable.run() should not be called directly

The purpose of theThread.run()andRunnable.run()methods is to execute code in a separate, dedicated thread. Calling those methods directly doesn't make sense because it causes their code to be executed in the current thread.

Thread和Runnable里面的run方法设计的目的是让run方法里面的代码在不同的线程中执行。如果直接调用run方法,就会导致run方法里的代码在当前线程中执行,失去意义

Noncompliant Code Example:不规范的代码示例

Thread myThread = new Thread(runnable);

myThread.run(); // Noncompliant


Compliant Solution:规范代码示例

Thread myThread = new Thread(runnable);

myThread.start(); // Compliant

这部分内容为个人理解,可以略过

但在有些情况,也会直接调用Runnable的run方法,

下面这个postTaskSafely方法会保证task永远在主线程中执行

public static void postTaskInMainThread(Runnable task) {

     int curThreadId= android.os.Process.myTid();//得到当前线程的id

    if(curThreadId==getMainThreadId()) {// 如果当前线程是主线程

            task.run();//直接执行

    }else{// 如果当前线程不是主线程

        getMainThreadHandler().post(task);//用主线程的Handler来post

}

14.Lambdas and anonymous classes should not have too many lines

Anonymous classes and lambdas (with Java 8) are a very convenient and compact way to inject a behavior without having to create a dedicated class. But those anonymous inner classes and lambdas should be used only if the behavior to be injected can be defined in a few lines of code, otherwise the source code can quickly become unreadable.

anonymous class number of lines : at most 20

15.Resources should be closed:该关闭的一定记得关闭

Java's garbage collection cannot be relied on to clean up everything. Specifically, connections, streams, files and other classes that implement theCloseableinterface or it's super-interface,AutoCloseable, must be manually closed after creation. Failure to do so will result in a resource leak which could bring first the application and then perhaps the box it's on to their knees.

Noncompliant Code Example:不规范的代码示例

    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.

    }


Compliant Solution:规范代码示例

    OutputStream stream = null;

    try{

        stream = new FileOutputStream("myfile.txt");

        for (String property : propertyList) {

            // ...

        }

   }catch(Exception e){

        // ...

   }finally{

       stream.close();

   }

16.Exception handlers should preserve the original exception

Noncompliant Code Example:不规范的代码示例

// Noncompliant - exception is lost

try { /* ... */ } catch (Exception e) { LOGGER.info("context"); }

// Noncompliant - exception is lost (only message is preserved)

try { /* ... */ } catch (Exception e) { LOGGER.info(e.getMessage()); }

// Noncompliant - exception is lost

try { /* ... */ } catch (Exception e) { throw new RuntimeException("context"); }


Compliant Solution:规范的代码示例

try { /* ... */ } catch (Exception e) { LOGGER.info(e); }

try { /* ... */ } catch (Exception e) { throw new RuntimeException(e); }

try {

/* ... */

} catch (RuntimeException e) {

doSomething();

throw e;

} catch (Exception e) {

// Conversion into unchecked exception is also allowed

throw new RuntimeException(e);

}

17.Catches should be combined

Since Java 7 it has been possible to catch multiple exceptions at once. Therefore, when multiplecatchblocks have the same code, they should be combined for better readability.

Note that this rule is automatically disabled when the project'ssonar.java.sourceis lower than7.

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;

}

18."entrySet()" should be iterated when both the key and value are needed

Noncompliant Code Example:不规范的代码示例

public void doSomethingWithMap(Map map) {

for (String key : map.keySet()) {  // Noncompliant; for each key the value is retrieved

Object value = map.get(key);

// ...

}   

}   


Compliant SolutionL:规范代码示例

public void doSomethingWithMap(Map map) {

for (Map.Entry entry : map.entrySet()) {

String key = entry.getKey();

Object value = entry.getValue();

// ...

}   

}   



文/麦思微(简书作者)
原文链接:http://www.jianshu.com/p/b50f01eeba4d
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

新版sonar代码审查问题总结 的相关文章

  • 【简单】228. 汇总区间

    原题链接 https leetcode cn problems summary ranges description 228 汇总区间 给定一个 无重复元素 的 有序 整数数组 nums 返回 恰好覆盖数组中所有数字 的 最小有序 区间范围
  • CVPR 2021 Object Detection

    一 关于3D有26篇 3DIoUMatch Leveraging IoU Prediction for Semi Supervised 3D Object Detection ST3D Self Training for Unsupervi
  • 数据结构---红包分配算法

    红包分配算法 错误解法 二倍均值法 JAVA实现 线段切割法 确定每一条子线段的长度 JAVA实现 问题如下 所有人抢到的金额之和要等于红包金额 不能多也不能少 每个人至少抢到1分钱 要保证红包拆分的金额尽可能分布均衡 不要出现两极分化太严
  • Linux下软链接方法切换CUDA版本

    Linux下软链接方法切换CUDA版本 Linux下安装多版本的CUDA 直接切换版本 CUDA切换 sudo rm rf usr local cuda 删除之前的软链接 sudo ln s usr local cuda 10 0 usr
  • Allegro如何导出和导入设计规则操作指导

    Allegro如何导出和导入设计规则操作指导 当需要借用另外一款PCB的设计规则时候 Allegro支持把PCB设计规则导入到另外一块PCB中 如下图 具体操作如下 打开规则管理器 打开后如下图
  • 黑马程序员mysql笔记--索引基本操作部分

    视频链接 https www bilibili com video BV1iF411z7Pu 1 3 1 索引的基本操作 1 3 1 1 索引概述 索引是什么 索引是通过某种算法 构建出一个数据模型 用于快速找出在某个列中有一特定值的行 不
  • 《A Metric Learning Reality Check》笔记

    1 是 metric learning 的一篇学术打假文 回顾了 deep metric learning 领域两个经典工作 contrastive loss triplet loss 和近年来 2017 2019 见文中 Table 6
  • DC-DC电源管理

    BUCK电源芯片的使用与选择 BUCK电路降压原理 在开关S闭合时 对电感L与电容C进行充电同时也对负载R供电 在开关S断开时储能元器件L与C继续对R进行供电并通过D1形成回路 输出电压Vo Vi Ton Ton Toff Ton 开关S闭
  • 【C语言】实现一个通讯录:通讯录可以用来存储1000个人的信息,每个人的信息包括: 姓名、性别、年龄、电话、住址

    先写一个只能录固定人数的通讯录 不能增容 不能保存 通讯录可以用来存储1000个人的信息 每个人的信息包括 姓名 性别 年龄 电话 住址 实现功能 1 添加联系人信息 2 删除指定联系人信息 3 查找指定联系人信息 4 修改指定联系人信息
  • Linux 压缩解包命令讲解

    tar命令使用讲解 压缩 tar命令 c 生成档案文件 v 列出归档解档的详细过程 f 指定档案文件名称 t 列出档案在包含的文件 x 解开档案文件 打包 tar cvf a tar txt tar cf a tar txt 解包 tar
  • mysql split函数用逗号分隔的实现方法

    本文主要介绍了mysql split函数用逗号分隔的实现 文中通过示例代码介绍的非常详细 对大家的学习或者工作具有一定的参考学习价值 需要的朋友们下面随着小编来一起学习学习吧 1 定义存储过程 用于分隔字符串 1 2 3 4 5 6 7 8
  • 服务端推送SSE技术

    SSE Server Sent Events 是一种用于实现服务器主动向客户端推送数据的技术 也被称为 事件流 Event Stream 它基于 HTTP 协议 利用了其长连接特性 在客户端与服务器之间建立一条持久化连接 并通过这条连接实现
  • 杂学日记

    glob函数的使用 glob库函数用于Linux文件系统中路径名称的模式匹配 即查找文件系统中指定模式的路径 注意 这不是正则表达式匹配 虽然有些相似 但还是有点差别 glob函数原型 include
  • 快速提升代码能力(7)sort(a,a+n);

    从零起步看算法 第七天 4 12 q9 交叉排序 算是一道水题了 1 花点时间看一下样例 就可以理解题意了 2 本题唯一知识点 用sort 实现 数组的从大到小排序 很简单的操作 https blog csdn net jimmy lee1
  • python 字典中 get 和 [] 的区别

    在Python中 get和 是用来访问字典 dict 或字典样的对象 例如defaultdict 中的元素的两种常见方式 它们有一些区别 使用get方法时 如果指定的键不存在于字典中 它会返回一个默认值 默认为None 也可以自定义 而不会
  • ConceptFusion 论文翻译

    ConceptFusion 论文翻译 本文仅仅是本人在英语水平不够的情况下对原论文的翻译 如果有错烦请指正 原始论文地址参见 https arxiv org pdf 2302 07241 pdf 下面开始正式翻译 摘要 构建三维环境地图对于
  • Wireshark网络抓包工具下载和安装(2023)

    一 Wireshark的下载 下载网址 https www wireshark org download html 也可以阿里网盘自取 wiresharkhttps www aliyundrive com s c4qeGBQMfwj提取码
  • 实现 Java 平台的三种方式

    广泛地说 只要能执行 Java bytecode 者 就可以称为 Java 平台 Java platform 大致上 实现 Java 平台的方式有三种 分别是 Java 虚拟机器 Java Virtual Machine JVM Java
  • Java实现企业微信上传临时文件获取media_id

    目录 1 上传临时素材API 2 测试代码 3 测试完成 4 遇到的问题 4 1 文件类型无法解析 1 上传临时素材API 调试工具 素材上传得到media id 该media id仅三天内有效 media id在同一企业内应用之间可以共享
  • Qt之:QProcess使用总结

    1 主程序 初始化及设定信号槽 process new QProcess connect process SIGNAL started SLOT started connect process SIGNAL finished int QPr

随机推荐