Interfaces (interface/abstract class) are not abstractions?

后端 未结 4 1879
情书的邮戳
情书的邮戳 2021-01-02 04:43

Of late, I have been reading posts which talks about the supposed wrong notion that interfaces are abstractions. One such post is http://blog.ploeh.dk/2010/12/02/InterfacesA

4条回答
  •  心在旅途
    2021-01-02 05:00

    I'd say I disagree with many of the points in the linked articles:

    • interfaces are contracts. The contract has two parts - the method signature (purely syntactic) and the documentation.

    • interfaces are abstractions. I couldn't see an example of LSP violation. The IRectangle example is not a good one at all. The same thing can be said about Set extends Collection, where adding duplicates is disallowed. If you are passed a Collection you might be surprised it disallows duplicates. With the Collection interfaces this is taken care of by documenting that implementors may add restrictions

    • Leaky abstractions are inevitable. But this entirely depends on the designer. And btw "interfaces are leaky abstractions" means they are abstractions.

    • The guys seem to have missed "exposure" to unit-testing. Mock implementations are a very good reason to use an interface (although you can mock concrete classes as well).

    • A very good example from our current project - initially we has only one DAO implementation - one taking stuff form the database. But later we switched some of the operations to a dedicated search engine. We add another implementation of the DAO, and there we go. So having an interface with one implementation initially paid off.

    • Btw, initially SortedSet had only one implementation in the JDK - TreeSet. Now it has two. And many more from external libraries.

    • finally, interfaces (as a language construct) are a way to describe a class' functionality with the extra feature of disallowing any implementation slipping in. That is - interfaces are a hard to misuse way of providing abstraction.

    That all said, you don't need an interface for everything. But it depends on the concrete case. I, for example, don't use interfaces for helper classes. And a valid point of the articles is the "programming to an interface" does not necessarily include the interface keyword. The "public interface" of a class is (theoretically) the set of its public methods.

提交回复
热议问题