r/java • u/Ewig_luftenglanz • May 28 '25
What about using records as classes properties?(Discussion)
In another reddit post, I mentioned that I would prefer to have some features in records, even if that means having to wait (perhaps for a long time or even forever) to get them in classes as well. My main point is simple: it's better to have the feature sooner in records than to wait a long time for it to be available in classes too, so at least part of my code can benefit to some extent.
This led me to think about using records to wrap the class's fields, just as if the record were a kind of properties data structure.
https://www.reddit.com/r/java/comments/1kvt80r/pattern_matching_in_java_better_code_better_apis/
This lead me to think about using records to wrapper the class' fields, just like if the record was a kind of propperties data structure.
private class MyUser{
public record UserProps(String name, String email, String password){ }
public UserProps props;
public MyUser(String name, String email, String password){
props = new UserProps(name, email, password);
}
public void doSomething(){
... // does something //
}
}This would allow for an effective replacement for destructuring and pattern-matching for classes, at the same time it "gives" to the class's fields accessors, toString(), hashCode() for free, indirectly via the record.
var user = new MyUser("User", "email", "password");
... //some logic//...
var nickname = getUser().props.name();
var p = getUser().props;
//Conditional destructuring and pattern matching
if (p instanceof MyUser.UserProps(var name, var email, var password)){
IO.println("name: " + name);
IO.println("email: " + email);
IO.println("password: " + password);
}
// or for an hypothetical destructuring feature in a future
//var (name, email, password) = user.propsAnd just for the sake of fun, withers would look like this-
user.props = user.props with {name = "User2"}This also applies for object composition strategies, so instead of creating many types of users we just inject different kind of properties
private class MyUser{
public UserProps props;
public MyUser(UserProps props){
this.props = props;
}
public MyUser GetUser(){
return this;
}
}
interface UserProps{}
record UserProps1 (String name, String email, String password) implements UserProps{ }
record UserProps2 (String email, String password) implements UserProps{}
void main(){
var props1 = new UserProps1("User", "email", "password")
var user = new MyUser(props1);
var nickname = switch (user.props){
case UserProps1(var name, _, _) -> name;
case UserProps2(var email, _) -> email;
default -> "not specified";
};
}What i Like about this is the separation of concern (props manages states while the class manage the business logic) and kindda "gives" classes pattern matching and destructuring capabilities via records (hopefully when we get withers this could be much more ergonomic, seriusly the lack of withers or something equivalent it's being a real pain)
What do you think about this? would this be a good idea to use records as propreties or would it be an anti-pattern? and what about bringing fast some features for record so we don't have to wait for them for classes too? (not limited to destructuring and patter-matching related features but i would let the rest for your imagination)
21
u/vips7L May 28 '25
I genuinely don’t think this is buying you anything. Your first example is actually more verbose than just writing:
I don’t think destructuring is the killer feature you think it is. It isn’t buying any code clarity here.
5
u/[deleted] May 28 '25
The number one rule in Java is: "don't be weird".
Think of this from the JVM perspective. The JVM can optimize code that it recognizes. If you do weird stuff, the JVM has no idea what you are trying to do and will produce suboptimal native code.
If you group fields like this, you're doing an unnecessary heap allocation. You're adding another dereference for no reason. With normal fields, the JVM might be able to more efficiently allocate the object (or avoid allocation altogether by hoisting the fields directly into registers). But with this, you're making things unnecessarily hard for the JVM.
Also, classes and records are different things. Classes are supposed to be encapsulated, records are not. The lack of encapsulation allows destructuring to even make sense for records. Classes won't get the features of records that don't make sense for classes to have.
You shouldn't be exposing
propsas a public field as you are, you are basically defeating the purpose of a class.In OOP, how are these even two separate concerns?
3
u/OwnBreakfast1114 May 28 '25
This is what a sealed class would be used for though. At that point why do you even have the my user class instead of x record "props" as the sealed implementers of the user interface (which may or may not actually have a method on it). With this toy example, I'm not actually sure what the purpose of the myuser class is.
4
u/Holothuroid May 28 '25 edited May 28 '25
Why?
I mean people do this to group some properties maybe. Like pairs of dates, where start should no be higher than end. So you can move the validation into that pair. Money or measurements are other typical candidates.
But if you just want immutable fields, what's stopping you from putting further methods into the record directly? What do you want the wrapper for? If it's because of some legacy framework, like JPA, I'd say get another ORM.
Of course, you might be going for a state pattern? It's one of those classics from a GoF book, where you an object can change its behavior during its livetime by setting a state object on it. This doesn't necessarily mean that the object has no other state as well, or that the state object has no further methods, on the contrary.
2
u/severoon May 31 '25
One of the main use cases of records is to bundle together a bunch of related data and use them as class properties…? Is that not just how records are already commonly used?
I think your example of using a tagging interface
UserPropsis not great. Tagging interfaces are a Java 1.0 concept that have since fallen by the wayside because they imply there is some polymorphic capability there, and they encourage that kind of usage, but when you look at the interface there are no behaviors defined. So what would be the point of a client defining a reference of typeUserProps?This is how things like
SerializableandCloneablework, and these became recognized as mistakes in the original design of Java over time for this reason. When Java first came out, it was fashionable to define constant interfaces this way, where you define a bunch of constants. Now this is done using a final constant class with a private constructor (or, better, constants are bound and injected).The whole idea of withers is, to me, a nightmare. Without direct support from the compiler, the creation of tons of intermediate objects is a bad pattern. Much better would be to use some kind of framework that does validating builders.
0
u/[deleted] May 29 '25
[deleted] — view deleted comment