Hacker News new | ask | show | jobs
by ratww 1771 days ago
Java offers Records now, which are pretty much that.

Pretty cool feature IMO: https://docs.oracle.com/en/java/javase/14/language/records.h...

3 comments

What are the tradeoffs between records and structs?
From MS:

  You can use structure types to design data-centric types that provide value equality and little or no behavior. But for relatively large data models, structure types have some disadvantages:

  * They don't support inheritance.
  * They're less efficient at determining value equality. For value types, the `ValueType.Equals` method uses reflection to find all fields. For records, the compiler generates the `Equals` method. In practice, the implementation of value equality in records is measurably faster.
  * They use more memory in some scenarios, since every instance has a complete copy of all of the data. Record types are reference types, so a record instance contains only a reference to the data.
The biggest difference is that Records are Immutable.
structs can be made `readonly` as well. The biggest difference IMO is a record is still a class, so it's still copy-by-reference rather than copy-by-value, potentially giving performance gains when passing data around, and leaving a shortcut for value-comparisons (if two variables reference the same object, you obviously know it is the same).
Alternatively you could just make a final class with public member variables and no getters/setters and just treat it like a struct.
That's a great point, there's absolutely nothing wrong with public members if you only want a simple struct.
Records seems very nice! What I wonder is if people are going to use them, considering Java is a bit old at this point and lots of code already exists. Refactoring to use object would be a heavy cost. Maybe some new framework and ecosystems will appear based on new features of Java?
Refactoring to use them is not really hard, as they are easily interchangeable with regular classes. They are pretty much syntax sugar for this class pattern here: https://stackoverflow.com/a/63615514
That's true, but that's still a large refactoring to do, especially with going from mutability to immutability. The community might also just not like them.
On the other hand in some cases this type of refactoring might actually reveal design issues with the code, maybe even bugs.