SonarQube代码检查,java代码优化(Bug类型)

文章目录

一、bug类型

1、运算类型优化

将此乘法运算的一个操作数强制转换为“long”

  • 解决思路把第一个运算数直接转换成很long类型即可,后面的所有运算会自动升级为long类型运算
cast one of the operands of this multiplication operation to a "long"
  • 原代码
long l=12*60*60
  • 更新后代码
long l=12L*60*60

将此除法运算的一个操作数强制转换为“double”

  • 解决思路把第一个运算数直接转换成double类型即可
cast one of the operands of this division operation to a "double"

通过将“&0xff”添加到此表达式来阻止“int”提升

Prevent "int" promotion by adding "& 0xff" to this expression
  • 原代码
byte high = (byte) 0B11010000;
byte low = (byte) 0B01111111;
byte result = (byte) (high << 4 | low);
  • 更新后代码
//(high << 4 | low) 运算完之后会升级为int类型
//直接转换为beye类型,会直接舍弃高位,保留8位低位。效果和 0xff一样的
//这里是SonarQube会进行代码检查而已,本身逻辑没问题
byte high = (byte) 0B11010000;
byte low = (byte) 0B01111111;
byte result = (byte) ((high << 4 | low) & 0xff);

更正运算符“||”两侧的一个相同子表达式

correct one of the identical sub-expressions on both sides of operator "||"

2、变量类型优化

删除“字节”的装箱

remove the boxing of "byteint"
  • 原代码
int byteint= Integer.parseInt(swap,16) & 0xFF;
b[j] = new Integer(byteint).byteValue();
  • 更新后代码
int byteint= Integer.parseInt(swap,16) & 0xFF;
b[j] = byteint.byteValue();

移除"Double"的装箱

remove the boxing to "Double"
  • 原代码
public static void main(String[] args) {
    Double record = 2.58493128;
    Long longValue = Double.valueOf(record * Math.pow(10, 8)).longValue();
    System.out.println(longValue);
}
  • 更新后代码
public static void main(String[] args) {
    Double record = 2.58493128;
    Long longValue = (long)(record * Math.pow(10, 8));
    System.out.println(longValue);
}

引入一个新变量,而不是重复使用参数“row”

  • 报错原因:方法传入的参数尽量不要修改,而是创建一个新的变量接收
introduce a new variable instead of reusing the parameter "row"
  • 原代码
    public int queryAdd (int row,int b){
        row=mapper.queryCount();
        return row+b;
    }
  • 更新后代码
    public int queryAdd (int row,int b){
        a=mapper.queryCount();
        return a+b;
    }

请改用“BigDecimal.valueOf”

Use "BigDecimal.valueOf" instead
  • 原代码
BigDecimal dataSize = new BigDecimal(new Double(0));
  • 修改后
BigDecimal dataSize = BigDecimal.valueOf(0);

3、try-catch-finally相关

使用try with resources或关闭“finally”子句中的此“BufferedReader”。

Use try-with-resources or close this "BufferedReader" in a "finally" clause.
情形一:FileInputStream流没有关闭
  • 原代码
try{
    FileInputStream fileInput=new FileInputStream("C:\\Users\\ljj\\Desktop\\test.txt");
}catch (Exception e){
	e.printStackTrace();
}
  • 更新之后代码
//方式一
FileInputStream fileInput=null;
try{
    fileInput=new FileInputStream("C:\\Users\\ljj\\Desktop\\test.txt");
}catch (Exception e){
    e.printStackTrace();
}finally {
    if (fileInput!=null){
        fileInput.close();
    }
}
//方式二,简洁
try(FileInputStream fileInput=new FileInputStream("C:\\Users\\ljj\\Desktop\\test.txt")){

}catch (Exception e){
    e.printStackTrace();
}

从这个finally块中删除这个throw语句。

remove this throw statement from this finally block.
  • 原代码
