4 ms·
Java offers Records now, which are pretty much that. Pretty cool feature IMO: https://docs.oracle.com/en/java/javase/14/language/records.html https://docs.orac
by ratww 5y ago
Java offers Records now, which are pretty much that.
Pretty cool feature IMO: https://docs.oracle.com/en/java/javase/14/language/records.html https://docs.oracle.com/en/java/javase/14/language/records.h...
- Zababa 5y agoRecords 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?
- ratww 5y agoRefactoring 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 https://stackoverflow.com/a/63615514
- Zababa 5y agoThat'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.
- dgb23 5y agoOn the other hand in some cases this type of refactoring might actually reveal design issues with the code, maybe even bugs.
- gnabgib 5y agoC# too, a very handy types https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record https://docs.microsoft.com/en-us/dotnet/csharp/language-refe...
- Zababa 5y agoWhat are the tradeoffs between records and structs?
- ratww 5y agoThe biggest difference is that Records are Immutable.
- whoisthemachine 5y agostructs 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).
- gnabgib 5y agoFrom 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.
- gonzo41 5y agoAlternatively you could just make a final class with public member variables and no getters/setters and just treat it like a struct.
- ratww 5y agoThat's a great point, there's absolutely nothing wrong with public members if you only want a simple struct.