by hashmash · 5y ago · 0 comments
A lot of the time, the software I'm working on has data objects that are really amalgamations of other fields. Example: "Address" is the street address, the city, the postal code, etc, etc. These sorts of objects should be immutable. Records are perfect for that.
If I need to add additional logic, methods, then you can add those to a record. But it continues to enforce that the state is immutable.
* tuples (complex numbers, points, dimensions, colors, IP addresses),
* database query results,
* stateless beans for DI frameworks where it cuts down on the verbosity of using constructor injection (actually a slight misuse)
* composite natural keys in database modeling
The immutability can help to enforce API contracts and proper service layering. A common problem in legacy code is modules communicating with each other by modifying objects that were passed as arguments.
Eventually, Project Valhalla will introduce the possibility to declare records as primitive, which will also reduce the overhead of Wither methods.
Edit: Building web APIs should also benefit from records because the argument and result types are only supposed to be created and read, not modified.
They reduce a lot of boilerplate, e.g. when passing multiple return values.
I know the answer is always use IDE and all but it causes more context switches than scrolling a bit to see types I created.
record Point(int x, int y) {}
Point p = new Point(1, 2); Point pp = p with { x = 3; }
[1] https://github.com/openjdk/amber-docs/blob/master/eg-drafts/...