Generic exceptions should never be thrown
Using such generic exceptions as Error, RuntimeException, Throwable, and Exception prevents calling methods from handling true, system-generated exceptions differently than application-generated errors.
不应该写成如下方式:
1 | public void foo(String bar) throws Throwable { // Noncompliant |
应该写成如下方式:
1 | public void foo(String bar) { |
Instance methods should not write to “static” fields
实例化方法不写静态字段。
优化前:
1 |
|
优化后:
1 | public static void setApplicationContextImpl(ApplicationContext context) { |
Neither “Math.abs” nor negation should be used on numbers that could be “MIN_VALUE”
Math.abs(Integer.MIN_VALUE)的值还是其本身。通过查阅Java的API文档,我们看到对abs(int a)运算,“如果参数等于 Integer.MIN_VALUE 的值(即能够表示的最小负 int 值),那么结果与该值相同且为负。
优化前:
1 | int newlineId = Math.abs(randomPointId.replaceAll("-", "").hashCode()); |
优化后:
1 | String hashedSourceId = sourceId.replaceAll("-", ""); |