android sonar 简书,sonar 问题总结

前言

sonar 是一个代码静态扫描工具,可以在开发阶段规避一些较为明显的问题。现在总结一些工作中经常遇到的扫出来的 bug。

IO Exception

规则原文:

Connections, streams, files, and other classes that implement the Closeable interface or its super-interface, AutoCloseable, needs to be closed after use. Further, that close call must be made in a finally block otherwise an exception could keep the call from being made. Preferably, when class implements AutoCloseable, resource should be created using "try-with-resources" pattern and will be closed automatically.

Failure to properly close resources will result in a resource leak which could bring first the application and then perhaps the box it's on to their knees.

大致意思是:连接,流,文件等需要在使用后关闭。这些操作都应该放在 finally 代码块里面,防止异常情况发生而没有调用关闭资源的代码。

错误代码示例:

private void readTheFile() throws IOException {

Path path = Paths.get(this.fileName);

BufferedReader reader = Files.newBufferedReader(path, this.charset);

// ...

reader.close(); // Noncompliant

// ...

Files.lines("input.txt").forEach(System.out::println); // Noncompliant: The stream needs to be closed

}

直接在方法里面 new 一个资源,这是不对的,因为在 new 后很可能抛出异常,之后的代码都不会执行导致资源没有正确的关闭从而导致资源泄漏。

错误代码示例:

FileInputStream fileInputStream = null;

try {

// do sth

fileInputStream = new FileInputStream("222");

} catch (FileNotFoundException e) {

e.printStackTrace();

} finally {

fileInputStream.close();

}

fileInputStream 有可能为 null,有潜在的空指针异常存在。应该加上非空判断。加上非空判断后就是最标准的 IO 流处理了。

FileInputStream fileInputStream = null;

try {

// do sth

fileInputStream = new FileInputStream("222");

} catch (FileNotFoundException e) {

e.printStackTrace();

} finally {

if(fileInputStream != null){

fileInputStream.close();

}

}

以上的代码还是略显繁杂,jdk 1.7 增加了 try-with-resource 的新语法糖,编译后的字节码和上面的代码等效。但代码量和可阅读性缺大大增加。

try-with-resource 实例:

// do sth

try (FileInputStream fileInputStream = new FileInputStream("222")) {

} catch (FileNotFoundException e) {

e.printStackTrace();

}

写法上就是在 try 后面的括号里面定义资源对象。这些由于都继承了 AutoCloseable 接口,所以会在方法结束前自动关闭资源的占用。题外话 Closeable 接口要求实现者实现幂等关闭操作。AutoCloseable 则没有这个强制要求。

推荐使用 IDEA,这些代码上的潜在问题都会提示你,在代码上按 Alt + Enter 就可以快速安全重构了。

BigDecimal 相关

一些 BigDecimal 相关的操作使用不当也会导致严重 bug,尤其是涉及金钱类的。下面看几个例子。

sonar 规则:

Because of floating point imprecision, you're unlikely to get the value you expect from the `BigDecimal(double)` constructor.

From [the JavaDocs](http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#BigDecimal(double)):

> The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625\. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.

Instead, you should use `BigDecimal.valueOf`, which uses a string under the covers to eliminate floating point rounding errors, or the constructor that takes a `String` argument.

sonar 提示我们,如果使用 double 类型的变量作为构造函数的参数使用会丢失精度。而使用 BigDecimal.valueOf 和使用 String 类型的参数则没有这个问题。

错误代码示例:

BigDecimal monthBudget = null;

if (montBudgetObj == null) {

monthBudget = BigDecimal.ZERO;

} else {

monthBudget = new BigDecimal(Double.parseDouble(montBudgetObj.toString()));

}

正确示例:

monthBudget = new BigDecimal(montBudgetObj.toString());

还有一个经常被忽略的就是 BigDecimal 的 add 方法返回的结果是需要接收的,不是直接改变原来的变量的。因为 BigDecimal 是不可变类型。

正确示例:

BigDecimal amount = BigDecimal.ZERO;

amount = amount.add(journal.getReceiptAmount());

总结

以上两个是比较常见而且在编码阶段比较容易忽略的,借助 sonar 等静态代码扫描工具能够有效的保证我们代码的健壮和可读性。文中提到的知识冰山一角,像空指针异常这种其实才是最难发现的,也是 sonar 扫描带来最大的价值。大家感兴趣也可以参照本文实践一下。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值