It's an OO-solution I'm after! Sure in this simple case I could add a
Process method to the Node class but what if I where to do something
more interesting in the Process method or the Node classes where not
under my control (CodeDom classes for instance)?


public class NodeProcessor {
   private StringBuilder _sb = new StringBuilder();
 
   void Process(Node node) {
     if (node is BinaryNode) {
        BinaryNode bnode = (BinaryNode)node;
        Process(bnode.Left);
        _sb.Append(bnode.Operator);
        Process(bnode.Right);
     }
     else if (node is SetNode) {
        SetNode snode = (SetNode)node;
        bool first = true;
        foreach (Node n in snode.Nodes) {
            if (!first)
               _sb.Append(",");   
            Process(n);
            first = false;
        }
     }
     else if (node is LiteralNode) {
        LiteralNode lnode = (LiteralNode)node;
        _sb.Append(lnode.Value);
     } 
     // 10-15 other subclasses to handle        
     else if (...) { }
   }

   public string Result {
       get { return _sb.ToString(); }
   }
}

I could use the Visitor approach but that limits the control you have
while processing the node tree, for example the comma handling for the
SetNode processing.

Basically I'm after a solution that is maintainable, object-oriented and
fast :)

// Kristofer

 
-----Original Message-----
From: Discussion of advanced .NET topics.
[mailto:[EMAIL PROTECTED] On Behalf Of John Brett
Sent: den 17 juli 2006 18:10
To: [email protected]
Subject: Re: [ADVANCED-DOTNET] Multiple downcasts pattern

<snip>

> My problem is when you have a lot of subclasses to Node that you want
to
> process in different ways the second example gets very deeply nested
and
> hard to maintain. Is there a better way to deal with multiple
downcasts
> like this?

The example above is crying out for an object-oriented solution. Add an
abstract "Process" method to your base class, and lose all of the casts.

If you absolutely can't do that, then you could build an if/elseif tree
based
on node.GetType(), although even that's pretty poor practice unless you
absolutely can't use the OO approach.

John

===================================
This list is hosted by DevelopMentor(r)  http://www.develop.com

View archives and manage your subscription(s) at
http://discuss.develop.com

===================================
This list is hosted by DevelopMentorĀ®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com

Reply via email to