Sub topic 13
Designing immutable objects
An immutable object is an object whose state cannot change after it is created. Its state is the data stored in its fields.
For example, a contact card might hold a name and a list of tags. If the card is immutable, neither its name nor its tags can change after the card is created. To get a card with another tag, you create a new card instead.
Immutability makes objects easier to reason about. You can give an immutable object to another part of a program without worrying that it will change the object behind your back.
The design rules
A simple immutable class usually follows these rules:
- Make its fields
private, so other classes cannot change them directly. - Set its fields in the constructor, and mark them
final. A constructor is the code that sets up a new object. Afinalfield can be assigned only once. - Do not provide methods that change the object’s state.
- Validate constructor inputs, so the object starts in a valid state.
- Protect any mutable objects stored in the fields.
A mutable object is an object whose state can change. Lists are mutable: you can add and remove items. A Java String, by contrast, is immutable.
The last rule needs special care. A final field can hold a reference to a mutable object. The field cannot be set to a different reference, but the referenced object may still change.
Build an immutable contact card
This example stores a name and a list of tags. It protects the list in two ways:
- It copies the list supplied to the constructor.
- It gives callers an unmodifiable view of that private copy.
A caller is code that uses a method or constructor. An unmodifiable view is a way to read a list without using that view to add, remove, or replace its items.
Save this program as Main.java:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
final class ContactCard {
private final String name;
private final List<String> tags;
public ContactCard(String name, List<String> tags) {
if (name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException("Name must not be blank");
}
if (tags == null) {
throw new IllegalArgumentException("Tags must not be null");
}
List<String> copy = new ArrayList<>(tags);
for (String tag : copy) {
if (tag == null || tag.trim().isEmpty()) {
throw new IllegalArgumentException("Tags must not be blank");
}
}
this.name = name;
this.tags = Collections.unmodifiableList(copy);
}
public String getName() {
return name;
}
public List<String> getTags() {
return tags;
}
public ContactCard withAddedTag(String tag) {
List<String> updatedTags = new ArrayList<>(tags);
updatedTags.add(tag);
return new ContactCard(name, updatedTags);
}
}
public class Main {
public static void main(String[] args) {
List<String> originalTags = new ArrayList<>();
originalTags.add("friend");
ContactCard card = new ContactCard("Mina", originalTags);
System.out.println("Original: " + card.getName() + " " + card.getTags());
originalTags.add("runner");
System.out.println("After changing input: " + card.getTags());
try {
card.getTags().add("music");
} catch (UnsupportedOperationException e) {
System.out.println("Cannot change returned tags");
}
ContactCard updated = card.withAddedTag("runner");
System.out.println("Updated: " + updated.getTags());
System.out.println("Original still: " + card.getTags());
}
}Compile and run it from the folder containing the file:
javac Main.java
java MainThe output is:
Original: Mina [friend]
After changing input: [friend]
Cannot change returned tags
Updated: [friend, runner]
Original still: [friend]In this example, both classes are in the same file. Main is the public class, so the file must be named Main.java.
Follow the construction steps
The constructor first checks the inputs. A name cannot be null, empty, or made only of spaces. The tag list cannot be null, and each tag must contain some non-space text. An empty tag list is allowed.
The checks use trim() to test for spaces at the ends of the text. They do not change the text stored in the card.
If an input fails a check, the constructor throws an IllegalArgumentException. This reports a problem with an input value. The caller does not receive a successfully constructed card with that invalid value.
These checks establish an invariant: a rule that must remain true for the object. Here, one invariant is that every stored tag contains some non-space text. Since callers cannot later change the tags, that rule stays true.
Protect the list
The constructor makes a copy with new ArrayList<>(tags). This creates a new list containing the supplied tags. A copy made to protect an object’s state is called a defensive copy.
The copy matters because the caller still has originalTags. After creating the card, the program adds "runner" to that original list. The card still shows only "friend" because it holds a different list.
The constructor then wraps its private copy with Collections.unmodifiableList. The returned view lets callers read the tags, but it does not let them change the list through that view.
When the program tries to add "music" through getTags(), Java throws an UnsupportedOperationException. This signals that the requested operation is not supported. The try and catch code handles that exception so the demonstration can continue.
Why use both a copy and a view?
An unmodifiable view does not freeze the list behind it. If the card wrapped the caller’s original list without copying it, the caller could still change that original list. The changes would then appear through the card’s view.
A copy alone would not be enough either if getTags() returned that mutable copy. A caller could use the returned list to change the card.
The example avoids both problems:
- No caller holds the mutable list copy created by the constructor.
- Callers receive only its unmodifiable view.
The items also matter. This list contains String objects, which are immutable. If it contained mutable objects, copying the list would copy the references, not the objects themselves. A caller might still change an item inside the list.
To protect a list of mutable items, you may need to copy each item as well. This is often called a deep copy. You must also avoid returning those private mutable items directly.
Create a changed version
The withAddedTag method does not change the existing card. It makes a new list, adds the requested tag, and uses that list to construct a new ContactCard.
The new constructor call runs the same validation. For example, an attempt to add a blank tag fails rather than producing an invalid card. The original card remains unchanged.
This style gives the caller a choice: keep using the original card, use the new card, or keep both. In the example, card still has [friend], while updated has [friend, runner].
A variable that refers to an immutable object can still be assigned a reference to another object unless that variable is final. Changing which object a variable refers to is different from changing the object itself.
Prevent changes through other classes
The example declares ContactCard as a final class. This means another class cannot extend it.
An extending class, also called a subclass, could otherwise add changeable state or change how methods behave. Preventing subclasses keeps this simple design easier to reason about. Declaring a class final does not, by itself, make its objects immutable; the fields and the objects they refer to must also be protected.
Know the costs
Creating a new object for each change can use more time and memory than changing an existing object. Copying a large list also takes work.
Immutability is a good fit when values should stay stable and are shared in several places. A mutable object can be a better fit when a program must make many frequent changes to a large amount of data. Choose based on how the object will be used.
Practice
Exercise
A caller creates a card from a list containing "art", then adds "books" to that original list. What does the card's tag list contain?
Show answer
It contains only "art". The constructor stored a separate copy of the list.
Exercise
Why would making a list field private and final not be enough if a getter returned the mutable list directly?
Show answer
A caller could use the returned reference to change the list's contents. The final field would still refer to the same list.
Exercise
An immutable class stores a mutable date object. What should it do with the date supplied to its constructor and with a date returned to a caller?
Show answer
It should store a defensive copy of the supplied date and return a copy, so callers cannot change its private date.