From: "David A. Black" Date: 2004-12-12T12:31:22+09:00 Subject: Re: Avoiding if requires type mutation -- evil.rb? Hi -- On Sun, 12 Dec 2004, Mikael Brockman wrote: > 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? One possibility would be have a Branchlike module and extend leaf objects with it when they became branches: module Branchlike def show_kids ... end # etc. end class Branch include Branchlike # etc. end class Leaf def add_node extend(Branchlike) end # etc. or something along those lines, maybe even more modularized. David -- David A. Black dblack@wobblini.net