finally{
	try{
		reader.close;
	}catch (IOException e){
		throw e;
	}	
}
  • 更新后代码
finally{
	try{
		reader.close;
	}catch (IOException e){
	}	
}

从finally块中删除此return语句

  • 说明:因为finally里面写了return语句的时候,就会覆盖掉try代码块里面的return。因为finally是肯定会执行的。
remove this return statement from this finally block
  • 原代码
//单位某个人才写的代码,把return写进finally。作者发现catch模块虽然重新抛出了异常,但是因为finally会正常返回,catch抛出的异常失效
static String test() throws RuntimeException{
    try{
        int i=1/0;
        System.out.println(i);
    }catch (Exception e){
        throw new RuntimeException("运行时异常");
    }finally {
        return "finally返回";
    }
}
  • 更新后代码
static String test() throws RuntimeException{
    try{
        int i=1/0;
        System.out.println(i);
    }catch (Exception e){
        return "finally返回";
    }
    return "正常运行";
}

重新中断此方法,或者重新引发可以在此处捕获的“InterruptedException”

either re-interrupt this method or rethrow the "InterruptedException"  that can be caught here
  • 原代码
try{
    Thread.sleep(3000);
}catch (InterruptedException e){
    e.printStackTrace();
}
  • 更新后代码
try{
    Thread.sleep(3000);
}catch (InterruptedException e){
    e.printStackTrace();
    Thread.currentThread().interrupt();
}

4、if模块相关

更改此条件,使其不总是计算为“true”

change this condition so that it does not always evaluate to "true"
  • 原代码
//构造函数不存在返回null,只有可能抛出错误
Account account=new AliyunAccount(dgInfo.getDbUsername(),dbInfo.getDbPass());
if(null==account){
	log.error("连接阿里云异常")
	throw new Exception("连接阿里云异常")
}
  • 修改后
Account account=new AliyunAccount(dgInfo.getDbUsername(),dbInfo.getDbPass());

只应检查结果的标志

Only the sign of the result should be examined
  • 原代码
if(a.compareTo(b)==-1){
}
  • 更新后代码
if(a.compareTo(b)<0){
}

删除此条件结构或编辑其代码块,使它们不完全相同

  • 提示原因:if里面执行的代码相同了
remove this conditional structure or edit its code blocks so that they're not all the same
  • 原代码
if(dept.equals("1")){
    System.out.println("这里是外联部");
} else if (dept.equals("2")) {
    System.out.println("这里是外联部");
}
  • 更新后代码
if(dept.equals("1")){
    System.out.println("这里是外联部");
}

无法到达该分支,因为该条件与同一“if/else-if”语句序列中的前一个条件重复

  • 提示原因:if的判定条件相同了
this branch can not be reached because the condition duplicates a previous condition in the same sequence of "if/else if" statements
  • 原代码
if(dept.equals("外联部")){
    System.out.println("这里是外联部");
} else if (dept.equals("外联部")) {
    System.out.println("这里是第二个外联部");
}
  • 更新后代码
System.out.println("这里是外联部");

5、返回值相关

检查“read”调用的返回值,查看读取了多少字节

Check the return value of the "read" call to see how many bytes were read
  • 原代码
inputStream.read(data)
  • 更新后代码
while(-1 != inputStream.read(data)){
}

对“delete”返回的“boolean”值执行操作

do something with the "boolean" value returned by "delete"
  • 原代码
if(csvFile.exists()){
	csvFile.delete();
}
  • 更新后代码
//解决方案:增加false判断
if(csvFile.exists()){
	if (!csvFile.delete()) {
      log.error("文件删除失败");
	}
}

必须使用返回值“length”

The return value of "length" must be used
  • 原代码
String s = "abcdefg";
s.length();
  • 更新后代码
String s = "abcdefg";
int len = s.length();

未分类

更新此作用域并删除“systemPath”

