Java developers would gain an easier way to create records, and more streamlined code for declaring record classes, through derived record creation, a preview language feature being considered by the OpenJDK community.Derived record creation would allow developers to create new records from existing records, specifying only the components that are different. Goals of the proposal include providing a concise means to create new record values from existing ones and streamlining the declaration of record classes by eliminating the need to provide explicit wither methods, which are the immutable analogue of setter methods.Underlying the proposal is the notion that immutability is a powerful technique for creating safe, reliable code that is easy to reason about. Writing immutable classes in Java traditionally was a tedious exercise involving lots of boilerplate, but record classes introduced in JDK 16 make it easy to declare immutable, data-centric classes.Immutability of record classes ensures predictability and safety and enables features that make them easy to use, including canonical constructors, accessor methods, and well-defined Objectcode methods. However, the systems that developers need to model still have state, and it can be cumbersome to evolve state modeled by record classes, the proposal notes. A better way to derive new record values from old record values would be to let developers focus on transforming components and have the Java compiler handle deconstruction and instantiation of record values automatically.Created in late-November of 2023 and updated February 28, the derived record creation proposal would become part of Java Standard Edition. No specific version has been named as the recipient. Coming up with derived creation expressions for ordinary, non-record values is not a goal of the current proposal, but may be the subject of a future JDK enhancement proposal.
Copyright © 2024 IDG Communications, Inc.
Source link