What are the rules on writing a mutator method on an immutable class?
Below is a first attempt - consider:
public final class Person
{
private final String firstName;
private final String lastName;
public Person(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() { return this.firstName; }
public String getLastName() { return this.lastName; }
public Person setFirstName(String newFirstName)
{
return new Person(newFirstName, this.lastName);
}
}
The setFirstName() method is obviously the mutator of interest -- it should return a new instance that is a copy of the old instance, save with the newFirstName value as the firstName property.
Is this semantically correct? That is, would it achieve the desired effect?
Is the Person class overall still immutable? And ultimately, thread safe?
If this approach is viable, what rules or other considerations should be observed?
Please feel free to provide any other feedback regarding this matter.
Edit:
- With the manner of creating a new object in the setFirstName() method, is it done atomically?
Thing is that if this
Person
instance is referenced anywhere else than where you are callingsetFirstName()
method from, it will not update there.Could be a problem or a feature. In the latter case, I would rename the method
setFirstName()
to something likecloneWithFirstName(String newFirstName)