Part 6 of 6 · 2 min read
Exercises
Easy
Easy 1: Find the tree (20 minutes)
List three things in everyday software that are trees of parts and groups. For each, name the leaf and the composite.
Done when: three entries each have a leaf and a composite.
Hint
A folder, a menu and a drawing group each hold things of their own kind.
Easy 2: Run the tree (20 minutes)
Type the Node, FileNode and Folder code and build the example tree. Print it and its size.
Done when: you print the tree, 22 for the root and 12 for docs.
Hint
A folder's size is the sum of its children's sizes.
Easy 3: Walk it (20 minutes)
Add the iterator and print the names with a for-each loop.
Done when: you print [a.txt, docs, b.md, c.md, empty].
Hint
Implement Iterable<Node> on Folder.
Medium
Medium 1: Menu (45 minutes)
Build a MenuItem leaf and a Menu composite, both with price() and print(). A menu's price is the sum of its parts.
Done when: a menu with two items and a submenu prints the right tree and total.
Hint
price() on a menu loops over children.
Medium 2: Breadth-first iterator (45 minutes)
Write a second iterator that visits the tree level by level, with a queue.
Done when: it prints the root's children first, then the next level, in order.
Hint
Add children to a queue as you take each folder.
Medium 3: Find by name (45 minutes)
Add find(String name) to the tree that returns the first node with that name, using the iterator.
Done when: find("c.md") returns the file and find("zzz") returns nothing.
Hint
Return an Optional<Node>.
Hard
Hard 1: Organisation chart (90 minutes)
Model people and teams. A team has a manager and members, and headcount() counts everyone below. Support moving a person between teams.
Done when: a move changes both team counts and the total stays the same.
Hint
Each person belongs to one team at a time.
Hard 2: Guard against cycles (90 minutes)
Show that adding a folder to itself, or to one of its own children, creates an endless loop. Add a check in add to prevent it.
Done when: a test shows the loop, and the check rejects the bad add with a clear message.
Hint
Walk up the parents, or search the new child's subtree for the parent.
Hard 3: Safe and transparent (90 minutes)
Write the file tree twice: with add on the common interface, and with add only on the folder. Compare client code and failure cases.
Done when: a table compares both designs for safety, simplicity and where errors appear.
Hint
The transparent version needs a failing add on files.