[关闭]
@ZeroGeek 2016-07-18T08:49:04.000000Z 字数 4896 阅读 1564

Sonar建议代码质量 Note

未分类


  1. if语句注意合并
  2. static final 变量 大写
  3. switch 语句 要包含 default
  4. 集合和map判断建议:
  1. public static boolean isEmpty(Collection<?> collection){
  2. return collection == null || collection.isEmpty();
  3. }
  4. public static boolean isEmpty(Map map){
  5. return map == null || map.isEmpty();
  6. }
    5.
  1. double d = 1.1;
  2. BigDecimal bd1 = new BigDecimal(d); // Noncompliant; see comment above
  3. BigDecimal bd2 = new BigDecimal(1.1); // Noncompliant; same result
  4. Compliant Solution
  5. double d = 1.1;
  6. BigDecimal bd1 = BigDecimal.valueOf(d);
  7. BigDecimal bd2 = BigDecimal.valueOf(1.1);
  1. clone,compareTo,equals
  2. final class,不要包含protect成员

冗余代码

  1. private void closeCursor(Cursor c) {
  2. if (c != null) {
  3. if (!c.isClosed()) {
  4. c.close();
  5. c = null; // 多余
  6. }
  7. } else {
  8. c = null; // 多余
  9. }
  10. }
  1. private void delShareAccBook(AccountBookVo shareAccBook){
  2. if(shareAccBook!=null){
  3. try {
  4. AccountBookManager.getInstance().deleteAccountBook(shareAccBook);
  5. } catch (AccountBookException e) {
  6. DebugUtil.exception(TAG, e);
  7. }
  8. shareAccBook = null; // 多余
  9. }
  10. }
  1. 使用 String 和 List 的 indexOf 最好将它和 -1 来比较, 0 是一个有效数字.
  2. 遍历map 集合 ,如果只需 key 使用 keySet , 否则 entrySet()
  1. public void doSomethingWithMap(Map<String,Object> map) {
  2. for (String key : map.keySet()) { // Noncompliant; for each key the value is retrieved
  3. Object value = map.get(key);
  4. // ...
  5. }
  6. }
  7. public void doSomethingWithMap(Map<String,Object> map) {
  8. for (Map.Entry<String,Object> entry : map.entrySet()) {
  9. String key = entry.getKey();
  10. Object value = entry.getValue();
  11. // ...
  12. }
  13. }
  1. 不建议使用public static ,添加 final 或者 改为私有
  1. public static CreditsListener creditsListener; // 暴露了接口
  1. BaseApplication.java
  2. /**
  3. * 全局缓存,终端修改 删除新增账单均要填写ffrom字段,内容是终端类型+产品名称+版本号+"操作类型",交易增删改时填写
  4. */
  5. public static String TRANS_FFROM_INSERT = "";
  6. public static String TRANS_FFROM_UPDATE = "";
  7. public static String TRANS_FFROM_DELETE = "";
  8. // 这种情况,建议提供静态方法对其读取或者复制
  1. abstract class , 应该包含不完全的抽象方法。如果不包含字段,应该定义为Interface,否则定义为具体的类。
  2. 抽象类命名 “AbstractXXX”

  3. Looks for methods named "getX()" with "boolean" as the return type. The convention is to name these methods "isX()".

  4. Catches should be combined

  1. catch (IOException e) {
  2. doCleanup();
  3. logger.log(e);
  4. }
  5. catch (SQLException e) { // Noncompliant
  6. doCleanup();
  7. logger.log(e);
  8. }
  9. catch (TimeoutException e) { // Compliant; block contents are different
  10. doCleanup();
  11. throw e;
  12. }
  13. Compliant Solution
  14. catch (IOException|SQLException e) {
  15. doCleanup();
  16. logger.log(e);
  17. }
  18. catch (TimeoutException e) {
  19. doCleanup();
  20. throw e;
  21. }
  1. Classes without "public" constructors should be "final", 带私有够造函数的类,应该定义为final,防止被继承。
  2. Resources should be closed :在try{}finally { // do }
  3. Android - call super first, 根据周期来调用
  4. 局部变量尽量避免使用final类型
  5. 建议用同步语句块来替代同步方法,避免修改方法时产生冲突
  6. if语句后加括号,哪怕是一句

  7. "BigDecimal(double)" should not be used

  1. public static void main(String[] args) {
  2. BigDecimal d1 = new BigDecimal(0.1);
  3. BigDecimal d2 = BigDecimal.valueOf(0.1); // 推荐用法
  4. if (d1.equals(d2)) {
  5. System.out.print("==");
  6. } else {
  7. System.out.print("!="); // 执行结果
  8. }
  9. }
  1. "Cloneables" should implement "clone"
  2. "enum" fields should not be publicly mutable
    错误用法:公有成员变量,公有的set方法

  3. "equals" methods should be symmetric and work for subclasses

  1. if (this.getClass() == obj.getClass()) {
  2. return ripe.equals(((Fruit)obj).getRipe());
  3. }
  1. 工具类,应该使用私有构造函数
  1. // Noncompliant Code Example
  2. class StringUtils { // Noncompliant
  3. public static String concatenate(String s1, String s2) {
  4. return s1 + s2;
  5. }
  6. }
  7. // Compliant Solution
  8. class StringUtils { // Compliant
  9. private StringUtils() {
  10. throw new IllegalAccessError("Utility class");
  11. }
  12. public static String concatenate(String s1, String s2) {
  13. return s1 + s2;
  14. }
  15. }
  1. 方法的参数建议用可变列表参数 替代 数组参数

  2. 预防空指针引起漰溃
    78 处, 以下是示例

  1. @CheckForNull
  2. String getName(){...}
  3. public boolean isNameEmpty() {
  4. return getName().length() == 0; // Noncompliant; the result of getName() could be null, but isn't null-checked
  5. }
  1. Connection conn = null;
  2. Statement stmt = null;
  3. try{
  4. conn = DriverManager.getConnection(DB_URL,USER,PASS);
  5. stmt = conn.createStatement();
  6. // ...
  7. }catch(Exception e){
  8. e.printStackTrace();
  9. }finally{
  10. stmt.close(); // Noncompliant; stmt could be null if an exception was thrown in the try{} block
  11. conn.close(); // Noncompliant; conn could be null if an exception was thrown
  12. }
  1. private void merge(@Nonnull Color firstColor, @Nonnull Color secondColor){...}
  2. public void append(@CheckForNull Color color) {
  3. merge(currentColor, color); // Noncompliant; color should be null-checked because merge(...) doesn't accept nullable parameters
  4. }
  1. 判断的正确与优化,(|| ,&&)
  2. 当某操作返回的是一个boolean,应该判断是否操作成功,并处理不成功的逻辑
  3. Math should not be performed on floats
    For small numbers, float math has enough precision to yield the expected value, but for larger numbers, it does not. BigDecimal is the best alternative, but if a primitive is required, use a double.
  1. float a = 16777216.0f;
  2. float b = 1.0f;
  3. float c = a + b; // Noncompliant; yields 1.6777216E7 not 1.6777217E7
  4. double d = a + b; // Noncompliant; addition is still between 2 floats
  1. float a = 16777216.0f;
  2. float b = 1.0f;
  3. BigDecimal c = BigDecimal.valueOf(a).add(BigDecimal.valueOf(b));
  4. double d = (double)a + (double)b;
  1. Mutable fields should not be "public static"
    集合类的成员变量应该设置为 protected 或者 private 而不是 public static

  2. Mutable members should not be stored or returned directly

  1. class A {
  2. private String [] strings;
  3. public A () {
  4. strings = new String[]{"first", "second"};
  5. }
  6. public String [] getStrings() {
  7. return strings; // Noncompliant
  8. }
  9. public void setStrings(String [] strings) {
  10. this.strings = strings; // Noncompliant
  11. }
  12. }
  13. public class B {
  14. private A a = new A(); // At this point a.strings = {"first", "second"};
  15. public void wreakHavoc() {
  16. a.getStrings()[0] = "yellow"; // a.strings = {"yellow", "second"};
  17. }
  18. }
  1. Null should not be returned from a "Boolean" method
  2. 返回值是集合或者数组,如果返回的是空集合或者空数组,不要返回null,应该使用Collections.emptyList()等方法
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注