16 条 yyds 的代码规范
阅读本文大概需要 8.5 分钟。
作者:涛姐涛哥
来源:cnblogs.com/taojietaoge/p/11575376.html
如何更规范化编写Java 代码
<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 =
</if>
<if test="author !=null and author !='' ">
AND 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 =
</if>
<if test="author !=null and author !='' ">
AND author =
</if>
</where>
</select>
//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();
}
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);
}
//在循环中拼接字符串反例
String str = "";
for (int i = 0; i < 10; i++){
不会对其进行优化
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() 反例
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";
}*/
}
}
//把其它对象或类型转化为字符串反例:
int num = 520;
// "" + value
String strLove = "" + num;
//把其它对象或类型转化为字符串正例:
int num = 520;
// String.valueOf() 效率更高
String strLove = String.valueOf(num);
// BigDecimal 反例
BigDecimal bigDecimal = new BigDecimal(0.11D);
// BigDecimal 正例
BigDecimal bigDecimal1 = bigDecimal.valueOf(0.11D);
//返回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 方法反例
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);
}
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;
}
}
// 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"]
推荐阅读:
内容包含Java基础、JavaWeb、MySQL性能优化、JVM、锁、百万并发、消息队列、高性能缓存、反射、Spring全家桶原理、微服务、Zookeeper、数据结构、限流熔断降级......等技术栈!
⬇戳阅读原文领取! 朕已阅
评论