Reputation: 3565
I am busy writing an API which modifies a graph. To control what I am exposing to the users of the API I am using interfaces.
The interfaces exposing the methods which will be used are as follows. Essentially this is what the user will see:
public interface GraphEditor{
Edge addEdge(AsbtractNode f, AbstractNode t)
}
public interface AbstractNode{
}
public interface ExampleNode1 extends AbstractNode{
}
public interface ExampleNode2 extends AbstractNode{
}
The implementation structure is:
public class GraphEditorImpl implements GraphEditor{
public Edge addEdge(AsbtractNode f, AbstractNode t){
AbstractNodeImpl from = (AbstractNodeImpl) f;
AbstractNodeImpl t = (AbstractNodeImpl) f;
from.getVertex().addEdge(t.getVertex);
}
}
public class AbstractNodeImpl implements AbstractNode{
Vertex vertex; //Must remain hidden from users
public Vertex getVertex(){
return vertex;
}
}
Inside graph editor I have a method which allows the user to add and edge between two nodes addEdge
. This method has to cast AbstractNode
to AbstractNodeImpl
in order to access the getVertex()
method which is needed to get the 'Vertex'.
I cannot expose getVertex()
within the AbstractNode
interface as I cannot have users working with the Vertex
directly. Is there any way to achieve this sort of functionality without having to cast from the interface into the implementation?
Upvotes: 1
Views: 106
Reputation:
Your current model will not work. You can make it so that the AbstractNode
interface only contains information on on the node, and the GraphEditor
interface contains all the methods need to edit the graph:
interface AbstractNode {
// identify this node
// this class only contains the ID of this node
}
interface GraphEditor<T extends AbstractNode> {
// this class stores the graph
void addEdge(T a, T b);
}
Upvotes: 3
Reputation: 26926
It is a bad design using a type as a parameter and cast it to a different subtype inside the method.
What happens if a user create a custom class that extends AbstractNode
?
You need to consider also that when you write an API.
If there is no other possibility you need to check in your code that the real type of the parameter is AbstractNode, if not you need to throw at least an IllegalArgumentException
Upvotes: 0
Reputation: 11
Add the function addEdge(AbstractNode)
to the AbstractNode
interface.
The implementation of this function can be getVertex().addEdge(that.getVertex)
or whatever is appropriate to the implementing class.
And if you don't want people to be able to access the Vertex
instance, make getVertex()
private or protected.
Upvotes: 1