update this scope and remove the "systemPath"
  • 原代码
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>4.5.15</version>
    <scope>system<scope>
    <systemPath>${project.basedir}/libs/hutool-all.jar</systemPath>
</dependency>
  • 更新后代码,作者还没想好

保存并重复使用此“Random”

Save and re-use this "Random"
  • 原代码
Random rand=new Random();
  • 更新后代码
Random rand=new SecureRandom();

重构这种可能导致大型输入堆栈溢出的重复

Refactor this repetition that can lead to a stack overflow for large inputs
  • 原代码
//邮箱地址判断
//提示原因:([-+.]\\w+)* 在表达式里面重复了
Pattern pattern= Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-+.]\\w+)*\\.w+([-+.]\\w+)*$");
  • 更新后代码:作者还不知道

向该方法添加类型测试

  • 类型转换之前没有,进行判断
Add a type test to this method
  • 原代码
public boolean equals(Object obj) {
    Student student = (Student) obj;
    if (student.getName().equals(this.name)) return true;
    return false;
}
  • 修改后
public boolean equals(Object obj) {
    if (obj == null) {
        return false;
    }
    if (this.getClass() != obj.getClass()) {
        return false;
    }
    Student student = (Student) obj;
    if (student.getName().equals(this.name)) return true;
    return false;
}

该类重写“equals()”,因此也应重写“hashCode()”

  • 因为类中写了 equals 方法,但是却没有重写 hashCode 方法
  • 解决方法:补一个hashCode()方法即可,IDEA可以通过Alt+Insert自动生成。
this class overrides "equals()" and should therefore also override "hashCode()"

“-1”对于设置“dayOfMonth”无效

  • 注意:Java中月份是从0开始,即0表示1月;周日是数字1,以此类推;
"-1" it not a valid for setting "dayOfMonth"
  • 原代码
Calendar calendar = new GregorianCalendar(1900, 0, -1);
  • 修改后
Calendar calendar = new GregorianCalendar(1900, 0, 0);
calendar.add(Calendar.DATE, -1);

请确保此处应为周-年“YYYY”,而不是年“yyyy”

Make sure that week year "YYYY" is expected here instead of Year "yyyy"
  • 原代码
SimpleDateFormat formater = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
  • 修改后
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

使“sdf”成为实例变量

  • 有些类不是线程安全的,将变量生命为静态的可能会导致线程安全问题
Make "sdf" an instance variable
  • 原代码
public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  • 修改后代码
public final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

删除此“return”语句或将其设为条件语句

Remove this "return" statement or make it conditional
  • 原代码
public static int maxArray(int a[]){
    for (int i : a) {
        return i;
    }
    return 0;
}
  • 更新后代码
public static int maxArray(int a[]){
    for (int i : a) {
        
    }
    return 0;
}

引发此异常或删除此无用语句

  • 错误原因:生成了异常对象,但是没有抛出。
Throw this exception or remove this useless statement
  • 原代码
try{
    System.out.println("程序正常执行!");
}catch (Exception e){
    System.out.println("程序非正常执行!");
    new RuntimeException("程序非正常执行!");
}
  • 更新后代码
try{
    System.out.println("程序正常执行!");
}catch (Exception e){
    System.out.println("程序非正常执行!");
    throw new RuntimeException("程序非正常执行!");
}

重写Object.equals(Object-obj),或者完全重命名该方法以防止混淆

either override Object.equals(Object obj),or totally rename the method to prevent any confusion

二、漏洞类型

更改此代码以使用更强的协议

Change this code to use a stronger protocol

在此SSL/TLS连接上启用服务器证书验证

Enablle server certificate validation on this SSL/TLS connextion
  • 原代码
@Override
public void checkClientTrusted(X509Certificate[] chain,String authType){
}

使用安全填充方案

Use a secure padding scheme
  • 原代码
SSLContext sc=SSLContext.getInstance("SSL")

参考文档

  • 19
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值