M
Mikael Brockman
I am writing a tree editor. The algorithm for displaying a node is
recursive. On leaf nodes, it's trivial. Branches need to display all
their kids.
I would like to implement this with three classes: the Leaf, the
Branch, and the Node. Leaf & Branch are subclasses of Node.
The problem: nodes are mutable. You can add a kid to a node. If that
node's a Leaf, it needs to become a Branch.
I can think of three solutions.
- Add a wrapper object around every Node, and give it a #replace
method.
- Use Object#become from evil.rb.
- Represent nodes and leaves as instances of the same class, and use if
statements.
I'd like #2 the best if evil.pb wasn't likely to win awards for being
the nastiest hack of all time. (Props to the authors!) I don't like #1
or #3, but if I had to choose, I'd go with #3.
Making nodes non-mutable would be annoying and unintuitive, I think.
What would you do?
recursive. On leaf nodes, it's trivial. Branches need to display all
their kids.
I would like to implement this with three classes: the Leaf, the
Branch, and the Node. Leaf & Branch are subclasses of Node.
The problem: nodes are mutable. You can add a kid to a node. If that
node's a Leaf, it needs to become a Branch.
I can think of three solutions.
- Add a wrapper object around every Node, and give it a #replace
method.
- Use Object#become from evil.rb.
- Represent nodes and leaves as instances of the same class, and use if
statements.
I'd like #2 the best if evil.pb wasn't likely to win awards for being
the nastiest hack of all time. (Props to the authors!) I don't like #1
or #3, but if I had to choose, I'd go with #3.
Making nodes non-mutable would be annoying and unintuitive, I think.
What would you do?