Recall that Speed3 achieves its performance by representing groups of connected containers as parent-pointer trees. The root of each tree knows the size of its group and the per-container amount of water. Connecting two containers entails attaching the smaller of the two trees to the larger one—the so-called link-by-size policy.
Let’s focus on the connectTo operation because it benefits the most from a readability overhaul. Besides adding a proper documentation comment in Javadoc format, you can apply Extract Method and delegate the actual tree merging operation to a new support method, linkTo. In this way, connectTo becomes extremely simple: it finds the two group roots, checks whether they’re the same (in that case, no operation is performed), and finally merges the two trees according to the link-by-size policy.
This method also gets a small reliability enhancement: if you call it with a null argument, it throws an NPE with a custom error message, as shown in the following listing.
/** Connects this container with another. 1 Javadoc comment * * @param other the container that will be connected to this one */ public void connectTo(Container other) { Objects.requireNonNull(other, "Cannot connect to a null container."); 2 Precondition check Container root1 = findRootAndCompress(), 3 This support method is the same root2 = other.findRootAndCompress(); as in chapter 3. if (root1==root2) return; 4 Checks if they’re already connected if (root1.size <= root2.size) { 5 Link-by-size policy root1.linkTo(root2); } else { root2.linkTo(root1); } }
The support method linkTo performs the rest of the job. In turn, linkTo gives rise to another extracted support method called combinedAmount, which computes the per-container amount after merging two groups.
private void linkTo(Container otherRoot) { parent = otherRoot; otherRoot.amount = combinedAmount(otherRoot); otherRoot.size += size; } private double combinedAmount(Container otherRoot) { return ((amount * size) + (otherRoot.amount * otherRoot.size)) / (size + otherRoot.size); }
3.142.173.227