3 ms·
I would use records a lot more (pretty much everywhere) if I could easily derive new values from existing ones.
by bcrosby95 5y ago
I would use records a lot more (pretty much everywhere) if I could easily derive new values from existing ones.
- ivan_gammel 5y agoThere are some funny ways to work with records. I can recommend this article: https://benjiweber.co.uk/blog/2020/09/19/fun-with-java-records/ https://benjiweber.co.uk/blog/2020/09/19/fun-with-java-recor...
- stickfigure 5y agoStill way too much typing compared to lombok's @Value @With.
- BoyRobot777 5y agoThis will be solved[1]: 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/reconstruction-records-and-classes.md https://github.com/openjdk/amber-docs/blob/master/eg-drafts/...
- stickfigure 5y agoInteresting. It's ok. It seems like they're adding this syntax just to avoid extra copies eg, `p with {x = 3, y = 4}` instead of `p.withX(3).withY(4)`. I really don't mind the later. My gut feel is that records break encapsulation and will make refactoring slightly more difficult than the equivalent lombok value class. But if this gets more people making objects immutable, I'm all for it.
- samus 5y agoThe perfect transparency of the underlying data is rather the whole point of records. Tempered by immutability, records should be a useful tool for modeling data where encapsulation is not required. Note that it is still possible to add methods that can perform computation on the underlying data.
- ivan_gammel 5y agoTBH both approaches are just poor design of the object model. The one from my link is a clever but inefficient way to manipulate records (reflection), the one with Lombok is creating redundant interfaces without business meaning. A record with few business methods is lean enough and ensures that only valid transitions can happen.
- stickfigure 5y agoEh? This is pretty good: Colour changed = colour.withRed(5);
- ivan_gammel 5y agoEvery method of your API must serve some business purpose. "With" methods and setters generated or written "just in case" often do not have one or they are being used only in tests, which would be insufficient justification for having them. Does your code really need to change individual components of the color? If it is not a graphic editor, probably not and those methods will be redundant.
- stickfigure 5y agoThat sounds unpleasantly pedantic.