I am designing a treeNode
class. While implementing the getPathToParentNode()
and getPathFromParentNode()
methods, I noticed that their functionality is essentially the same - they just operate on different data structures.
getPathToParentNode()
recursively adds all parent nodes into a queue, and then creates the path using the queue iterator.
getPathFromParentNode()
recursively adds all parent nodes into a stack, and then creates the path using the stack iterator.
To adhere to the DRY principle, I was thinking of extracting the duplicate code (recursively adding parents to a collection, and using the collection iterator to generate the path) into a separate function, and just passing it a queue from the first function and a stack from the second function.
// takes in a queue or a stack
// returns path to root node or path from root node respectively
List<ITreeNode<T>> getPath(Collection<ITreeNode<T>> pathCollection) {
pathCollection.add(this);
ITreeNode<T> parent = this.getParent();
pathCollection.add(parent);
while (parent.getParent() != null) {
pathCollection.add(parent.getParent());
}
return new ArrayList<ITreeNode<T>>(pathCollection);
}
However, the resulting helper function doesn't feel right. I don't think it performs something independent/worthwhile enough to justify its existence. Furthermore, its objective changes based on the type of collection passed into it, and perhaps as a consequence of that, it is difficult to name.
Is such a method considered "good" in light of the principles of object-orientated design? What would be a better approach?
Edit:
Similar question regarding method extraction in general (but the answers do not address my specific case): Should I extract specific functionality into a function and why?