这样规范写代码,同事直呼“666”

做者:涛姐涛哥
来源:https://www.cnblogs.com/taojietaoge/p/11575376.html
复制代码

上一篇:阿里规定超过3张表,禁止join,为什么?html

1、MyBatis 不要为了多个查询条件而写 1 = 1

当遇到多个查询条件,使用where 1=1 能够很方便的解决咱们的问题,可是这样极可能会形成很是大的性能损失,由于添加了 “where 1=1 ”的过滤条件以后,数据库系统就没法使用索引等查询优化策略,数据库系统将会被迫对每行数据进行扫描(即全表扫描) 以比较此行是否知足过滤条件,当表中的数据量较大时查询速度会很是慢;此外,还会存在SQL 注入的风险。java

反例:git

<select id="queryBookInfo" parameterType="com.tjt.platform.entity.BookInfo" resultType="java.lang.Integer">
    select count(*) from t_rule_BookInfo t where 1=1
    <if test="title !=null and title !='' ">
        AND title = #{title} 
    </if> 
    <if test="author !=null and author !='' ">
      AND author = #{author}
    </if> 
</select>

复制代码

正例:程序员

<select id="queryBookInfo" parameterType="com.tjt.platform.entity.BookInfo" resultType="java.lang.Integer">
    select count(*) from t_rule_BookInfo t
    <where>
        <if test="title !=null and title !='' ">
            title = #{title} 
        </if>
        <if test="author !=null and author !='' "> 
            AND author = #{author}
        </if>
    </where> 
</select>
复制代码

UPDATE 操做也同样,能够用标记代替 1=1。面试

2、迭代entrySet() 获取Map 的key 和value

当循环中只须要获取Map 的主键key时,迭代keySet() 是正确的;可是,当须要主键key 和取值value 时,迭代entrySet() 才是更高效的作法,其比先迭代keySet() 后再去经过get 取值性能更佳。正则表达式

反例:数据库

//Map 获取value 反例:
HashMap<String, String> map = new HashMap<>();
for (String key : map.keySet()){
    String value = map.get(key);
} 
复制代码

正例:后端

//Map 获取key & value 正例:
HashMap<String, String> map = new HashMap<>();
for (Map.Entry<String,String> entry : map.entrySet()){
    String key = entry.getKey();
    String value = entry.getValue();
} 

复制代码

3、使用Collection.isEmpty() 检测空

使用Collection.size() 来检测是否为空在逻辑上没有问题,可是使用Collection.isEmpty() 使得代码更易读,而且能够得到更好的性能;除此以外,任何Collection.isEmpty() 实现的时间复杂度都是O(1) ,不须要屡次循环遍历,可是某些经过Collection.size() 方法实现的时间复杂度多是O(n)数组

反例:bash

LinkedList<Object> collection = new LinkedList<>();
if (collection.size() == 0){
    System.out.println("collection is empty.");
}
复制代码

正例:

LinkedList<Object> collection = new LinkedList<>();
if (collection.isEmpty()){
    System.out.println("collection is empty.");
}

//检测是否为null 可使用CollectionUtils.isEmpty()
if (CollectionUtils.isEmpty(collection)){
    System.out.println("collection is null.");
}
复制代码

4、初始化集合时尽可能指定其大小

尽可能在初始化时指定集合的大小,能有效减小集合的扩容次数,由于集合每次扩容的时间复杂度极可能时O(n),耗费时间和性能。

反例:

//初始化list,往list 中添加元素反例:
int[] arr = new int[]{1,2,3,4};
List<Integer> list = new ArrayList<>();
for (int i : arr){
    list.add(i);
}
复制代码

正例:

//初始化list,往list 中添加元素正例:
int[] arr = new int[]{1,2,3,4};
//指定集合list 的容量大小
List<Integer> list = new ArrayList<>(arr.length);
for (int i : arr){
    list.add(i);
}
复制代码

5、使用StringBuilder 拼接字符串

通常的字符串拼接在编译期Java 会对其进行优化,可是在循环中字符串的拼接Java 编译期没法执行优化,因此须要使用StringBuilder 进行替换。

反例:

//在循环中拼接字符串反例
String str = "";
for (int i = 0; i < 10; i++){
    //在循环中字符串拼接Java 不会对其进行优化
    str += i;
}
复制代码

正例:

//在循环中拼接字符串正例
String str1 = "Love";
String str2 = "Courage";
String strConcat = str1 + str2;  //Java 编译器会对该普通模式的字符串拼接进行优化
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++){
   //在循环中,Java 编译器没法进行优化,因此要手动使用StringBuilder
    sb.append(i);
}
复制代码

