I want to use composition pattern and create a record from another record type in Java but I have some problems with the usage, maybe I am misusing the record in Java, could you please guide me, how you would handle this situation?
Imagine we have the following record
public record Request(String id, String name, String from) {
}
And now I want to warp it in another record which enriches some field of this record with useful data:
public record RequestWrapper(Request originalRequest, Name name, String from) {
public RequestWrapper(Request originalRequest) {
this.originalRequest = originalRequest;
this.name = new Name(originalRequest.name());
this.from = originalRequest.from();
}
public record Name(String name) {
public Name(String name) {
this.name = convert(name);
}
}
static String convert(String str) {
return str + " converted";
}
}
but compiler complain about Non-canonical constructor must delegate to another constructor, in other words record should always have canonical constructor. this encourage me to add other fields to the constructor as well, as bellow:
public record RequestWrapper(Request originalRequest, Name name, String from) {
public RequestWrapper(Request originalRequest, Name name, String from) {
this.originalRequest = originalRequest;
this.name = new Name(originalRequest.name());
this.from = originalRequest.from();
}
public record Name(String name) {
public Name(String name) {
this.name = convert(name);
}
}
static String convert(String str) {
return str + " converted";
}
}
But this is not convincing for me as I have to pass some data that are not being used in the constructor, and I want the record to be created from the Original request and not other passed arguments, how would you handle this situation, am I misusing records in this situation?
I see two options: static factory method or delegating constructor.
Static factory method
Delegating constructor