HeadlinesBriefing favicon HeadlinesBriefing.com

Ruby 3.2 Favors Data.define for DTOs

DEV Community •
×

Ruby 3.2 introduces Data.define as the new standard for creating Data Transfer Objects, effectively replacing the aging Struct class. This shift addresses long-standing issues with Struct, which has quirks that complicate pure data transfer. The new class factory is purpose-built to create simple, immutable "Value Objects" that behave predictably across complex application architectures.

Unlike Struct, Data objects are immutable by design, preventing accidental side effects when data moves through different layers of an application. Developers gain flexible initialization supporting both positional and keyword arguments, alongside automatic value equality checks. These objects also integrate seamlessly with Ruby's modern pattern matching syntax, offering a cleaner, more robust interface for handling application state.

While Struct remains useful for mutable scratchpad objects or legacy environments, Data.define is the superior choice for modern stacks. It enforces strict data integrity and improves code readability. For developers building APIs or service layers, adopting this new standard ensures DTOs remain honest, predictable containers, free from the unexpected behaviors that plagued older implementations.