A dataclass turns a data-focused Python class into a concise carrier for storing and representing data. It addresses the point where constructors, accessors, equality logic, and string representations obscure the meaning of the data itself. section 4.1.2 section 4.4
Prefer meaningful data over positional noise
A Person object with many fields becomes difficult to construct when values are passed positionally: nulls hide intent, integers can appear in the wrong place, and parameter order couples callers to implementation details. A dataclass offers a concise way to model that data without reproducing the surrounding boilerplate manually. section 4.1.2 section 4.4
Listing 4.1 The Person DTO written with full boilerplate code
public class Person {
private String firstname;
private String lastname;
public Person() {} #1
#1
public Person( #1
String firstname, #1
String lastname) { #1
this.firstname = firstname; #1
this.lastname = lastname; #1
} #1
public void setLastname(String lastname) { #2
this.lastname = lastname; #2
} #2
public void setFirstname(String firstname) { #2
this.firstname = firstname; #2
} #2
public String getFirstname() { #3
return firstname; #3
} #3
public String getLastname() { #3
return lastname; #3
} #3
@Override #4
public String toString() { #4
return "Person{" + #4
"firstname='" + firstname + '\'' + #4
", lastname='" + lastname + '}'; #4
} #4
#4
@Override #4
public boolean equals(Object o) { #4
if (this == o) return true; #4
if (!(o instanceof Person person)) #4
return false; #4
return Objects.equals(firstname, person.firstname) #4
&& Objects.equals( #4
lastname, #4
person.lastname); #4
} #4
#4
@Override #4
public int hashCode() { #4
return Objects.hash(firstname, lastname); #4
} #4
private Person(Builder builder) { #5
this.firstname = builder.firstname; #5
this.lastname = builder.lastname; #5
} #5
#5
public static class Builder { #5
private String firstname; #5
private String lastname; #5
#5
public Builder setFirstname(String firstname) { #5
this.firstname = firstname; #5
return this; #5
} #5
#5
public Builder setLastname(String lastname) { #5
this.lastname = lastname; #5
return this; #5
} #5
#5
public Person build() { #5
return new Person(this); #5
} #5
} #5
} #5
Compare the full boilerplate required for a small Person data object with the concise data-oriented style enabled by modern language constructs. section 4.1.2






