POJO
public class Person {
private firstName;
private lastName;
private email;
private List<String> addresses;
// defualt ctor, we don't need it if it's empty
// public Person() {
// }
// getters and setters
public void setAddresses(Collection<String> addresses) {
// this.address = address;
this.address = new ArrayList<>(addresses); // copy? no?
// what about getters? what if users get the list and then
// change it?
}
}
The problem is:
- not immutable, hard to reason about thread safety
- what if it gets changed unintentionally?
- what about collections?
public class Person {
// note final
private final firstName;
private final lastName;
private final email;
private final ImmutableList<String> addresses;
public Person(String firstName, String lastName, String email, Collection<String> addresses) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.addresses = ImmutableList.copyOf(addresses);
}
// getters only
}
- immutable, so thread safe
- easy to reason and maintain
- if you use ImmutableCollections, they are also copy-free