The title is hardly understandable, but I'm not sure how to summarize that another way. Any edit to clarify is welcome.
I have been told, and recommended to use interfaces to improve performances, even in a case which doesn't especially call for the regular "interface" role. In this case, the objects are big models (in a MVC meaning), with many methods and fields.
The "good use" that has been recommended to me is to create an interface, with its unique implementation. There won't be any other class implementing this interface, for sure. I have been told that this is better to do so, because it "exposes less" (or something close) to the other classes which will use methods from this class, as these objects are referring to the object from its interface (all public methods from the implementation being reproduced in the interface).
This seems quite strange to me, as it seems like a C++ use to me (with header files). There I see the point, but in Java?
Is there really a point in making an interface for such unique implementation? I would really appreciate some clarifications on the topic, so I could justify not 开发者_开发问答following such kind of behavior, and the hassle it creates from duplicating all declarations.
Edit: Thanks everybody for the answers, it was really helpful and instructive (most of them, not only the "accepted" one).
There is clearly no advantage in performance, and I now have a larger scope of the interest that can come from it (depending on the situation), besides the usual OO role of the interface.
Using interfaces has not much to do with performance (except maybe the performance of the development team, i.e. the speed of development). It is more about keeping dependencies under control, and separating unrelated parts of the program.
If you depend directly on concrete class C in your code, that code is more difficult to unit test, among others. If you instead depend on an interface, it is a snap to create a mock implementation in your unit tests.
Of course, you may not need to pull up all the methods of your class into the parent interface. In fact, you may not need one single parent interface. Analyze the usage of that class and (especially with a big class like yours) chances are, you find two or even more distinct groups of methods, used by different clients (e.g. one group of clients only queries object state, while the other updates it). This makes it possible to create two or more distinct interfaces, which are much simpler and cleaner each.
This analysis may even lead to the conclusion that your class is trying to do too many things (instead of having a single responsibility), and you would be better of extracting some of its contents into a separate class! In other words, once you start thinking about - and programming to - interfaces, you start to see design on a different level, and this may lead to better design solutions.
All this told, if after all the analysis above you still see no use of the interface for your model class, make a note about it. Revisit it after, let's say, half a year. Then, if you still feel it hasn't paid for itself, just dump it. Interfaces - like any other element of your program - should always have a clear purpose and a reason to exist (and a better one than "my coworker told me to create it"). They are no panacea. If you use them cleverly, you make your code better. If you use them stupidly, you make your code even worse. The fact that you posted this question here means you want to learn how to use them cleverly, which is good :-)
First of all, interfaces do not have any performance benefit. If anything, the use of polymorphic code and dynamic dispatching (like C++ virtual functions) carries a cost.
Think of interfaces not as something that adds expressive power, but as something that constraints you into writing better. Interfaces are important, IMHO, for three reasons:
1) They can help you write code with better encapsulation, data hiding, stability, etc.
2) They can help you separate behavior and implementation by thinking about what you are trying to represent rather than how to implement it. Not being able to add state does a lot to prevent you from adding it accidently.
3) They let you extend things in the future and separate your code into independent units. Each component knows only what it needs to know about other services.
You can do some of this with abstract classes that have no state, but interfaces are specifically meant for this and carry the benefit of multiple subtyping. In C++, such abstract classes are often used to mimic interfaces.
Now if you can write a huge system with the perfect level of encapsulation directly with classes, that's great. But with classes there is often a temptation to bring in state prematurely and create connections.
Should you always write interfaces? Of course not. Always be afraid of "Always" rules :) It's always a balance between wasted work and =useless complexity and the benefits. With time and experience, you get the instinct for it.
Also, header files are essentially interface files. They generally define allowed behavior but no state. If you learn C and then Java (some schools do that), you learn about ADTs in C, and then about ADTs in Java using interfaces.
Briefly -
- you're documenting the API to that module explicitly in an interface object. It will be clearer to your users and perhaps make you think about what goes in that interface
- you can provide multiple interfaces on the same object, and restrict consumers in what they can do (e.g. read-only vs read-write)
- mocking frameworks make use of interfaces, and mocking classes is a very powerful test technique
In fact, using interfaces instead of classes allows you three things :
- Dstinguish the contract from its implementation : the contract is the interface (it's what you declare you'll do) and the class is obviously the implemenation
- Provide easily altrnative implementation. Typical examples of this imply replacing a storage mechanism by another without modifying user code (like repalcing MySQL by, say, Project Voldemort)
- As a benefit of 2 (and this time easily extendable to model elements), interfaces allow you to do kind of white box testing : by using a mocking framework (JMock, EasyMock, ...), you'll repalce your implementation of the interface, which behaviour may be suspicious, by a so-called "mock" returning exactly what you expect for your test. This will allow your test to not only check one component, but also ensure the error come from that component, and not from its inner contractors (the interface you give him).
This reason for using interfaces seems also very strange to me. I don't see how there could be any performance advantage, and if there was one it would be probably completely unimportant.
That said, there are some reasons to use interfaces even if there is currently one implementation. It might be easier to extend later or provide alternative implementations. (Though there is an extract interface refactoring in any decent IDE.) It might be much easier to test: if you want to test a class that uses other classes only through interfaces, you can easily provide mock objects for the other classes.
Here's 2 links that explain why you'd want to do this:
http://www.artima.com/lejava/articles/designprinciples.html http://pragmaticjava.blogspot.com/2008/08/program-to-interface-not-implementation.html
It has nothing to do execution performance(more to do with programmer(you) performance), in that you're decopling users of a class from its implemenation - among other things for easing testability and maintainability.
There won't be any other class implementing this interface, for sure.
Maybe not this year, but next year there might.
Interfaces are incredibly overused in Java partly because of the language design and partly because people think making lots of interfaces is good design.
Abstract classes would be superior to interfaces if Java allowed multiple inheritance. Scala a new programming language for the JVM has a concept of Traits which are essentially abstract classes with MI capability.
The advantage to an abstract class is that you can add behavior to the abstract class with out breaking existing classes that extend it. Thus an abstract class is also better as an extension mechanism (plugin) then interfaces.
Unfortunately JMock and its brethren encourage lots of interfaces for BDD testing but this is not necessarily true because there are at least a couple of libraries to mock concrete objects.
This question targeted C#, but I think it applies as well. The highest voted answer says that defining an interface for every class is just code noise.
There is a relatively common development dogma that there should be an interface for pretty much everything. As far as I can tell, this is based either on a cargo-cult mentality in regard to "program to an interface, not an implementation" (which most definitely does not require you to litter you code with interfaces all over), or on doing test-driven-development with older mocking frameworks that couldn't mock concrete classes.
Disregard such nonsense.
Yet another way to misuse interfaces?
There are no obvious performance gain using interfaces. Conversely, it may have a negative performance impact due to RTTI (Based on your compiler's features)
精彩评论