CSE Roadmap

Core tier · about 3 hours · 7 parts

Part 3 of 7 · 2 min read

A worked failure

Counting insertions in a HashSet.

EJ gives a clear case. A program needs to count how many elements were ever added to a HashSet. The first idea is a subclass that overrides add and addAll, each adding to a counter before calling the parent.

class CountingSet<E> extends HashSet<E> {
    private int addCount = 0;

    @Override public boolean add(E e) {
        addCount++;
        return super.add(e);
    }
    @Override public boolean addAll(Collection<? extends E> c) {
        addCount += c.size();
        return super.addAll(c);
    }
    int getAddCount() { return addCount; }
}

Adding three elements with addAll should give a count of 3. It gives 6. The parent's addAll is built on top of add, though its documentation does not say so. The subclass counted 3 in addAll, then the parent called the overridden add three more times. This was run to confirm: the result is 6.

Fixes fail too. Removing the addAll override works only because the parent happens to use add, which is a detail that may change between releases. Looping over the elements in the override and calling add avoids the parent's addAll, but it reimplements parent behaviour, is slow to write, and cannot reach private parts of the parent. EJ also notes a subtler risk: if a later release adds a new method that can insert elements, the subclass will miss it, and the count will be wrong.

EJ's conclusion: inheritance violates encapsulation. A subclass relies on how its parent is built inside. It is safe within a package under one team, or when extending a class that was designed and documented for it. Extending an ordinary concrete class across package boundaries is dangerous. The problems apply to implementation inheritance only, and not to implementing an interface.

Check yourself: 1. Why is the count 6 and not 3? 2. Why is deleting the addAll override a fragile fix? 3. When does EJ call inheritance safe?