From: Mikael Brockman Date: 2004-12-12T12:53:17+09:00 Subject: Re: Avoiding if requires type mutation -- evil.rb? "David A. Black" writes: > 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. > > > > ... > > > > 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. Hm. Yes, that could work. The only issue I can see with it regards removing kids: I'd have to keep extending Branchlike and Leaflike, which would make leaf.is_a? Branchlike true. I'll probably never use #is_a?, though. The proxy thing is kinda starting to grow on me though. It's so simple. Node#become would be easy to make. I think I prefer that.