Lombok!代码简洁神器还是代码“亚健康”元凶?
共 10132字,需浏览 21分钟
·
2021-09-07 09:21
爱的开始,恨的起源
public class MyObject{
private Long id;
private String name;
private int age;
private int gender;
public Long getId(){
return id;
}
public void setId(Long id){
this.id = id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
public int getGender(){
return gender;
}
public void setGender(int gender){
this.gender = gender;
}
@Override
public boolean equals(Object o){
if(this == o){
return true;
}
if(o == null || getClass() != o.getClass()){
return false;
}
MyObject obj = (MyObject) o;
return age = obj.age &&
gender = obj.gender &&
Objects.equals(id,obj.id) &&
Objects.queals(name,obj.name);
}
@Override
public int hashCode(){
return Objects.hash(id,name,age,gender);
}
@Override
public String toString(){
return "MyObject{"+
"id="+id+
"name="+name+
"age="+age+
"gender="+gander+
"}";
}
}
@Getter
和@Setter
注解后,代码会像下面这样看起来很苗条:@Getter
@Setter
public class MyObject{
private Long id;
private String name;
private int age;
private int gender;
@Override
public boolean equals(Object o){
if(this == o){
return true;
}
if(o == null || getClass() != o.getClass()){
return false;
}
MyObject obj = (MyObject) o;
return age = obj.age &&
gender = obj.gender &&
Objects.equals(id,obj.id) &&
Objects.queals(name,obj.name);
}
@Override
public int hashCode(){
return Objects.hash(id,name,age,gender);
}
@Override
public String toString(){
return "MyObject{"+
"id="+id+
"name="+name+
"age="+age+
"gender="+gander+
"}";
}
}
@EqualsAndHashCod
注解替换到equals和hashCode方法:@Getter
@Setter
@EqualsAndHashCode
public class MyObject{
private Long id;
private String name;
private int age;
private int gender;
@Override
public String toString(){
return "MyObject{"+
"id="+id+
"name="+name+
"age="+age+
"gender="+gander+
"}";
}
}
@ToString
注解去掉对于的方法:@Getter
@Setter
@EqualsAndHashCode
@ToString
public class MyObject{
private Long id;
private String name;
private int age;
private int gender;
}
@Data
,可以替换掉类名头上那坨像翔一样的东西:@Data
public class MyObject{
private Long id;
private String name;
private int age;
private int gender;
}
@Slf4j
,@NoArgsConstructor
,@AllArgsConstructor
等等,介绍Lombok用法不是本文重点。扭曲的审美,爱的隐患
1. JDK版本问题
2. 胁迫使用
3. 可读性差
@AllArgsConstructor
注解,它将提供一个巨型构造器,让外界有机会在初始化对象时修改类中所有的属性。首先,这是极其不安全的,因为类中某系属性我们是不希望被修改的;另外,如果某个类中有几十个属性存在,就会有一个包含几十个参数的构造器被Lombok注入到类中,这是不理智的行为;其次,构造器参数的顺序完全由Lombok所控制,我们并不能操控,只有当你需要调试时才发现有一个奇怪的“小强”在等着你;最后,在运行代码之前,所有JavaBean中的方法你只能想象他们长什么样子,你并不能看见。4. 代码耦合度增加
5. 得不偿失
总结
有道无术,术可成;有术无道,止于术
欢迎大家关注Java之道公众号
好文章,我在看❤️