Video in progress
How does returning an internal List through a getter break encapsulation, and how do you fix it?
If a getter returns the private list itself, outside code can add or remove elements, bypassing the class's checks. The fix: return an unmodifiable view (Collections.unmodifiableList) or a copy (List.copyOf), and make changes through separate methods.
📖 Answer
public class Cart {
private final List<Item> items = new ArrayList<>();
private static final int MAX_ITEMS = 50;
public void add(Item item) {
if (items.size() >= MAX_ITEMS) throw new IllegalStateException("Savat to'ldi");
items.add(item);
}
public List<Item> getItems() { return items; } // a hole!
}
cart.getItems().add(anyItem); // the MAX_ITEMS check was bypassed
cart.getItems().clear(); // the cart was emptied from outside
The fixed version:
public List<Item> getItems() {
return Collections.unmodifiableList(items); // reading is fine, modifying throws UnsupportedOperationException
}
Which one to use when:
Collections.unmodifiableList(items)makes no copy, so it is cheap; but later changes inside the class show up in the view too;List.copyOf(items)is a real "snapshot" that doesn't change afterwards; on big lists you pay for a copy on every call.
The same problem exists on the way in: if you store a list passed to the constructor directly, the caller can change it later. The same rule applies to mutable objects like Date, or even better, use immutable types like Instant/LocalDate.
Sign up to mark studied questions and save your progress.