Java Mutator Implemtation on Immutable Class

229 Views Asked by At

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.

  1. Is this semantically correct? That is, would it achieve the desired effect?

  2. Is the Person class overall still immutable? And ultimately, thread safe?

  3. If this approach is viable, what rules or other considerations should be observed?

  4. Please feel free to provide any other feedback regarding this matter.

Edit:

  1. With the manner of creating a new object in the setFirstName() method, is it done atomically?
1

There are 1 best solutions below

2
On

Thing is that if this Person instance is referenced anywhere else than where you are calling setFirstName() 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 like cloneWithFirstName(String newFirstName)