DEV Community

lou
lou

Posted on

4

DTO as a record

With DTOs we're dealing with immutable data more often than not, which means that once an object is created, we cannot change its content.

To accomplish this in Java, we create a class with private, final fields and public accessors.

Take a SpaceShipDTO class for example

final class SpaceShipDTO {
    final String name;
    final String description;
    final int weapons;

    public SpaceShip(String name, String description, int weapons) {
        this.name = name;
        this.description = description;
        this.weapons = weapons;

    }
    String getName() { return name; }
    double getDescription() { return description; }
    double getWeapons() { return weapons; }

}
Enter fullscreen mode Exit fullscreen mode

We can easily replace this with a record

record SpaceShipDTO(String name, String description, int weapons){ }

Enter fullscreen mode Exit fullscreen mode

This record automatically creates 3 private final fields, public accessor methods, a constructor and implementations of equals(), hashCode(), and toString() methods, all generated by the Java compiler.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs