CSE Roadmap

Core tier · about 3 hours · 7 parts

Part 4 of 7 · 2 min read

The composition fix

Wrap, forward, and add the new behaviour.

EJ's cure: do not extend the class. Give the new class a private field holding an instance of the old one. This is called composition. Each method of the new class calls the matching method on the held object and returns the result, which is forwarding. The new class is a wrapper.

class CountingSet<E> implements Set<E> {
    private final Set<E> inner;
    private int addCount = 0;

    CountingSet(Set<E> inner) { this.inner = inner; }

    public boolean add(E e) { addCount++; return inner.add(e); }

    public boolean addAll(Collection<? extends E> c) {
        addCount += c.size();
        return inner.addAll(c);
    }

    int getAddCount() { return addCount; }

    // the remaining Set methods only forward to inner
    public int size() { return inner.size(); }
    public boolean isEmpty() { return inner.isEmpty(); }
    public boolean contains(Object o) { return inner.contains(o); }
    public Iterator<E> iterator() { return inner.iterator(); }
    public Object[] toArray() { return inner.toArray(); }
    public <T> T[] toArray(T[] a) { return inner.toArray(a); }
    public boolean remove(Object o) { return inner.remove(o); }
    public boolean containsAll(Collection<?> c) { return inner.containsAll(c); }
    public boolean retainAll(Collection<?> c) { return inner.retainAll(c); }
    public boolean removeAll(Collection<?> c) { return inner.removeAll(c); }
    public void clear() { inner.clear(); }
}

Run with new CountingSet<>(new HashSet<>()) and addAll of three names: the count is 3. The inner set's own addAll calls its own add, not the wrapper's, so nothing is counted twice. The wrapper also works with any Set, such as a TreeSet, since it holds the interface. EJ's version moves the forwarding into a reusable forwarding class, so that each wrapper writes only the methods it changes.

The wrapper's cost is a long list of forwarding methods. That is boilerplate, but it is simple and safe. EJ notes one more limit: wrappers are not well suited to callback frameworks where the wrapped object passes itself to other objects.

Forwarding

Forwarding means a method passes the call on to the same method of a held object and returns its result.

Example: size() in the wrapper returns inner.size().

Check yourself: 1. Why does the wrapper count 3 and not 6? 2. What does the wrapper hold in its field? 3. What is the main cost of the wrapper?