关于java:这16条规范代码同事拍桌子-大喊-666

7次阅读

共计 8056 个字符,预计需要花费 21 分钟才能阅读完成。

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

当遇到多个查问条件,应用 where 1=1 能够很不便的解决咱们的问题,然而这样很可能会造成十分大的性能损失,因为增加了“where 1=1”的过滤条件之后,数据库系统就无奈应用索引等查问优化策略,数据库系统将会被迫对每行数据进行扫描(即全表扫描)以比拟此行是否满足过滤条件,当表中的数据量较大时查问速度会十分慢;此外,还会存在 SQL 注入的危险。

反例:

<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。

二、迭代 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();}
复制代码 

三、应用 Collection.isEmpty() 检测空

应用 Collection.size() 来检测是否为空在逻辑上没有问题,然而应用 Collection.isEmpty() 使得代码更易读,并且能够取得更好的性能;除此之外,任何 Collection.isEmpty() 实现的工夫复杂度都是 O(1),不须要屡次循环遍历,然而某些通过 Collection.size() 办法实现的工夫复杂度可能是 O(n)

反例:

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.");
}
复制代码 

四、初始化汇合时尽量指定其大小

尽量在初始化时指定汇合的大小,能无效缩小汇合的扩容次数,因为汇合每次扩容的工夫复杂度很可能时 O(n),消耗工夫和性能。

反例:

// 初始化 list,往 list 中增加元素反例:int[] arr = new int[]{1,2,3,4};

List<Integer> list = newArrayList<>();

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);

}
复制代码 

五、应用 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);

}
复制代码 

六、若需频繁调用 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);

}

}
复制代码 

七、应用动态代码块实现赋值动态成员变量

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

反例:

// 赋值动态成员变量反例

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");

}
复制代码 

八、删除未应用的局部变量、办法参数、公有办法、字段和多余的括号。

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

工具类是一堆动态字段和函数的汇合,其不应该被实例化;然而,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();}
复制代码 

用 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";}*/

}

}
复制代码 

十一、字符串转化应用 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);
复制代码 

十二、防止应用 BigDecimal(double)

BigDecimal(double) 存在精度损失危险,在准确计算或值比拟的场景中可能会导致业务逻辑异样。

反例:

// BigDecimal 反例

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

正例:

// BigDecimal 正例

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

十三、返回空数组和汇合而非 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();

}
复制代码 

十四、优先应用常量或确定值调用 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);

}
复制代码 

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

枚举通常被当做常量应用,如果枚举中存在公共属性字段或设置字段办法,那么这些枚举常量的属性很容易被批改;现实状况下,枚举中的属性字段是公有的,并在公有构造函数中赋值,没有对应的 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;}

}
复制代码 

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

应用字符串 String 的 plit 办法时,传入的分隔字符串是正则表达式,则局部关键字(比方 .[]()| 等)须要本义。2021 金三银四 Java 面试宝典

反例:

// 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"]

参考:《2020 最新 Java 根底精讲视频教程和学习路线!》

链接:https://juejin.cn/post/692428…

正文完
 0