When working with a single object there are a number of ways to segregate interfaces to it.
- Breaking it into smaller components that can be treated independently.
- Breaking it into simpler interfaces.
Both of these seem challenging to do with a tree. I think it would be nice to be able to do the following.
class Node : INodeData, INodePresentation { ... }
class Program
{
static void Main()
{
var node = new Node();
ManipulateNode(node);
PresentNode(node);
}
void ManipulateNode(INodeData nodeData)
{
foreach (INodeData child in nodeData.GetChildren())
nodeData.AddVertices(...);
nodeData.Rotate(...);
}
void PresentNode(INodePresentation nodePresentation)
{
nodePresentation.Color = Color.Blue;
nodePresentation.Size = 15;
nodePresentation.Paint();
foreach (INodePresentation child in nodePresentation.GetChildren())
PresentNode(child);
}
}
In this way different parts of the program could use the node according to a concise interface. But each interface I add will require more methods in the Node class which could be unmaintainable. It seems like the presentation and data should be defined in separate classes, but I can’t think of a good way to do this while maintaining the ability to traverse the tree. Any suggestions?
1
Probably the most common way is to create a Node<T>
with just the structure stuff and pass that into other functions that can use a T
to do the presentation stuff.
If you’re having difficulty inverting control when doing a recursive traversal, try passing a function into a traversal method, something like (forgive syntax as I don’t know C#):
void DepthFirstTraversal(Node<T> node, Function func)
{
func(node);
foreach (Node<T> child in node.GetChildren())
DepthFirstTraversal(child, func);
}
Another useful method to add functionality to a class, but somewhat less familiar depending on what languages you know, is using a mixin. It may or may not be useful in your case.
You can implement mixins in C# 3.0 using extension methods, and I believe there are third-party libraries to help. Mixins basically let you add functionality to a class without requiring it to implement an interface. The implementation is mixed in with the existing implementation of the class.
1
It seems like the presentation and data should be defined in separate classes, but I can’t think of a good way to do this while maintaining the ability to traverse the tree. Any suggestions?
The thing about interfaces is that you have to know them all up front. If you want to add new interfaces, you’ll need to use the Decorator pattern. But I think maybe you should re-evaluate your approach. Do you really need an interface for every new node manipulation? You can just add a function/static method that takes the tree as an argument and does whatever manipulation you need.
3