Contracts: Interfaces vs Abstract Base Classes

Aug 29, 2010 at 11:24 AM

I thought I knew the answer to this one.  I was sure of it.  Everyone uses interfaces for publishing services to plug-ins, right?.

Please weigh in :)

I think there are three main choices:

  1. Interface is the contract
  2. Abstract Base Class (with optional implementation) is the contract
  3. Abstract Base Classes that implement Interfaces where the implementer can choose either for the contract

Advantages to #1 & #3:

  • A class may inherit several interfaces
  • Implementers with their own inheritance hierarchy are well-supported

Advantages to #2 & #3

  • Derived classes do not have to provide implementation for each behavior
  • I can add behavior to the base class contract, and implementers might be ok with a recompile
  • I can have fields (not sure I care?)

Disadvantage to #3

  • I'm an architect and I often lean towards this kind of best of all worlds solution.  But ITS MORE COMPLEX !!

At this point in time, I'm actually leaning toward #2.  I would really appreciate some guidance here :)



Aug 29, 2010 at 7:40 PM

I used to think 3 was the magic answer then Krzysztof (Cwalina) corrected me to the err of my ways. :-)

The biggest thing that 2 gives you is evolvability as you can add new methods and such in future versions without breaking backward compat.

3 looks alluring however it does not address 2. The reason is because your implementation than depends on the interface not the abstract class. Thus if you add a member to the interface you break BOTH consumers of the interface directly as well as consumers of the base class. Now the base class can be easily redistributed, which means the consumer is still in better shape though you still need to redeploy. In the case of the interface consumer however they are as broken as in 1.