19 ms·
Java's records, Lombok's data, and Kotlin's data classes
- smoldesu 5y agoThis might qualify as low-grade threadjacking, so I apologize if this is off topic, but who's actually using Java these days? Most devs I know avoid it like the plague, and only use it to maintain legacy codebases or get CS qualifications. Are there any real advantages to using Java in 2021, besides it's mature community/ecosystem/tooling?
- Misdicorl 5y ago> besides it's mature community/ecosystem/tooling Thats the answer. And its a really good one. The only other languages with the same or better breadth and depth have their own reasons to avoid them like the plague (e.g. C/C++ footguns, difficulty managing large-ish codebases without types)
- villasv 5y agoIKR. The question framing is almost like: is there any other reason to use Java except all the most important and good reasons?
- smoldesu 5y agoI meant it more on a language level. It has a great network of support, no doubt credited to it's long legacy, but what technical advantages would it provide over writing a program in a language like C++ or Rust? Is it all creature comfort, or does it have some hidden advantage that I can't see?
- Misdicorl 5y ago> besides it's mature community/ecosystem/tooling How could you not see this as an incredible technical advantage in almost any context?
- Misdicorl 5y agoIf you must have a specific language level technical advantage over C++/Rust, its the incredible GC algorithms available to you while you are (mostly) stuck with simple arena collectors in C++/Rust land.
- haolez 5y agoIt's a language that protects your investment. There is a lot of effort in backwards compatibility and the language puts a lot of constraints in the devs so that the development moves slowly, but in a sustainable manner. This is the best case scenario, of course. But it's an argument that I see being used in new Java projects.
- diab0lic 5y agoA large chunk of the Netflix backend runs on the JVM. Much of it written in Java. While I agree that many devs avoid it like the plague, and I used to be one of them, once I let go of attachments to programming languages I found it quite a pleasant experience to develop software using Java. Basically using Lombok and Vavr give you a very nice lightweight functional experience. Bells and whistles tend to be a distraction from making software that works and scales. I’d way rather focus on the hard problems in computing than how to most idiomatically or elegantly express things in a language.
- bob1029 5y agoIf C# didn't exist, we would certainly be a Java shop. Not only because of the ecosystem & tooling, but also because it is a language that has historically proven its ability to model incredibly complex business domains as well as support mission critical workloads without falling over on itself.
- azth 5y agoHow's your experience with C#/.NET been? Does it have an analogous offering to Java's JFR[0] for always-on profiling? [0] https://blogs.oracle.com/javamagazine/java-flight-recorder-and-jfr-event-streaming-in-java-14 https://blogs.oracle.com/javamagazine/java-flight-recorder-a...
- bpicolo 5y agoSeems like EventPipe is the C# equivalent? https://docs.microsoft.com/en-us/dotnet/core/diagnostics/eventpipe https://docs.microsoft.com/en-us/dotnet/core/diagnostics/eve...
- azth 5y agoIt seems somewhat similar, but I don't see mention of method traces (similar to a profile view in figure 7 in the blog post I listed).
- bpicolo 5y agoThere are tools built on top of it to that effect (eventpipe -> dotnet-trace -> tools built on top of trace) https://www.hanselman.com/blog/dotnettrace-for-net-core-tracing-in-perfview-speedscope-chromium-event-trace-profiling-flame-graphs-and-more https://www.hanselman.com/blog/dotnettrace-for-net-core-trac...
- bob1029 5y agoI am not familiar with the scope of JFR, but there have been some very recent movements around profiling in C#/.NET: https://devblogs.microsoft.com/dotnet/introducing-dotnet-monitor/ https://devblogs.microsoft.com/dotnet/introducing-dotnet-mon... https://devblogs.microsoft.com/dotnet/whats-new-in-dotnet-monitor/ https://devblogs.microsoft.com/dotnet/whats-new-in-dotnet-mo... My experience overall with the C# ecosystem has been fantastic. We started out on .NET Framework 4.x back in 2014-2015, and today are now talking about moving to .NET 6 and rewriting our native apps to use MAUI as November grows closer. A lot of the same code we had back in 2015 is still running today with zero modifications.
- autodidacticon 5y agoIt would seem that the world of data engineering is largely dominated by Java.
- johnnycerberus 5y agoI share the same view, based on the jobs in my area, everyone is using Python to prototype and Java/Scala to productionize, I've also seen Node.js increasingly being used, probably for things that are I/O-intensive and not compute-bounded. Rust could change the landscape for Node/Deno, critical code which is memory/cpu-intensive could be exported to a WASM library or an external dependency that can be called through FFI (though that would be very slow and you introduce the 2-language problem that Julia is trying to fix for Python). Anyway, even if we are in a way better state today than, let's say, 5 years ago when it comes to picking tools for data engineering, I strongly believe that JVM is here to say for a long, long time.
- barsonme 5y agoAndroid development. Kotlin is great, but Java is still a perfectly valid choice. In particular, if you don’t have dedicated Android developers Java can be a good choice because most people are at least somewhat familiar with it and won’t have to learn a new language to be productive. That said, I think anybody who understands Java should be able to understand Kotlin with minimal effort.
- skinkestek 5y ago> Most devs I know avoid it like the plague, and only use it to maintain legacy codebases or get CS qualifications. All the customers I have worked with since I became a consultant 4 years ago (and a couple of the best companies I worked with in the decade before) used Java or .Net. More specifically one of them was dotnet core and the rest are JVM. And I'm happy with that. Java and Maven means I can focus on the problem and not on all the crazy things people who think they are too clever to use Java do. I mean I have seen a couple of Abstract Factories in Java, but I haven't seen anyone avoiding putting passwords in the source code by writing things like this: rot13(<rot13password>) That is stuff I have found in Python code by the one consultant who was to smart to use Java or .Net.
- EvilEy3 5y ago> besides it's mature community/ecosystem/tooling? Not sure if I should be mad or just ignore you.
- dboreham 5y agoJava has the nice advantage that it works.
- jeroenhd 5y agoThe existence of Spring Boot makes Java a very good choice for loads of dev shops. Good balance between features, ease of use, performance and security, not difficult to pick up, and very well documented. In my personal opinion, C# is a superior language these days now that most of .NET has been ported into dotnet core. However, that's only been the case for a few years and before that, Java was in a league of its own with its excellent library ecosystem and omnipresent JVMs. Java is a very boring language. Features get added slowly compared to other languages, improvements are generally quite gradual and new concepts only rarely ever get added to the language. This will drive away many hot startups and fresh CS graduates because they want to use the latest technologies in brave new ways and explore the ecosystem. For general businesses, boring is good. Boring is predictable, understandable and maintainable. Java is not the fastest language to write software in, but it's fast enough not to warrant teaching your staff a new language for. It's missing many features that are standard in other languages, but there's third party libraries to make up for that. In my mind, languages like Rust and Zig are the Teslas of the software world, exciting, new, full of flaws that need to be ironed out but ready to storm the general market one day soon. Go and Kotlin are the shiny new SUVs, impressive and high quality, but packed with weird design choices and opinions on how to use them. Java and C# are the old van the company has owned for 20 years. Nothing impressive, but reliable, comfortable, predictable, and with quirks that everyone has been learning for years now. Most businesses don't need a Cybertruck, they need to get around, and what businesses already have is good enough for the next while.
- johnnycerberus 5y agoYou forgot about the spaceship called Scala and how many startups are trying to parallel park a spaceship when they just need a Mini. Just to continue your line of analogies. Though, I still like playing with spaceships.
- Karrot_Kream 5y agoHah this is a great set of analogies. Thanks!
- lowbloodsugar 5y ago>Are there any real advantages to using Java in 2021, besides it's mature community/ecosystem/tooling? It's fast: C fast in most cases. It can use a lot of cores and memory with minimal effort from developers. It has great tuning parameters for things like GC. We hit a cliff at about 150GB heap, tuned it, and now we're at 300GB. It's "good-enough" type safe. Java grows with you.
- throwpupper 5y agoJava? Not so much. JVM? Absolutely. The ecosystem, stability and performance is unmatched.
- taftster 5y agoTry this list out: https://projects.apache.org/projects.html?language#Java https://projects.apache.org/projects.html?language#Java There's a LOT of real interest in Java in many many industries. Saying this like "Most devs I know" just really is more of an observation of your local circle. Big data, Finance, Government Just to name three really big industries that are dominated by Java.
- AtNightWeCode 5y agoNot sure why immutable data structures have surfaced as something important. Typically you never change fields so it is kind of only of academic value if a field in a POD, POJO, POCO or whatever it is called in the specific language actually may change.
- ramblerman 5y ago> so it is kind of only of academic value if a field in a POD, POJO, POCO or whatever it is called in the specific language actually may change. I'm not sure if you've debugged much, or inherited any large legacy projects, but knowing it is immutable vs "typically it isn't" is a pretty big distinction in that moment.
- AtNightWeCode 5y agoGood code don't have this issue.
- slver 5y agoGood code doesn’t have concepts like “typically doesn’t mutate”. It’s either mutable or immutable.
- AtNightWeCode 5y agoThe standard way to do it is to mutate clones as always in Java. Typically by use of libraries that provide this. You really need very bad code to have to think about if objects are mutable.
- slver 5y agoApparently you don’t know most immutable structures are optimized for modified cloning in ways mutables aren’t.
- 5y ago
- hota_mazi 5y agoA long winded article that really never justifies its headline. Kotlin will soon be generating records in its back end, thereby gaining all the advantages that it's allegedly not getting today.
- jillesvangurp 5y agoThat feature was released this week with Kotlin 1.5.0.
- nicolai-parlog 5y agoThat misses the point. The strength of records is that the language can build features that are only possible because of records' restrictions. It's not that the bytecode says "I'm a record" - which is all you get if Kotlin compiles a data class to one. @JvmRecord gives you all the limitations with none of the benefits. The annotation only exists for compatibility reasons.
- unscaled 5y agoBut what are the benefits that are available right now? The only benefits I've seen in your article are not available right now, and can (and sometimes are) matched by Kotlin and even Lombok. * Destructuring pattern matching syntax (JEP 405) Proper pattern matching is obviously one of Kotlin's weak spots, but nothing prevents it from developing this in the future. Just like Java has JEP 405, Kotlin has KT-186[1], although Java might (uncharacteristically) beat Kotlin to this one. * with blocks This solution is far away and relies on introducing new syntax to the language. Meanwhile both Kotlin and Lombok already have solutions that give you the same benefits without introducing new syntax. Lombok has both @With and @ToBuilder, while Kotlin has the copy() method. * Serialization As far as I can see, Kotlin Serialization already supports algebraic data types - including Sum Types, not just Product Types! * Boilerplate reduction I don't think you were trying to imply otherwise, but just to be clear about it, this is the benefit that both Kotlin and Lombok data classes had from day one. [1] https://youtrack.jetbrains.com/issue/KT-186 https://youtrack.jetbrains.com/issue/KT-186
- pkulak 5y agoSo what's the answer to the question? Pattern matching and destructuring? But I don't see any reason Kotlin data classes can't do that. I know Kotlin pattern matching is pretty lack-luster, but I never thought this was the reason.
- abductee_hg 5y agosorry -java .. better? what? why would anyone use java for anything? let me give an example: from a project a while(some years actually) ago i still have a license for a php-ide(zend). its in java. no chance in hell to get it working today. meanwhile, stuff i did 2003 still runs on windows out of the box, even in wine/osx. so again: why use java for anything? https://twitter.com/abductee_org/status/711966430133026816 https://twitter.com/abductee_org/status/711966430133026816 (try it https://www.pouet.net/prod.php?which=11247 https://www.pouet.net/prod.php?which=11247 ) oh and there is this: https://people.eecs.berkeley.edu/~wkahan/JAVAhurt.pdf https://people.eecs.berkeley.edu/~wkahan/JAVAhurt.pdf so, double-again: why use java for anything?
- crummy 5y agoIsn't java famous for backwards compatibility?
- eweise 5y agoMain problem I had with lombok is that it was too flexible, causing me to have to read all the annotations on a class. Kotlin data classes are implemented a single way so I don't need to grok them individually.
- EvilEy3 5y ago@JvmRecord data class ... I'm sorry, you said something?
- andrewprock 5y agoI'm never understood why code generation for getters and setters is so over-engineered. Heavy technologies for light work is almost always more trouble than it's worth.
- commandlinefan 5y agoGetters are setters are pointless anyway - unless you're creating read-only properties by only providing getters, reflexively adding a getter and a setter for every property is exactly the same as just marking the property public. It's even worse in the case of immutable objects (like lists or maps), because the getter itself returns a reference to the mutable object. Getters and setters mentality came from a horrible misunderstanding of object oriented design principles and has been standardized into common practice.
- slver 5y agoget()/set() is the same as a public property, until you change the implementation, while maintaining interface compatibility, which is the point. In C# you'd have a point, they have parametric properties and readonly properties. So you'd favor just declaring public properties. But this is why context matters. And OO design principles also depend on this context.
- marcosdumay 5y ago> until you change the implementation, while maintaining interface compatibility, which is the point How many times have you seen that done on the real world? And how many times have you seen that done, and it not creating a lot of bugs because of the behavior change without interface changes? Personally, I've seen the first one more than zero times. Not the second. Every single time somebody decided to mess with a setter or a getter, it broke the systems that depended on it, and things would have been much better if they simply changed the interface, so the problems would arrive at compile time.
- slver 5y ago
- RcouF1uZ4gsC 5y agoTrying to read in Safari iOS but most of the article text seems to be missing.
- JackFr 5y agoCompletely unreadable on mobile for me.
- deleted 5y ago[deleted]
- Reason077 5y agoTry using "Reader" mode. Tap the little icon at the left of the URL bar.
- bvanderveen 5y agoSame.
- turtletontine 5y agoOnly half the code is rendering for me as well, Firefox iOS
- random42_ 5y agoYou have to scroll the page reeeeeally slow to let the text load where it’s supposed to.
- slver 5y agoSo this custom code font not only looks like Apple II, but it also works like Apple II. Amazing.
- eyelidlessness 5y agoI think it does a GC pause on every scroll. If you just scroll and wait a few seconds it renders. That said it got so frustrating I stopped reading, even though I was curious :(
- johnthuss 5y agoOne of the best things about Records is that they guide you to creating immutable data structures, which Lombok does not. This, along with the reduction of boilerplate, greatly reduces the cognitive load required to understand a lot of code.
- chris_j 5y agoLombok has @Value classes, which I use a lot. Is there something about them that does not guide you to creating immutable data structures?
- watwut 5y agoLombok increases the cognitive load required to understand and debug the code.
- oftenwrong 5y agoThe guidance is nice, but, unfortunately, Record components can still be mutable. It would be great if there was a way to have a stronger guarantee of immutability.
- jgrant27 5y agoThey are still classes, still live on the heap and still need to be garbage collected. Compare with value types that live on the stack in other languages such as Swift, Go and Julia.
- The_rationalist 5y agoValue classes, primitive types and specialized generics will be on the stack on the next versions. There is also this related work https://github.com/microsoft/openjdk-proposals/blob/main/stack_allocation/Stack_Allocation_JEP.md https://github.com/microsoft/openjdk-proposals/blob/main/sta...
- loukrazy 5y agoIsn’t the point that Record classes will be able to be upgraded to value types easily once Valhalla is done? Or am I missing something
- The_rationalist 5y agoNo they won't (or maybe they will be able to be speculatively opt-deopt?) Value types above a relatively small size are less efficient than references.
- kasperni 5y agoYes, just add 'primitive' before record in the declaration.
- kasey_junk 5y agoI’ve not explored them much, how well does escape analysis work with them?
- shagie 5y agoThe heap is an implementation detail. With escape analysis, the compiler can allocate the data on the heap, stack, or even stick it in registers. https://www.beyondjava.net/escape-analysis-java https://www.beyondjava.net/escape-analysis-java https://shipilev.net/jvm/anatomy-quarks/18-scalar-replacement/ https://shipilev.net/jvm/anatomy-quarks/18-scalar-replacemen... https://www.javaadvent.com/2020/12/seeing-escape-analysis-working.html https://www.javaadvent.com/2020/12/seeing-escape-analysis-wo...
- valenterry 5y ago> Actually, records are even better* than tuples. EP 395 says: > > Records can be thought of as nominal tuples. They are certainly not better, that's just a sad click-bait (the author even admits that). Sometimes nominal typing is better and sometimes structural typing is better. Forcing people to always use nominal types just ends in a lot of generic or long/meaningless names - one can already see this in Java.
- The_rationalist 5y agoNominal !≠ named You can have named tuple members while maintaining structural typing, it's not mutually exclusive.
- valenterry 5y agoDid I say something that contradicts that?
- slver 5y agoI've been thinking about structural vs nominal. As you say, both have use cases. How would you combine both in one language so it's not confusing?
- swsieber 5y agoRestrict structural types to tuples only.
- slver 5y agoThat honestly won’t be very useful.
- amitport 5y agoTypeScript!
- valenterry 5y agoI'm not sure, but I think I would make a language based on structural typing only, including to allow a structural type to contain names. (Scala actually already has literal types that come close) Think about the following type-level (not runtime) representation for a structural type (tuple): (String -> Integer) And the following for a structural type with where each "member" has a name: (("name" -> String) -> ("age" -> Integer)) And the following for a named structural type where each "member" has a name: ("User" -> (("name" -> String) -> ("age" -> Integer))) The last structural type here would be equivalent to a class/record in Java. I would then add syntax that makes working with these special kinds of structural types more easy. So record User (String name, Integer age) would translate to the structure above. But one could also do something like that _if they wanted to_: ("User" -> (("field1" -> ("name" -> String)) -> ("field2" -> ("age" -> Integer)))) The closed equivalent would be a Java record where each member is annotated. This could be used to serialize/deserialize it into json. I think that's what I would try :) but I'm not a PL designer.
- jayd16 5y agoRecords are good but if you want this in Lombok don't you just use @Getter instead of @Data to generate read only methods? Serialization is handled by Java bean getters and setters just fine. I don't really see an advantage.
- simonpantzare 5y agoI've used @Value along with @Builder(toBuilder=true).
- ctvo 5y agoWho is arguing otherwise? It's assumed that when a language adds a new feature that's historically been provided by libraries, it's probably better optimized. CompletableFutures, Streams, Date/Time. For many they've replaced libraries filling the gaps. But not all of us can use JDK 14, and will continue to use Lombok if we're writing in Java.
- Rapzid 5y agoWork on a Grails app; only boots on up to 11 ATM. BUT, the hot reload only works with 8... So while the app runs on 11, most development occurs on 8 still. Lombok JustWorks™. You forget it's there until you setup a new dev environment and forget to setup the annotation processor in IntelliJ.
- vbezhenar 5y agoYou need JDK 16 to use records without preview flags. And "with" syntax probably won't be available for JDK 17 which is next LTS, so for the next 3 years records will not be very useful for most projects, I guess.
- jsd1982 5y agoUsing Dark Reader extension for Chrome, all of the sample code text goes to the same color as the background so I thought I was scrolling over huge chunks of blank space.
- capitainenemo 5y agoI was surprised to encounter this as well in Firefox using Dark Mode. I'm still not 100% sure what's going on, because it's rather odd, but if I inspect the page, and add a: .language-java { opacity: 0.99999 } All content instantly renders. Interestingly: .language-java { opacity: 1 } or .language-java { opacity: 0.99999999 } /* probably same as 1 */ Blanks out the content again. Seems rather odd behaviour to me so definitely interested if anyone figures it out, even if this is kind of derailing the discussion.
- capitainenemo 5y agoKay. Day got a bit more quiet. I vaguely remembered running into this weirdness before. It's 'cause apparently opacity creates a new stacking context. Doing z-index:1;position: relative; does same thing. The rule that seems to be breaking everything is the one that forces a default opaque background on everything with dark text. For it to break this, there must be overlapping content, but haven't found it yet. But enough to know what was going on..
- tut-urut-utut 5y agoIt's not blog authors responsibility to test his blog for all possible extension that some readers might be using. If the reader is using some third-party software that modifies the original blog design, it's his responsibility to disable it if it doesn't work seamlessly.
- knoebber 5y agoI agree with this in general, though sometimes incompatibility with popular extensions is an indication that the author isn't following standards.
- billyjobob 5y agoKotlin data classes can use Java records as their implementation if running on JVM, so it’s not like you have to choose one or the other. https://kotlinlang.org/docs/jvm-records.html#declare-records-in-kotlin https://kotlinlang.org/docs/jvm-records.html#declare-records...
- _old_dude_ 5y agoI wonder why, unlike a Java record, in Kotlin a data class annotated with @Record can not be local. Being able to use local records is a useful feature in particular in unit tests. @Test void testPoints() { record Point(int x, int y) {} ... }
- tadfisher 5y agoI don't see the point; you're not testing code that depends on Point, as it's local, so `x to y` (i.e. `Pair(x, y)`) would work just as well. If there's a particular language feature records enable that Kotlin doesn't with ordinary data classes in this case, I'd love to see it.
- crdrost 5y agoThis is great news! I was also kind of surprised to see the article talking about algebraic data types... table stakes for ADTs is sum types and I have missed them considerably in the Java ecosystem. Kotlin has something like them with sealed classes, although I'm a newcomer to the Kotlin and Spring Boot ecosystem so I don't see explicitly how I make some simple case like JSON {"type": "left", "abc": 123} {"type": "right", "def": "456"} turn into some structure like: sealed class EitherTest { data class Left(val abc: Long): EitherTest() data class Right(val def: String): EitherTest() } rather than the hacky version that you have to do in relational databases and Java which don't support such things, enum class EitherType { LEFT, RIGHT } data class EitherTest(val type: EitherType, val abc: Int?, val def: String?) Like I’m not saying that there’s no way, I’m sure there’s a way... just that the ecosystem seems so hesitant to embrace sum types that like the above sealed class is widely viewed as a hack and there is no statement about “here is how you actually use sum types for everything in your Spring application with Kotlin.” Was gonna give the choose-your-own-adventure example of why sum types are handy and how you have to kind of hack around them with inheritance when you don't have them but it occurs to me that anyone who has stuck with this comment this far probably already has some familiarity with this?
- The_rationalist 5y agoKotlin data classes can be used with the JPA contrary to Java records. It's good to encourage immutability, but it is often a misfit and isn't the role of a "data class", they could have added a separate class qualifier immutable that would have been a better separation of concerns, here it's ad-hoc. Kotlin is enabling such immutable support thanks to Java records ironically https://kotlinlang.org/docs/jvm-records.html#declare-records-in-kotlin https://kotlinlang.org/docs/jvm-records.html#declare-records... Note however that an upcoming version of Java will get first class ergonomic support for manipulating immutable data: https://github.com/openjdk/amber-docs/blob/master/eg-drafts/reconstruction-records-and-classes.md#withers https://github.com/openjdk/amber-docs/blob/master/eg-drafts/... There is also https://github.com/hrldcpr/pcollections https://github.com/hrldcpr/pcollections
- vips7L 5y agoI'm really not sure if using data classes with JPA is smart idea. Solely because of generated hashCode/equals and JPA lazy loading. For instance ebean recommends against it [0]. https://ebean.io/docs/best-practice/#kotlin-data-class https://ebean.io/docs/best-practice/#kotlin-data-class
- Bjartr 5y ago> Kotlin is enabling such immutable support thanks to Java records ironically That a member of the JVM ecosystem is leveraging new JVM capabilities isn't ironic, it's totally expected.
- hueho 5y ago> Kotlin data classes can be used with the JPA contrary to Java records. Arguably this is more of an issue of JPA than an strict advantage of Kotlin: JPA was designed at a time where the general consensus was to primarily use mutable data, and was heavily influenced not only by existing Java ORM APIs, but by their implementations. Kotlin itself supports JPA by the use of a compiler plugin, which is a good enough solution, but nevertheless, not one native to the language. Data classes mostly work by accident, but pretty much any documentation you will find points it to _not_ use them with JPA.
- valenterry 5y agoScala's case classes are missing in the comparison (only mentioned briefly at the very end). They offer everything that records do and more. Good to see that Java finally catches up a bit.
- halfmatthalfcat 5y agoScala is usually omitted for one reason or another when Kotlin is compared against Java as a better alternative, which is a shame.
- aero142 5y agoScala has to the solution to every problem except the problem of too many features.
- AzzieElbab 5y agoMaybe but scalas case classes are super easy to grasp and require no magic like annotations
- xenomachina 5y agoWhat annotations are you referring to?
- scubbo 5y agoI'm not the person you were asking, but, presumably, Lombok's annotations.
- AzzieElbab 5y agoLomboks. Seriously, scala case classes are like the very first thing people start using when learning the language. Scala3 enums are even more straightforward
- 5y ago
- throwpupper 5y agoI think the article is misleading in the list of advantages over Kotlin's Data Classes. 1. Destructuring - available in Kotlin 2. Copy with change - available in Kotlin 3. Serialization - not sure why Kotlin data class would not be serializable 4. Boilerplate - Kotlin takes care of equals and hashCode Huge disadvantage that matters to me is that record fields cannot be mutated. It makes the records much less useful.
- throwaway4good 5y ago"Huge disadvantage that matters to me is that record fields cannot be mutated. It makes the records much less useful." No. It makes them much more useful.
- throwpupper 5y agoWell it means that the second you need a setter you can't use records so all the boilerplate remains.
- zaphar 5y agoWhy would you need a setter for a data class? They add no value there.
- deleted 5y ago[deleted]
- valenterry 5y agoYou are supposed to create a new copy with some of the fields changed. Just like you do it with the java.time.* classes and others.
- bcrosby95 5y agoYet the only mechanism for this is error prone or relying on mountains of boilerplate.
- flerchin 5y agoProject Lombok is my bae, but of course a language included API is better than an annotation processor.
- roflc0ptic 5y agoI love that this website is trying new stuff with design. I also think the TOC is terrible and distracting.
- cs-szazz 5y agoI'm not sure what it's taking about for the "with" feature: https://nipafx.dev/java-record-semantics/#with-blocks https://nipafx.dev/java-record-semantics/#with-blocks In Kotlin data classes, it's already implemented (just called copy) https://kotlinlang.org/docs/data-classes.html#copying https://kotlinlang.org/docs/data-classes.html#copying
- bcrosby95 5y agoIt was included because changing data using records (copying it except changing the fields you need to change) is a shitty experience, so rather than showing the code you have to write, they showed you code you may or may not in the future be able to write.
- dlbucci 5y agoSeems like an odd thing to mention. They are arguing that records are better than data classes, but part of their argument is "maybe, in the future, at some point, I don't know, it will be as easy to do this thing with records as it already is with data classes, we'll only need to add new syntax and a new keyword to the language".
- krzyk 5y agoWho is they? You mean the article author? Yes, it was odd that he mentioned that, but besides that not a bad feature to have (but a bit wordy for my taste, I hope they'll change that).
- giaour 5y ago"With" doesn't exist in Java, but it was introduced in C# 9.0 as part of the .NET implementation of records: https://devblogs.microsoft.com/dotnet/c-9-0-on-the-record/#with-expressions https://devblogs.microsoft.com/dotnet/c-9-0-on-the-record/#w... I think the author is more saying that a "with" operator would fit into Java record semantics but might not be compatible with Lombok @Data classes or Kotlin data classes (though it looks from your link that Kotlin actually does have something very similar in the "copy" method).
- abledon 5y agoIF you're not on Java 14 yet (70% of industry?[1])... this post shows two other alternatives for Lombok: https://medium.com/@vgonzalo/dont-use-lombok-672418daa819 https://medium.com/@vgonzalo/dont-use-lombok-672418daa819 Autovalue & Immutables [1] https://snyk.io/wp-content/uploads/jvm_2020.pdf https://snyk.io/wp-content/uploads/jvm_2020.pdf pg 5
- zoover2020 5y agoUnfortunately AWS Lambda doesn't support 14 yet :/
- jandrese 5y agoDo you care about memory leaks on a Lambda? I don't think they can live long enough to even invoke the GC. I guess if you're going through a lot of data you could blow your memory budget and have it terminated?
- ilrwbwrkhv 5y agoThat blog is hard to read for some reason.
- de_keyboard 5y agoGreat to see Records come to Java, although without the "with" feature they are pretty half-baked. I give it 5-10 years before we've tricked everyone into writing OCaml / F#!
- grishka 5y agoCurious question — why do people insist so much on fields being private and there being getters and setters, even when all that getters do is return the field and all that setters do is set it? What kind of problem does this arrangement solve? Why not just use public fields?
- blacktriangle 5y agoThis protects you from changes to the internal representation of state in the future. Direct field access totally blows away encapsulation.
- grishka 5y agoSo, uh, do a usage search before changing stuff? You'll have to, anyway.
- kaba0 5y agoNot necessarily agree with private fields, but that is not an option for library writers.
- erik_seaberg 5y agoThat works if your class is never used outside your own organization, but the API of published code needs to be changed more gracefully using semver.
- highwind 5y agoOnly argument I heard, not that I agree but, is future proofing by abstraction. What if a simple getter evolves into something more complex. Then You'd have to refactor all the places where it was using the fields. I personally never had to do this so I'm not sure if this is a real benefit.
- dragonwriter 5y agoDepending on the language, getters and setters may not be source and/or binary compatible with fields from the client side, so if you might ever need to refactor to a nontrivial getter or setter (whether because you are changing representation or for other reasons), starting with trivial getters/setters instead of fields limits future breakage.
- rdsubhas 5y agoI believe the article focuses too much on "perceived/future" benefits of records, while ignoring the actual benefits that Lombok & Kotlin data classes provide today. For example, article does not mention lombok @Builder and Kotlin `copy` when talking about boilerplate. Boilerplate is not just about application code, it's also about test code! We have dozens of entities, and when unit testing them – always having to construct the COMPLETE record with all attributes from scratch is a pain. Nested records things worse. We now have all data classes as @Value+@Builder, and test factories provide consistent builders which the actual test cases can chain, override and use. This is possible in Lombok & Kotlin, but not in Record.
- MichaelMoser123 5y agoyes, java records are part of jdk14, many places are still stuck with jdk8 or jdk11, hoewever everyone can use lombok (they didn't mention that detail in the article)