ADR-08 Define-Dtos-As-Records
Context
DTO (Data Transfer Object) classes are used to transport data between layers or services. They do not contain any business logic, and their data is generated by the sender and processed by the receiver. Immutability is desirable for DTOs because it prevents unintended changes, improves thread safety, and reduces bugs. Once created, DTOs should not require write access.
Decision
DTOs are implemented as Java records, which are immutable by design and provide automatic implementations for equals
, hashCode
, and toString
. For flexible object creation, Lombok's @Builder
annotation is used, allowing to avoid using the all-arguments constructor or writing multiple constructors with reduced argument lists.
Consequences
- Immutability of DTOs reduces unwanted side effects and improves safety and predictability.
- The builder pattern allows for flexible and readable object creation, especially when objects are finalized in multiple steps or by different components.
- Developers must use the builder if object factories only partially fill the object and other components finalize it later.
- Records may have limitations compared to traditional classes (e.g., cannot extend other classes, only support final fields).