views:

176

answers:

2

I'm working on some application, that uses a TreeView control to represent business objects. Currently the link between business objects and TreeNodes is maintained through the Tag property of the TreeNode. Im not very happy with this, because I think the link is not "tight" enough. For example there could be an TreeNode object without a business object, also I want to update the TreeNode image depending on the business objact state. Therefore I derived my own special TreeNode class from TreeNode:

class ActionTreeNode : TreeNode
   {
      private Action mAction;

      public Action Action
      { get ... }

      public ActionTreeNode(Action action)
         : base()
      {
         if (action == null) throw new ArgumentNullException("action", "Paramter action must not be null.");

         mAction = action;
      }

    public void UpdateState()
      {
         switch (mAction.ActionState)
         {
            case ActionState.Passed:
               SelectedImageIndex = 3;
               ImageIndex = 3;
               break;
            case ActionState.Failed:
               SelectedImageIndex = 2;
               ImageIndex = 2;
               break;
            ...
         }

         return;
      }
   }

With this minimal approach I have to cast every time I call a property or method of the base class that returns a TreeNode object like in "(ActionTreeNode)myNode.Parent". The solution would be to override/overwrite every method or property and return an object of ActionTreeNode type. What do you think, is it more suitable to take the minimal approach or would you take the effort to reimplement all the methods, properties in order to avoid casting? Thanks.

+3  A: 

I like the minimal approach. If you are worried about cluttering your code with loads of cast statements simply create a method to do it for you in one place:

private ActionTreeNode GetParent(ActionTreeNode node)
{
    return node.Parent as ActionTreeNode;
}

// in some method:
ActionTreeNode parent = GetParent(someNode);
if (parent != null)
{
    // the parent is an ActionTreeNode
}

Don't forget the null check on the return value though, should the parent not be an ActionTreeNode...

Fredrik Mörk
I like this version as well. Maybe the ActionTreeNode ctor with string as parameter should be overridden as well.
crauscher
+2  A: 

I think the question is how long will it take you to take the effort to make it strongly typed.

Weigh up the cost of making everythign "tight" with the cost of you and other developers having a solid platform to work with.

Without knowing more, I personally think I would strongly type it as it will also mean that any changes to your business logic such as different types stored in the tree will result in a compile failure rather than possible unknown bugs.

Robin Day