I have a question about the merits of two different approaches to implementing a recursive method. I’ve always followed the approach of version 1, i.e., accepting a single Node parameter, but I recently encountered the style used in version 2, which accepts a collection of Nodes.
Consider the following Node class, along with the 2 versions of the Visit method:
class Node
{
public List<Node> children = new List<Node>();
// other data members
}
Version 1 accepts a single Node parameter:
Visit(Node n)
{
DoSomethingUsefulWith(n);
foreach (Node child in n.children)
Visit(child);
}
Version 2 accepts a collection of Nodes:
Visit(List<Node> nodes)
{
foreach (Node n in nodes)
{
DoSomethingUsefulWith(n);
Visit(n.children);
}
}
Are there any benefits, even stylistically, to using one form over the other? Should the choice be based solely on whether you’re starting with a single Node vs a collection of Nodes, even though it would be trivial to use either method version in either case?
I wouldn’t implement version 2, always version 1.
Version 2 is basically version 1 in a for-each loop
If you later on decide that you want to call the method with one parameter you can always re-use version 1.
If you only have version 2 and one node you have to create a dummy list to use version 1.
I don’t think that performance is a real issue here. Both methods have one (by reference) argument, they should use about the same amount of memory.
However .NET might be able to optimize one of the two a bit better. Profile both methods to be sure.