6、若需频繁调用Collection.contains 方法则使用Set

在Java 集合类库中,List的contains 方法广泛时间复杂度为O(n),若代码中须要频繁调用contains 方法查找数据则先将集合list 转换成HashSet 实现,将O(n) 的时间复杂度将为O(1)。

反例:

//频繁调用Collection.contains() 反例
List<Object> list = new ArrayList<>();
for (int i = 0; i <= Integer.MAX_VALUE; i++){
    //时间复杂度为O(n)
    if (list.contains(i))
    System.out.println("list contains "+ i);
}
复制代码

正例:

//频繁调用Collection.contains() 正例
List<Object> list = new ArrayList<>();
Set<Object> set = new HashSet<>();
for (int i = 0; i <= Integer.MAX_VALUE; i++){
    //时间复杂度为O(1)
    if (set.contains(i)){
        System.out.println("list contains "+ i);
    }
}
复制代码

7、使用静态代码块实现赋值静态成员变量

对于集合类型的静态成员变量,应该使用静态代码块赋值,而不是使用集合实现来赋值。

反例:

//赋值静态成员变量反例
private static Map<String, Integer> map = new HashMap<String, Integer>(){
    {
        map.put("Leo",1);
        map.put("Family-loving",2);
        map.put("Cold on the out side passionate on the inside",3);
    }
};
private static List<String> list = new ArrayList<>(){
    {
        list.add("Sagittarius");
        list.add("Charming");
        list.add("Perfectionist");
    }
};
复制代码

正例:

//赋值静态成员变量正例
private static Map<String, Integer> map = new HashMap<String, Integer>();
static {
    map.put("Leo",1);
    map.put("Family-loving",2);
    map.put("Cold on the out side passionate on the inside",3);
}

private static List<String> list = new ArrayList<>();
static {
    list.add("Sagittarius");
    list.add("Charming");
    list.add("Perfectionist");
}
复制代码

8、删除未使用的局部变量、方法参数、私有方法、字段和多余的括号。

9、工具类中屏蔽构造函数

工具类是一堆静态字段和函数的集合,其不该该被实例化;可是,Java 为每一个没有明肯定义构造函数的类添加了一个隐式公有构造函数,为了不没必要要的实例化,应该显式定义私有构造函数来屏蔽这个隐式公有构造函数。

反例:

public class PasswordUtils {
    //工具类构造函数反例
    private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);

    public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";

    public static String encryptPassword(String aPassword) throws IOException {
        return new PasswordUtils(aPassword).encrypt();
    }
}
复制代码

正例:

public class PasswordUtils {
//工具类构造函数正例
private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);

//定义私有构造函数来屏蔽这个隐式公有构造函数
private PasswordUtils(){}

public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";

public static String encryptPassword(String aPassword) throws IOException {
    return new PasswordUtils(aPassword).encrypt();
}
复制代码

10、删除多余的异常捕获并跑出

用catch 语句捕获异常后,若什么也不进行处理,就只是让异常从新抛出,这跟不捕获异常的效果同样,能够删除这块代码或添加别的处理。

反例:

//多余异常反例
private static String fileReader(String fileName)throws IOException{

    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
        String line;
        StringBuilder builder = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        return builder.toString();
    } catch (Exception e) {
        //仅仅是重复抛异常 未做任何处理
        throw e;
    }
}
复制代码

正例:

//多余异常正例
private static String fileReader(String fileName)throws IOException{

    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
        String line;
        StringBuilder builder = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        return builder.toString();
        //删除多余的抛异常,或增长其余处理:
        /*catch (Exception e) {
            return "fileReader exception";
        }*/
    }
}
复制代码

11、字符串转化使用String.valueOf(value) 代替 " " + value

把其它对象或类型转化为字符串时,使用String.valueOf(value) 比 ""+value 的效率更高。

反例:

//把其它对象或类型转化为字符串反例:
int num = 520;
// "" + value
String strLove = "" + num;
复制代码

正例:

//把其它对象或类型转化为字符串正例:
int num = 520;
// String.valueOf() 效率更高
String strLove = String.valueOf(num);
复制代码

12、避免使用BigDecimal(double)

BigDecimal(double) 存在精度损失风险,在精确计算或值比较的场景中可能会致使业务逻辑异常。

反例:

// BigDecimal 反例    
BigDecimal bigDecimal = new BigDecimal(0.11D);
复制代码

正例:

// BigDecimal 正例
BigDecimal bigDecimal1 = bigDecimal.valueOf(0.11D);
复制代码

