3 ms·
Another problem with struct approach is inconsistency. Sometimes you want a computed property and you use non-trivial getter. Sometimes you want to do some wor
by vbezhenar 11y ago
Another problem with struct approach is inconsistency.
Sometimes you want a computed property and you use non-trivial getter. Sometimes you want to do some work in setter. And then client's code will look terrible: point.x * point.x + point.getY() * point.getY(). There are other problems: binary incompatibility; non-trivial refactoring when I need to introduce a getter or setter.
Java really need lightweight property syntax which would solve all those problems. I don't understand why it isn't introduced yet.
- logn 11y ago> Sometimes you want a computed property and you use non-trivial getter Then pre-compute it, make it immutable, and expose the variable. And if that ends up being too hard it's probably because you need a builder and/or to group your properties into smaller classes.
- barrkel 11y agoPrecomputing properties on a hundred million object instances is not cheap.
- jimueller 11y agoGoing from C# to Java, one of the biggest things I miss is the Property syntax.
- iconhacker 11y agoC# property shares its own set of issues , especially when there are exceptions involved.
- zmmmmm 11y agoThe lack of simple property syntax is probably the main reason I keep using Groovy now that Java 8 has arrived. Yes, state is evil. But there are still plenty of situations where you are just schlepping data around and generating thousands of lines of boilerplate to achieve simple data transfer is such a pointless and ugly hack.
- cam- 11y agoFor DTOs we don't user mutators. Just public member variables. It is the only way to keep business logic out of them. That being said, I wish Java has some object/struct syntactic sugar like Javascript Object Literals. They are so powerful.
- jay-anderson 11y agoProjects exist to to make a light weight property syntax. The most prominent might be @Getter and @Setter from lombok (https://projectlombok.org/ https://projectlombok.org/), but there are others which have similar goals (e.g. http://immutables.github.io/ http://immutables.github.io/, https://github.com/google/auto https://github.com/google/auto). That said, I agree that java _really_ needs something like this built in.
- PascalW 11y agoI'm surprised I haven't seen anybody mention the "public final fields" approach yet. I use this myself for immutable objects and I quite like it. Granted, you still need to implement equals and hashcode, but these can be generated easily and verified with tools like EqualsVerifier [2]. [1] public class MyImmutable { public final String field1; public final int field2; public MyImmutable(String field1, int field2) { // assign } // equals, hashcode, toString } [2] https://github.com/jqno/equalsverifier https://github.com/jqno/equalsverifier