04-03.eri-test Java 14 Records :: Are we alive to see getters and setters die?

Aspirator, installer and end of Lombok project?

Photographer Mike Kennelly does not splash

If you try to teach Java for thousands of years or for someone who uses another less verbose language, you will often encounter resistance in writing getters, setters, to strings, equals and hashCode methods, and requiring a lot of boilerplate code.

Old-school developers will ignore it. We are just used to instructing the IDE to generate them for us.

But let's face it: we don't particularly like them. We just got used to them. We accepted the need for these methods, but to be honest: it may be different.

Java14 has started recording : a new type of preview function without using getter, setter, to string, equal and hashCode methods You can create an object with a few lines of code.

How does it work?

Since it is still a preview function, we should enable the preview function on the compiler, IDE and / or Maven.

Insummary records havethefollowingcharacteristics:

  • They are final and immutable.
  • They can implement the interface.
  • They can have static members.
  • They can define verification.
  • They can define default values.
  • They accept generics.

I have tested it and the project is available on my computer on GitHub.

All passed! \ o /

Final and unchanged

Please note that records do not have classic fetchers and setters, so once they are assigned, their values ​​cannot be modified.

Please note that in lines 34 to 38 below, the attribute is read without the "get" prefix. We use property names directly.

进口静态的组织。unit.断言.assertTrue;进口java.time.LocalDateTime;进口java.time.月;进口java.util.对象;进口org.junit.Test;进口com.danianepg.previewfeature.data.NationalHoli天;进口com.danianepg.previewfeature.data.记录s.庆祝通用唱片;进口com.danianepg.previewfeature.data.records.特殊日期;/** *测试类以验证记录的功能。 *@作者DanianeP.Gomes * */上市classRecordsDemoTest{私人的串名称=“我的生日”;私人的整数天=20;私人的月月=月.十月;私人的LocalDateTime被创造=LocalDateTime.现在();私人的串国家=“巴西”;私人的串nationalHoli天Name=“独立日”;私人的整数全国假日=7;私人的月全国假日月=月.九月;@测试上市虚空specialDateRecord_ok(){特殊日期myB天 = 特殊日期名称 被创造);布尔值 isNameEquals = myB天.名称()。等于名称);布尔值 isDayEquals = myB天.() == ;布尔值 is月Equals = myB天.() == ;布尔值 isCreatedEquals = myB天.被创造()。等于被创造);assertTrueisNameEquals && isDayEquals && is月Equals && isCreatedEquals);}@测试上市 虚空 specialDateRecord_equals_ok() {特殊日期 myB天 = 特殊日期名称 被创造);特殊日期 myBdayCopy = 特殊日期名称 day 被创造);assertTruemyBday.equalsmyBdayCopy));}@测试上市 虚空 specialDateRecord_alternativeConstructor() {特殊日期 myBday = 特殊日期名称 day );布尔值 isCreatedNotNull = Objects.一片空白myBday.被创造());assertTrueisCreatedNotNull);}@测试预期 = IllegalArgumentException.class上市 虚空 specialDateRecord_exceptionWhenDayOutOfTheRange() {尝试 { 特殊日期名称 32 );} 抓住 IllegalArgumentException e {系统..打印“消息异常:”+e.getMessage()); e;}}@测试上市 虚空 庆祝通用唱片_ok() {庆祝通用唱片<法定假日> dateGenericClassic = CelebrationGenericRecord<>( 法定假日国家), nationalHolidayName 全国假日 全国假日月);布尔值 isInstanceOf法定假日 = dateGenericClassic.内容() 实例 法定假日;布尔值 isCountryEquals = ;如果 isInstanceOf法定假日 {NationalHoliday dateClassic = NationalHoliday dateGenericClassic.内容();isCountryEquals = dateClassic.getCountry()。equals国家);}assertTrueisInstanceOfNationalHoliday && isCountryEquals);} }

Interface, static member, authentication, default

The record is compatible with our classic interface. Check the record "Special Date" that implements the interface "CelebrationInterface", and therefore override the method "totalDates ()". Note lines 13 and 48.

For additional static members, please check line 18.

To verify, check line 28.

To get the default value, check the alternate constructor on line 41, which assigns the current date and time to the created object, even if the object is not notified during the creation of the record object.

 com.danianepg.previewfeature.data.records;

进口 java.time.LocalDateTime;
进口 java.time.Month;

进口 com.danianepg.previewfeature.interfaces.CelebrationInterface;

/ **
  *实现接口,验证数据,传递默认值以及使用额外的静态属性和方法的记录示例。
  * @作者Daniane P. Gomes
  *
  * /
上市 record 特殊日期 name 整数 day Month  LocalDateTime 被创造 实施 CelebrationInterface {/ **
      *其他静态成员
      * /私人的 static int totalDates;/ **
      *定义属性的验证
      * @参数名称
      * @参数日
      * @参数月份
      * @param创建
      * /上市 SpecialDate {如果 day < 1 || day > 31 {  IllegalArgumentException“日期必须在间隔1-31上。”);}totalDates++;}/ **
      *额外的构造函数,为属性“ created”分配默认值
      * @参数名称
      * @参数日
      * @参数月份
      * /上市 SpecialDateString name 整数 day Month  {这个name day  LocalDateTime.现在());}/ **
      *检索的其他公共方法
      * /上市 int totalDates() {返回 totalDates;}

}

Generic

The record is flexible and can accept generics! The definition can be found below, and examples of how to use it can be found in the test "celebrationGenericRecord_ok ()" of class " RecordsDemoTest ".

 com.danianepg.previewfeature.data.records;

进口 java.time.Month;

/**
 * Generic record
 * @author Daniane P. Gomes
 *
 * @param <T>
 */
上市 record CelebrationGenericRecord<T>(T 内容 String name 整数 day Month  {
}

Why is this useful?

Short answer: data for operators.

Long answer: Now, we can declare a simple data transfer object with a few lines of code without having to satisfy all the rituals we are used to in Java, which means CLEAN code!

Since logging is compatible with other important Java features, I am happy to start using it. Deleting redundant code on the project made me very satisfied.

in conclusion

Ok ... does this end for our beloved pet method getters and getters? Um ... obviously not yet.

Because records are immutable, they cannot simply replace our classic classes. In addition, another problem to be solved is how compatible are they with frameworks such as Hibernate and Spring?

However, they will help us write code cleaners and the smaller Ben Evans said that in some cases, they can even eliminate the need for external libraries such as Lombok. Java Magazine :

“This will help many applications make domain classes clearer and smaller. It will also help teams eliminate many hand-coded implementations of the underlying pattern and reduce or remove the need for libraries 喜欢 Lombok.”

However, please remember that this is a preview function, the document reminder :

"The preview function may be removed in a future version or upgraded to a permanent feature in the Java language."

I hope they keep it. Fingers crossed.

references

Jeep 359: Record (Preview)

Record (Java SE 14 & JDK 14)

Record came to Java

Originally posted on my mid-sized page .

from: https://dev.to//danianepg/java-14-records-did-we-live-to-see-getters-and-setters-die-350e

Published 0 original articles · liked 0 · visits 124

Guess you like

Origin blog.csdn.net/cunbang3337/article/details/105560300