The question is a bit hypothetical. Let’s say I have an application that draws a tree. My structure controller implements the ITree interface that describes a normal tree with methods like: getChildren(), getParent() … Some parts of the app only needs to know that the structure implements ITree, so it can look for it’s children or parent. Thus getParent() is highly enough to return an ITree typed object. And so getChildren() can return a collection of ITree objects.
But:)
What if in the hypothetical TreeNode class I want to do something specific with a node’s children. If I use the getChildren() function of ITree, I have to cast them to TreeNode to be able to call the appropriate instance functions (that are not defined by ITree). Or I can use my own iterator to walk through the child nodes and do whatever I can (because this way those are really TreeNodes).
So the question is: is it suggested to use interface functions every time it’s possible, or object specific actions make sense sometimes?
Updated: [illustration added]
(It’s AS3 syntax but the point is the structure.)
So here is ITree:
public interface ITree {
function getParent():ITree;
}
And here is my TreeNode class:
public class TreeNode implements ITree {
private var parent:TreeNode
public function getParent():ITree {
return parent;
}
function foo():void {}
function bar():void {
// Version 1 - using the interface
(getParent() as TreeNode).foo();
// Version 2 - using custom object accessor
parent.foo();
}
}
Which one is better: version 1 or 2?
Thanks
You need to use ITree interface everywhere you can, to reduce coupling. If you need functionality that your interface do not provides, use TreeNode object, but try to avoid cast operation.