Live data from Hacker News

Data Classes for Java

cr.openjdk.java.net

91–100 of 216 posts

Re: Data Classes for Java

#91

... To write such a class responsibly, one has to write a lot of low-value, repetitive code: constructors, accessors ... If you're writing a plain data class, why on earth would you write getters and setters? Just make your fields public and be done with it. I will be forever perplexed by the idea of getters and setters (and this extends to C#s syntax sugar). I have no idea what problem they solve. If you're at the l…

> If you're writing a plain data class, why on earth would you write getters and setters? Just make your fields public and be done with it.

When doing pure OOP, objects should only communicate via methods, period, it's called state encapsulation and is one of the core principle of OOP, the second being polymorphism.

> I will be forever perplexed by the idea of getters and setters (and this extends to C#s syntax sugar). I have no idea what problem they solve.

Then you don't understand encapsulation.

Re: Data Classes for Java

#92
post #3

I, for one, am enjoying the ever so slow scalaization of java.

If the JVM magically got rid of nulls and Scala cleaned up some of the slightly wartier bits (implicits come to mind, although they are useful and no clue how I'd fix em...) then Scala would be my favorite language around by quite a bit. Besides maybe Rust. Really different usecases though.

I've gotten to work two jobs with large Scala projects, plus one of my big OSS projects is in Scala and I really would hate to go back to a Java job.

Scala does have a lot of issues, I agree (implicits. Bleh! I know it makes DSLs easier, but I could be totally fine without DSLs. Python's Zen has it right: explicit is better than implicit), and some libraries can get into crazy insane syntax for those unfamiliar/just starting out with functional languages.

Overall I agree though. I hope the future of the JVM branches away from Java itself and more into the other JVM languages like Scala and Kotlin.

Re: Data Classes for Java

#93
post #89
post #37

Earlier quoted context omitted.

Not that nice compared to kotlin: data class Animal(dog: String, numberOfLegs: Int) val dog = Animal( name = "dog", numberOfLegs = 4 ) The amount of boilerplate for AutoValue builders is so ridiculous that most people use IDE plugins to generate it.

data class Animal(dog: String, numberOfLegs: Int) and Animal dog = Animal.builder() .setName("dog") .setNumberOfLegs(4) .build(); are very different. In this case the builder pattern is more powerful as it lets you pass around builders that haven't been "built" yet. Kind of like currying.

True, but the constructor method is checked/validated at compile time vs. run time with the builder pattern. Not quite the same as your example, but Kotlin does have good syntax for copying data classes while only changing a single field - this could be used similar to your currying usage.

https://kotlinlang.org/docs/reference/data-classes.html#copy...

Re: Data Classes for Java

#94

... To write such a class responsibly, one has to write a lot of low-value, repetitive code: constructors, accessors ... If you're writing a plain data class, why on earth would you write getters and setters? Just make your fields public and be done with it. I will be forever perplexed by the idea of getters and setters (and this extends to C#s syntax sugar). I have no idea what problem they solve. If you're at the l…

Even for just plain data values, getters and setters can be decorated with annotations that modify the member-"property's" behavior depending on context, e.g., what should happen to this member when I serialize to JSON ... or when I read from a DB?

I've found these decorators real useful in the past ... and while they balloon the code for the "data class" itself, they eliminate a lot of code elsewhere.

E.g., this may violate some "separation of concerns", but often one will want to: (a) read some hierarchical data from JSON in a web service request; (b) persist these elements to DB, maintaining proper relations between entities read in from JSON but now persisted as rows to multiple tables in a DB; (c) at some later point read back some of those elements and reconstruct the hierarchy and perhaps transform it or merge it with other hierarchies; (d) perhaps re-persist it, or send it out as a JSON response ... so ...

... in such a situation I am dealing with the same small set of "data classes" everywhere -- but when persisting or reading from a DB I have data fields that represent "primary" or "foreign key" DB values -- I possibly don't want those field values to ever get written to JSON; other member fields deal with the semantic hierarchy of that data in the JSON-like or internal-Java view (e.g., lists, maps, pointers-to-parents-in-hierarchies) ... but I don't want those members ever to be written to the DB (since they're replaced by PK/FK references) ... >>> rather than maintaining two sets of data classes for the two alternative representations (and the ugly boilerplate required to translate between them), it's much easier to have just one set of semantic data classes that each knows how to live in each context (DB, JSON, in-memory, etc. ...). The key to telling these data classes and their members to behave differently, in Java, for each context (JSON deserialize vs JSON serialize vs DB read vs DB write), is to use decorators on their setters and getters.

EDIT: included more lengthy rationale.

Re: Data Classes for Java

#95
post #79

Earlier quoted context omitted.

I get what you're saying, but at the same time I don't understand how you'd implement the class and why. class Temperature { public final double celcius, kelvins; Temperature(int celcius, int kelvins) { this.celcius = celcius; this.kelvins = kelvins; } public static Temperature fromCelcius(int c) { return new Celcius(c, c - 273.15); } } What's wrong with that approach, and how would you do it?

Why would you have two separate temperature values? Just have one in Kelvin that can't go below zero, and have getters and setters that translate to C/F when specified.

What you propose wouldn't be using "getters" to me. They just sound like normal methods.

Re: Data Classes for Java

#96
post #85

Earlier quoted context omitted.

Today's fields are tomorrow's computed properties. Fields are rigid and cannot be changed without recompiling dependencies. Notice how few fields there are in Java's standard library. Why have fields at all?

How many times have you run into this in your career (the need to convert "today's fields to tomorrow's computer properties")?

Plenty of times! The situation where a library released to third parties requires internal structural changes is not an uncommon one. What do you do? Break every piece of third party code or satisfy the new structure and the old interface simultaneously with a computed property? "Move fast and break stuff" doesn't always have to include breaking stuff.

Re: Data Classes for Java

#97
post #54

Earlier quoted context omitted.

In my experience writing getters and setters has been boilerplate 99% of the time. But I still write them because situations arise where you do need to change the nature of that property, sometimes dynamically, and then it's suddenly worth it. You can, for instance, change a getter and none of the class's clients need to know or care about the change. Though I haven't used Groovy much I like their approach to this: "…

Why don't you just use plain fields, and if you need to change it later, delete the field and go fix all compile errors? That's an easy way to find all usages. Or are you not talking about a statically-typed language which would find the errors when you temporarily delete a field?

You don't always control the code that uses it. You'll have a lot of angry customers if you break all their builds.

Re: Data Classes for Java

#98
post #14

Earlier quoted context omitted.

To provide flexibility in the future. When your data comes from a method you can change its source without changing the caller. This can be very useful and should be leveraged whenever possible.

But by definition getters and setters lack lexibility. They expose the internal representation of an object. They stop really being "objects" - high level opaque things you send messages to - and they turn into big porous bags of fields. To clarify, I would not consider something like this a setter: class Monster { int health; void Damage(int d) { this.health -= d; } } True, it is a method that just sets a variable.…

[deleted]

Re: Data Classes for Java

#99

... To write such a class responsibly, one has to write a lot of low-value, repetitive code: constructors, accessors ... If you're writing a plain data class, why on earth would you write getters and setters? Just make your fields public and be done with it. I will be forever perplexed by the idea of getters and setters (and this extends to C#s syntax sugar). I have no idea what problem they solve. If you're at the l…

In C# 6, using properties is actually slightly less verbose, "public int Foo { get; }" vs "public readonly int Foo;". Also, you can easily slap an interface around your data class if you need to later. So my thinking has switched when writing new C# -- why not use a property?

Re: Data Classes for Java

#100
post #26

Honestly immutable data classes that are created via builders is a must have in Java.

Is there something that a builder gets you that Kotlin-style data classes doesn't?

One thing I love about builders, besides the sibling replies, is that builders force users to explicitly name the arguments. Passing args to a constructor/method/whatever with implicit argument ordering can be error-prone in certain situations (multiple adjacent args with the same type).

    c = Class(firstName, lastname)   // are these passed in the right order?
    c = Class(lastName=firstName, firstName=lastName) // obviously incorrect
Especially when you're using other magic like auto-generating constructors based on fields (as with Lombok)...then rearranging two String fields can subtly break things with no compiler errors!
Post reply on HN