工作了一段时间,感觉自己代码很不规范,有很多冗余,比较乱,请问怎么针对性的改善代码规范?莫慌,这就来教你10条下饭的操作
一、MyBatis 不要为了多个查询条件而写 1 = 1
反例:
<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 获取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() 检测空
反例:
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.");
}
四、初始化集合时尽量指定其大小
反例:
//初始化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);
}
五、使用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
反例:
//频繁调用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");
}
八、删除未使用的局部变量、方法参数、私有方法、字段和多余的括号。
九、工具类中屏蔽构造函数
反例:
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();
}
十、删除多余的异常捕获并跑出
反例:
//多余异常反例
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";
}*/
}
}