« Why do people check Javadocs into version control? | Main | RFCs make me want to smoke crack »

If you can't type them, join them

Here's Martin Fowler on frigging with base classes:

"Many people get very disturbed by this kind of thing, but it does a great deal to simplify the logic of code that sweeps through the composite structure. I think of it as getting the leaf class (elephant) to provide a simple implementation as a courtesy to its role as a node in the hierarchy."
          class Elephant < Node
            def num_elephants
              return 1
            end
          end

I would go a bit further, and make this useful for non-Elephants. In 'Scruby' (Statically Compiled Ruby):

  class Node
    def num(type)
      if type is Node 
         return 1 
        else 
          return 0
    end
  end

Now subclass it where the Elephant Node returns 1 when supplied its type. Why? Two reasons. First, putting Elephants in boxes is just the beginning. More frigs are bound to occur, resulting in you AddingMoreStuffToTheBaseClass. That way lies honest to goodness Lovecraftian madness (or the DOM). Second, if you're going to make a hack, you might as well make a judicious hack so that you or someone else can dig your way out later. Above you've got the option to send a message to all types of Node and they can decide for themselves what type they are.

There are other ways to deal with this, the ultimate choice depending of course on the language at hand. For folks programming with composite structures in Java or C#, these guys have it nailed.

While the term CourtesyImplementation is tad Newspeak, it's good to see an industry leader outlining a trade-off instead of a fantasy world where trade-offs Just Don't Happen.


[franz ferdinand: michael]


August 17, 2004 03:54 PM

Comments

Trackback Pings

TrackBack URL for this entry:
http://www.dehora.net/mt/mt-tb.cgi/1390