十3、返回空数组和集合而非 null

若程序运行返回null,须要调用方强制检测null,不然就会抛出空指针异常;返回空数组或空集合,有效地避免了调用方由于未检测null 而抛出空指针异常的状况,还能够删除调用方检测null 的语句使代码更简洁。

反例:

//返回null 反例
public static Result[] getResults() {
    return null;
}

public static List<Result> getResultList() {
    return null;
}

public static Map<String, Result> getResultMap() {
    return null;
}
复制代码

正例:

//返回空数组和空集正例
public static Result[] getResults() {
    return new Result[0];
}

public static List<Result> getResultList() {
    return Collections.emptyList();
}

public static Map<String, Result> getResultMap() {
    return Collections.emptyMap();
}
复制代码

十4、优先使用常量或肯定值调用equals 方法

对象的equals 方法容易抛空指针异常,应使用常量或肯定有值的对象来调用equals 方法。

反例:

//调用 equals 方法反例
private static boolean fileReader(String fileName)throws IOException{

 // 可能抛空指针异常
 return fileName.equals("Charming");
}
复制代码

正例:

//调用 equals 方法正例
private static boolean fileReader(String fileName)throws IOException{

    // 使用常量或肯定有值的对象来调用 equals 方法
    return "Charming".equals(fileName);

    //或使用:java.util.Objects.equals() 方法
   return Objects.equals("Charming",fileName);
}
复制代码

十5、枚举的属性字段必须是私有且不可变

枚举一般被当作常量使用,若是枚举中存在公共属性字段或设置字段方法,那么这些枚举常量的属性很容易被修改;理想状况下,枚举中的属性字段是私有的,并在私有构造函数中赋值,没有对应的Setter 方法,最好加上final 修饰符。

反例:

public enum SwitchStatus {
    // 枚举的属性字段反例
    DISABLED(0, "禁用"),
    ENABLED(1, "启用");

    public int value;
    private String description;

    private SwitchStatus(int value, String description) {
        this.value = value;
        this.description = description;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}
复制代码

正例:

public enum SwitchStatus {
    // 枚举的属性字段正例
    DISABLED(0, "禁用"),
    ENABLED(1, "启用");

    // final 修饰
    private final int value;
    private final String description;

    private SwitchStatus(int value, String description) {
        this.value = value;
        this.description = description;
    }

    // 没有Setter 方法
    public int getValue() {
        return value;
    }

    public String getDescription() {
        return description;
    }
}
复制代码

十6、tring.split(String regex)部分关键字须要转译

使用字符串String 的plit方法时,传入的分隔字符串是正则表达式,则部分关键字(好比 .| 等)须要转义。

反例:

// String.split(String regex) 反例
String[] split = "a.ab.abc".split(".");
System.out.println(Arrays.toString(split));   // 结果为[]

String[] split1 = "a|ab|abc".split("|");
System.out.println(Arrays.toString(split1));  // 结果为["a""|""a""b""|""a""b""c"]

复制代码

正例:

// String.split(String regex) 正例
// . 须要转译
String[] split2 = "a.ab.abc".split("\\.");
System.out.println(Arrays.toString(split2));  // 结果为["a""ab""abc"]

// | 须要转译
String[] split3 = "a|ab|abc".split("\\|");
System.out.println(Arrays.toString(split3));  // 结果为["a""ab""abc"]
复制代码

热门内容:

一、历史文章分类导读列表!精选优秀博文都在这里了!》

二、优化后的 Spring Boot 启动究竟能有多快?

三、Spring 常犯的十大错误,这坑你踩过吗?

四、不说“分布式事务”理论,直接上大厂解决方案,绝对实用!

五、阿里巴巴程序员经常使用的 15 款开发者工具!你知道几个?

六、七个开源的 Spring Boot 先后端分离项目,必定要收藏!

七、用 Git 和 Github 提升效率的 10 个技巧!

八、警戒,MyBatis的size()方法居然有坑!

九、面试官:线程顺序执行,这么多答案你都答不上来?

十、手把手教你重构乱糟糟的代码

【视频福利】2T免费学习视频,搜索或扫描上述二维码关注微信公众号:Java后端技术(ID: JavaITWork),和20万人一块儿学Java!回复:1024,便可免费获取!内含SSM、Spring全家桶、微服务、MySQL、MyCat、集群、分布式、中间件、Linux、网络、多线程,Jenkins、Nexus、Docker、ELK等等免费学习视频,持续更新!

相关文章
相关标签/搜索