Programming an API and programming to an interface
It is often recommended to "program to an interface, not an implementation". It is useful to promote separation of concerns, and helps with unit testing. However, I was 开发者_C百科thinking about API programming.
Let's say I wrote an API and that API used a lot of "programming to interfaces". Let's also say that the API was insanely popular and used by many external clients. If one of the interfaces in the API had to change, that would require apps using the API to be recompiled.
My question is, how is such an issue avoided (or the impact of such changes reduced), or is it unavoidable? I am not an API programer and would like to know the best practice here. It seems to me that changing an interface that has existed for a long time and is widely used is a bad idea.
Published interfaces should never change. In the case that you have to augment functionality, just add a new interface.
To quote from MSDN:
When you create an interface, you are creating a definition that can never change after the interface definition has been released. This interface invariance is an important principle of component design, because it protects existing systems that have been written to use the interface.
When an interface is clearly in need of enhancement, a new interface should be created. This interface might be named by appending a "2" onto the original interface name, to show its relationship to the existing interface.
I think a distinction can be made here between APIs to services and APIs to libraries.
In the case of services, those APIs should not be broken. Adding interfaces to these will not impact existing consumers.
Changing a library API only requires a recompile if the consumer wants to use the newer version of the library. This is likely going to go along with a recompile anyway, and simply adding to the interface won't require existing code change (you can mark deprecated methods with attributes, if applicable).
If you actually need to make a breaking change to the API, then yes, consumers will have to change their code to make it buildable.
While this is not to be taken lightly, there are many very popular libraries whose APIs have changed significantly over time (Fluent NHibernate comes to mind), and from my perspective, at least, the pain of updating my project is minimal, especially given the improvements that come along with those updates.
I think that for libraries, there is an expectation that some adaptation may be required when adopting a new version. Likewise, there is an expectation that where the API does not change, working code should not be rendered broken by a new version.
精彩评论