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.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

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

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay