Programming Search⌘K

Techniquecore

Encapsulate collection

Also called read-only collection view.

Stop a getter from handing out the collection that an object owns; give the object methods to add and remove elements, and return a copy or a read-only view.

Family
refactoring
Intent
Make the owner of a collection the only code that changes which elements it holds.

Purpose

An object that owns a list, a set or a map usually has rules about it: no duplicates, a maximum size, an order, a count kept in another field. A getter that returns the collection itself breaks all of them. The caller gets a reference, calls push or remove on it, and the owner never knows.

Encapsulate collection keeps the changes inside the owner. The getter returns a copy or a read-only view, and the owner gets methods such as addCourse and removeCourse for each change it allows. The catalogue card shows a Person whose courses getter returns this._courses before and this._courses.slice(), a copy, after, with addCourse and removeCourse added.1 The first edition has the refactoring under the same name.2

This is the collection case of Encapsulate Record and Encapsulate Variable. Encapsulating the variable that holds the collection is not enough. The variable can be private while its contents are open to everyone who called the getter.3

Steps

  1. Run the tests and see them pass.
  2. If the field that holds the collection is not yet behind accessors, apply Encapsulate Variable.3
  3. Add methods to add and to remove an element, and to do any other change that callers need.
  4. If there is a setter for the whole collection, remove it, or make it store a copy of its argument.3
  5. Run the static checks.
  6. Find each caller that changes the collection through the getter, and change it to call the methods of step 3. Test after each.
  7. Change the getter to return a copy or a read-only view. Test.3

Example

A team allows at most three members. Before the refactoring, a caller can add a fourth through the getter. After it, the team checks each change and hands out only copies.

import assert from "node:assert/strict";

// Before: the getter returns the list that the team owns.
class TeamBefore {
  #members = [];
  get members() { return this.#members; }
}
const leaky = new TeamBefore();
leaky.members.push("ana", "bo", "cy", "dee"); // the rule cannot run
assert.equal(leaky.members.length, 4);

// After: changes go through the owner; readers get a frozen copy.
class Team {
  static MAX = 3;
  #members = [];
  get members() { return Object.freeze([...this.#members]); }
  addMember(name) {
    if (this.#members.includes(name)) return;
    if (this.#members.length >= Team.MAX) throw new RangeError("team is full");
    this.#members.push(name);
  }
  removeMember(name) {
    this.#members = this.#members.filter((m) => m !== name);
  }
}

const team = new Team();
for (const n of ["ana", "bo", "cy"]) team.addMember(n);
assert.throws(() => team.addMember("dee"), RangeError);
assert.throws(() => team.members.push("dee"), TypeError); // frozen copy
team.removeMember("bo");
team.addMember("dee");
assert.deepEqual(team.members, ["ana", "cy", "dee"]);
console.log("encapsulate collection: tests pass");
Output
encapsulate collection: tests pass

Object.freeze makes the copy read-only, so a caller that tries to change it gets an error at once, not a change that has no effect. A frozen array is shallow: the elements, if they are objects, can still change.4

Language What the example shows
JavaScript a frozen copy from the getter, and add and remove methods, as above
Python a tuple from the getter, and a MappingProxyType view of a dictionary
Java List.copyOf in the getter, and the UnsupportedOperationException on a change
Go slices.Clone in the getter, because a slice shares its array
PythonGitHub
from types import MappingProxyType

class Team:
    MAX = 3

    def __init__(self):
        self._members = []
        self._roles = {}

    @property
    def members(self):
        return tuple(self._members)  # a copy that cannot be changed

    @property
    def roles(self):
        return MappingProxyType(self._roles)  # a live, read-only view

    def add_member(self, name, role="dev"):
        if name in self._members:
            return
        if len(self._members) >= self.MAX:
            raise ValueError("team is full")
        self._members.append(name)
        self._roles[name] = role

    def remove_member(self, name):
        self._members.remove(name)
        del self._roles[name]

team = Team()
for n in ("ana", "bo", "cy"):
    team.add_member(n)
roles = team.roles  # taken before the change below
team.remove_member("bo")
team.add_member("dee", role="lead")
assert team.members == ("ana", "cy", "dee")
assert roles["dee"] == "lead"  # the view shows the change
def set_role():
    roles["x"] = "y"

for change in (lambda: team.members.append("x"), set_role):
    try:
        change()
        raise AssertionError("expected an error")
    except (AttributeError, TypeError) as e:
        print(type(e).__name__)
print("encapsulate collection: tests pass")
Output
AttributeError
TypeError
encapsulate collection: tests pass
JavaGitHub
import java.util.ArrayList;
import java.util.List;

public class Main {
    static final class Team {
        static final int MAX = 3;
        private final List<String> members = new ArrayList<>();

        List<String> members() { return List.copyOf(members); } // an unmodifiable copy

        void addMember(String name) {
            if (members.contains(name)) return;
            if (members.size() >= MAX) throw new IllegalStateException("team is full");
            members.add(name);
        }

        void removeMember(String name) { members.remove(name); }
    }

    public static void main(String[] args) {
        Team team = new Team();
        for (String n : List.of("ana", "bo", "cy")) team.addMember(n);
        try {
            team.members().add("dee");
            throw new AssertionError("expected an exception");
        } catch (UnsupportedOperationException e) {
            System.out.println("the copy is unmodifiable");
        }
        team.removeMember("bo");
        team.addMember("dee");
        if (!team.members().equals(List.of("ana", "cy", "dee"))) throw new AssertionError(team.members());
        System.out.println(team.members());
        System.out.println("encapsulate collection: tests pass");
    }
}
Output
the copy is unmodifiable
[ana, cy, dee]
encapsulate collection: tests pass
package main

import (
	"errors"
	"fmt"
	"slices"
)

type Team struct{ members []string }

// Before: the slice header is copied, but the array behind it is shared.
func (t *Team) MembersLeaky() []string { return t.members }

// After: a clone, so the caller cannot change the team's array.
func (t *Team) Members() []string { return slices.Clone(t.members) }

func (t *Team) AddMember(name string) error {
	if slices.Contains(t.members, name) {
		return nil
	}
	if len(t.members) >= 3 {
		return errors.New("team is full")
	}
	t.members = append(t.members, name)
	return nil
}

func main() {
	t := &Team{}
	for _, n := range []string{"ana", "bo", "cy"} {
		_ = t.AddMember(n)
	}
	t.MembersLeaky()[0] = "zed" // changes the team
	fmt.Println(t.members)
	t.members[0] = "ana"

	t.Members()[0] = "zed" // changes only the copy
	fmt.Println(t.members, t.AddMember("dee"))
	if t.members[0] != "ana" {
		panic("the copy was shared")
	}
	fmt.Println("encapsulate collection: tests pass")
}
Output
[zed bo cy]
[ana bo cy] team is full
encapsulate collection: tests pass

When to use

  • The owner has rules about the collection. A size, an order, no duplicates, a total kept in step.
  • Callers change the collection through a getter. Each such caller is a place where a rule can be broken.
  • As part of a fix for Mutable Data. A collection that many callers can change is shared mutable data.

Pitfalls

A copy is not a view. A copy is a snapshot: later changes by the owner do not show in it. A view shows them. Python's MappingProxyType is a view: the documentation calls it a "Read-only proxy of a mapping" that "provides a dynamic view on the mapping’s entries".5 Choose by what the caller needs.

Shallow protection. A read-only list of mutable objects lets the caller change the objects. The Java documentation says so of its unmodifiable lists: "if the contained elements are themselves mutable, this may cause the List's contents to appear to change".6

A silent failure. A copy that the caller can change, such as slice() without a freeze, accepts the change and throws it away. The caller's code looks right and does nothing. A read-only view or a frozen copy fails at once.

The cost of a copy. A copy on each read of a large collection can be slow. A read-only view costs little, and an iterator over the elements can be enough for many readers.

Shared backing arrays. In Go, a slice returned from a getter shares its array with the field. The caller can change the elements in place. slices.Clone "returns a copy of the slice".7

Tools that do it

This refactoring is a sequence of steps, not one action of a tool. A tool can generate the accessors of a field; the add and remove methods, and the choice of a copy or a view in the getter, are the programmer's steps.

References

  1. Martin Fowler, Catalog of Refactorings, Encapsulate Collection, the entry
  2. Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 8, Organizing Data, Encapsulate Collection
  3. Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 7, Encapsulation, Encapsulate Collection, motivation and mechanics
  4. MDN Web Docs, Object.freeze(), the description, and the note that freeze is shallow
  5. Python documentation, types, MappingProxyType, class types.MappingProxyType
  6. Java SE 21 API, Interface List, Unmodifiable Lists
  7. Go standard library, package slices, func Clone

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/9BZ2PT/text.yaml