Application design - When should interfaces be used?
I kind of understand an interface as being a contract that can be applied to classes that would otherwise have nothing in common (ex: Comparable in Java). However, in what situation(s) would you have the reflex of adding an interface at the 开发者_如何学编程design stage?
Whenever you are using a statically typed language, and you want to make it possible for the developer to use your code while providing an alternate implementation - in other words, in such language it is necessary to achieve low(er) coupling.
Languages that use ducktyping as a rule, rather than strict type checking, for example, python, would generally have no need for interfaces.
"I kind of understand an interface as being a contract that can be applied to classes that would otherwise have nothing in common" - that's probably not the way to think about what an Interface is.
An Interface describes behaviour, and implementing an interface means a class enters into a contract to deliver that behavior.
By programming to an interface, rather than an implementation, you enable polymorphism and get more flexible code with lower coupling. For example, this method can take any instance that implements IQuack
:
public void DoSomething(IQuack quacker)
{
// ...
}
If you are designing a product and you know the product is going to interact with a type of device, service etc. but not necessarily which, you can use an interface to move forward with the overall architecture, PROVIDED that you know enough about those types of devices to write an interface that can be successfully used by any given device of that type. Of course if you are in the design phase, you better have that knowledge. It's not uncommon to do high level designs using only interface declarations. I'm not saying it's good or bad, but it seems to be a pretty common practice of those who use software (like Rose etc) to generate a skeleton from UML.
Another time would be if you know exactly what device you are going to use but you think there might be a chance that you will need to work with different or multiple types of that device down the road.
A third usage of interfaces is to reduce duplicated code. This is probably the only place people ever get carried away with interface usage and if it wasnt for that, I'd be comfortable saying dont ask "Should this be an interface?" but "Can this be an interface?".
精彩评论