Recently I Had conversation with my friend about good practices to create public API's We started to argue when we came to return types. He told me to return only widen type eg List insted of ArrayList. But in my opinion it all depend on problem we try to solve. I see nothing wrong in:
ArrayList foo();
When I want to say "Hey I am giving You ArrayList just to assure that u got access to elements in O(1) time"
In next example lets assume that there is no inforamtion in method signature or documentation about what kind of graph is returned or what representation is used
Graph foo();
What now? I might wonder whether this graph is directed or undirected , based on adjacency list or adjacency matrix. What is worst it could lead to code like:
Graph graph = foo();
if(graph instanceof DirectedGraph)
//code
which is a violation of Liskov substitution principle
What are your thoughts ?
Think about why would you even expose an API and why should somebody use it? The most obvious reason would be to hide complexity of a problem (and solution) from the user of your API.
The user of your API doesn't want to concern himself with implementation details and underlying complexities you have abstracted away from him in the first place.
As an API provider, generally speaking, you don't want to limit yourself to concrete implementation such as the ArrayList in this example. Even if you should use ArrayList most of the time as List interface implementation, it wouldn't be impossible to get yourself in the situation that LinkedList would preform better.
This would break your existing API and clients would have to re-implement the change obviously. This is exactly what you don't want to do.
Take a look at programming to interface concept.
Edit
Whether you can put directed graph and a graph behind same interface will depend on your use case. What you could do most certainly however is to provide two interfaces, one for graph and the other for directed graph, protecting users of your API from future changes in implementations of these graphs.
User of your API should be able to specify what kind of graph he wants, directed or not, and you should be able to hide from him concrete graph implementation details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With