zoukankan      html  css  js  c++  java
  • java代码审查

    1.工具类或者常量类里面的方法都是静态的,建议直接用类名调用,不用创建对象,所以将构造方法私有化,禁止创建对象

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    //error example:
    public class StringUtils{
    /**
    * 判断一个字符串是否为英文中文或数字
    *
    * @param str
    * @return
    */
    public static boolean isLetterDigitOrChinese( String str ) {
    String regex = "^[a-z0-9A-Zu4e00-u9fa5]+$";
    return str.matches( regex );
    }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    //right example:
    public class StringUtils{
    //添加构造私有构造方法
    private StringUtils{
    }
    /**
    * 判断一个字符串是否为英文中文或数字
    *
    * @param str
    * @return
    */
    public static boolean isLetterDigitOrChinese( String str ) {
    String regex = "^[a-z0-9A-Zu4e00-u9fa5]+$";
    return str.matches( regex );
    }
    }

    2.NPE(空指针异常)-equals

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    //error
    String testString="abc";
    if(testString.equals("abc")){
    大专栏  java代码审查v class="line">
    }else{
    }
    //right
    String testString="abc";
    if("abc".eqauls(testString)){
    //code
    }else{
    //code
    }

    3.map list 新建 (java 1.7 )

    1
    2
    3
    4
    5
    6
    7
    // Noncompliant
    List<String> strings = new ArrayList<String>();
    Map<String,List<Integer>> map = new HashMap<String,List<Integer>>();
    //Compliant Solution
    List<String> strings = new ArrayList<>();
    Map<String,List<Integer>> map = new HashMap<>();

    4.使用isEmpty 来判断集合是否为空

    1
    2
    3
    4
    5
    6
    7
    8
    9
    //Noncompliant
    if(data.size==0){
    }
    //compliant
    if(data.isEmpty){
    }

    5.数组定义 (“[]” 在变量名字前面)

    1
    2
    3
    4
    5
    //Noncompliant
    int arr[]={};
    //compliant
    int[] arr={};

    6.字符串转换为数字

    1
    2
    3
    4
    5
    6
    //Noncompliant
    String numString="12222222";
    long numLong=Long.valueOf(numString);
    //compliant
    String numString="12222222";
    long posNum=Long.parseLong( posMap.get( "num" ).toString());

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

  • 相关阅读:
    bash 教程 shell 基础语法
    使用 Flutter 开发 Windows 桌面应用 [MD]
    小tips:使用babelupgrade从babel6升级babel7
    JS的可选链操作符(?.)与双问号(??),你用到了吗?
    JS处理html的编码(encode)与解码(decode)
    pdf A3 到 A4
    grub4dos 制作U盘启动盘
    amixer的用法
    一个tomcat设置多个端口
    PostgreSQL 配置内存参数
  • 原文地址:https://www.cnblogs.com/lijianming180/p/12409931.html
Copyright © 2011-2022 走看看