Sitemap

Member-only story

đźš« Stop Writing Boilerplate DTOs: Use Java Records Instead

3 min readApr 16, 2025

In most Java applications, especially those following clean architecture or layered design, you’ll find dozens of DTOs (Data Transfer Objects) that exist just to carry data between layers.

These DTOs are often filled with boilerplate: fields, constructors, getters, equals(), hashCode(), and toString() — repeated again and again.

But there’s a cleaner, more modern alternative introduced in Java 14 (finalized in Java 16): records.

In this article, you’ll learn why Java records are the best way to replace boilerplate DTOs, and how to refactor your code to use them effectively.

đź’ˇ What Is a DTO?

A DTO (Data Transfer Object) is a simple class used to carry data between layers — for example:

  • Client -> Server (REST API)
  • Controller → Service
  • Java → JSON (in REST APIs)

DTOs should not contain any business logic — just plain data.

❌ The Problem: Boilerplate in Classic DTOs

Let’s look at a typical Java DTO:

public class UserDTO {
private String name;
private String email;

public UserDTO(String name, String email) {
this.name = name;
this.email = email;
}

public String getName() {
return name;
}

public String getEmail() {
return email;
}

@Override
public boolean equals(Object o) {
// implementation
}

@Override
public int hashCode() {
// implementation
}

@Override
public String toString() {
return "UserDTO{name=" + name + ", email=" + email + "}";
}
}

This is just for 2 fields — imagine writing this for every entity.

âś… The Solution: Java Records

Records are a concise way to declare immutable data classes in Java.

Refactored DTO using record:

public record UserDTO(String name, String email) {}

✅ That’s it. No getters, constructors, or overrides needed — it’s all auto-generated by the compiler.

đź§± What Makes Records Ideal for DTOs?

--

--

No responses yet