469,085 Members | 1,008 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,085 developers. It's quick & easy.

Interface vs. Abstract Class

I'm trying to determine if there's a general rule for when an Interface
should used vs. an Abstract Class. Is there any design advantage to using
one or the other?

Brad
Nov 17 '05 #1
18 3489
Bradley wrote:
I'm trying to determine if there's a general rule for when an Interface
should used vs. an Abstract Class. Is there any design advantage to using
one or the other?


Seems a good place to start is by looking at the difference between the
two. For starters someone implementing an interface can implement
multiple interfaces and can also have a base class. With an abstract
base, that is the only base class they can have, although they could
implement other interfaces. What this means is that two classes that
are completely unrelated in any other way could both implement your
interface. With an abstract class, anyone inheriting from your abstract
class would be more closely related in that they would all have a same
base type (your abstract class) in their inheritance hierarchy.

With an abstract class you can, if you want or need, provide some
implementation in the abstract class. An interface can provide no
implementation.
--
Tom Porterfield
Nov 17 '05 #2
Well, if the implementations share a lot of code, you're probably looking at
an abstract class. On the other hand, if you just want the programming
interface to conform to a certain set of sigunatures, and there is little or
no possibility that the implementations will share code, you're probably
looking at an Interface.

That's it in a nutshell. Broadly speaking.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Ambiguity has a certain quality to it.

"Bradley" <br************@roche.com> wrote in message
news:OD**************@TK2MSFTNGP14.phx.gbl...
I'm trying to determine if there's a general rule for when an Interface
should used vs. an Abstract Class. Is there any design advantage to using
one or the other?

Brad

Nov 17 '05 #3
Thanks for the responses. It sounds like unless you need to inherit
implementation code, there's very little difference.

Brad

"Kevin Spencer" <ke***@DIESPAMMERSDIEtakempis.com> wrote in message
news:eK**************@TK2MSFTNGP15.phx.gbl...
Well, if the implementations share a lot of code, you're probably looking at an abstract class. On the other hand, if you just want the programming
interface to conform to a certain set of sigunatures, and there is little or no possibility that the implementations will share code, you're probably
looking at an Interface.

That's it in a nutshell. Broadly speaking.

--
HTH,

Kevin Spencer
Microsoft MVP
.Net Developer
Ambiguity has a certain quality to it.

"Bradley" <br************@roche.com> wrote in message
news:OD**************@TK2MSFTNGP14.phx.gbl...
I'm trying to determine if there's a general rule for when an Interface
should used vs. an Abstract Class. Is there any design advantage to using one or the other?

Brad


Nov 17 '05 #4
Ditto. But when I do it, I tend to create both (i.e., the abstract/base
class implements an interface). I've found this useful to have when all of
a sudden I find the abstract class doesn't cut it anymore, and have to go to
the interface. I figured since it's done a lot in the framework, I may as
well do it too!!

Derrick
"Kevin Spencer" <ke***@DIESPAMMERSDIEtakempis.com> wrote in message
news:eK**************@TK2MSFTNGP15.phx.gbl...
Well, if the implementations share a lot of code, you're probably looking
at an abstract class. On the other hand, if you just want the programming
interface to conform to a certain set of sigunatures, and there is little
or no possibility that the implementations will share code, you're
probably looking at an Interface.

That's it in a nutshell. Broadly speaking.

--
HTH,

Kevin Spencer
Microsoft MVP
.Net Developer
Ambiguity has a certain quality to it.

"Bradley" <br************@roche.com> wrote in message
news:OD**************@TK2MSFTNGP14.phx.gbl...
I'm trying to determine if there's a general rule for when an Interface
should used vs. an Abstract Class. Is there any design advantage to
using
one or the other?

Brad


Nov 17 '05 #5
Brad,

This is how I would start: Initially if I am not sure which one to
use, then I would use an Interface. Now, once you have a few
implementation classes for that interface, you may realize that there
are some methods that have code that are always the same between the
classes. You can extract out those methods; one way is to extract them
out to a common parent class. In this case, the new implementation
class would need to inherit from the parent class and implement the
interface. If the parent class and the interface are always used
together, then you may want to use an abstract class instead to group
them together, so you won't be accidentally using just the interface
but not the parent class.

HTH,
Alex

Nov 17 '05 #6
Bradley... After you code for a while you will discover the sudden need
to add a method to an interface. This is a bad place to be. Changing the
interface will break all clients. Soooooo. You need to refactor the
interface so that you can easily extend the framework. You need to be
sure about the interface. If you are not sure about the interface you
may want to start with an abstract class. If you add a method to the
abstract class, you can add a default implementation and not break any
clients.

Regards,
Jeff
Is there any design advantage to using
one or the other?
*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #7

"Bradley" <br************@roche.com> wrote in message
news:OD**************@TK2MSFTNGP14.phx.gbl...
I'm trying to determine if there's a general rule for when an Interface
should used vs. an Abstract Class. Is there any design advantage to using
one or the other?

Brad


Interfaces are most appropriate when defining contracts between types that
are invariant over time.
You also need to use interfaces when you want to provide polymorphic value
type hierarchies (value types cannot inherit from other types).
But in general you would prefer abstract types over interfaces as they
version much better and they are extensible.

Willy.
Nov 17 '05 #8
Jeff Louie <je********@yahoo.com> wrote:
Bradley... After you code for a while you will discover the sudden need
to add a method to an interface. This is a bad place to be. Changing the
interface will break all clients. Soooooo. You need to refactor the
interface so that you can easily extend the framework. You need to be
sure about the interface. If you are not sure about the interface you
may want to start with an abstract class. If you add a method to the
abstract class, you can add a default implementation and not break any
clients.


On the other hand: use mock frameworks for unit testing is *much*
easier with interfaces.

I do take your point about breaking changes, but it's worth noting that
lots of people are in lots of different deployment situations. In many
cases, you know all the implementors of an interface, and can change
them all appropriately. In many other cases, you really can't do that -
so you have to end up creating another interface, etc. (Icky.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #9
Jon... In fact, I relentlessly code to an interface in this situation.
If I need to add a method to the interface the compiler immediately
finds all of the invalid classes for me!!!!! Then I just update the
classes until the compiler stops complaining :).

Regards,
Jeff
In many cases, you know all the implementors of an interface, and can
change them all appropriately.

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #10
As Uncle Chutney sez, "it's six of one of half of one of half of a dozen of
the other."

I don't believe it is possible from either angle to write code that doesn't
need rewriting at some point. At least I know that I'm not that good! ;-)

--

Kevin Spencer
Microsoft MVP
..Net Developer
Ambiguity has a certain quality to it.

"Jeff Louie" <an*******@devdex.com> wrote in message
news:Ov**************@TK2MSFTNGP14.phx.gbl...
Jon... In fact, I relentlessly code to an interface in this situation.
If I need to add a method to the interface the compiler immediately
finds all of the invalid classes for me!!!!! Then I just update the
classes until the compiler stops complaining :).

Regards,
Jeff
In many cases, you know all the implementors of an interface, and can
change them all appropriately.

*** Sent via Developersdex http://www.developersdex.com ***

Nov 17 '05 #11
When making this decision, I always go back to O-O basics. Let's say I
have a class Derived and I'm trying to decide whether to make it a
derived class of an abstract base class Base, or simply have it
implement interface Inter.

First, I ask myself whether Derived "is a" Base. That is, in the real
world, is Derived a special-case example of Base, or is that too odd a
concept? If I need the same functionality across classes that don't
have a strong enough relationship that I want to entrench that
relationship in my class hierarchy, then I go with the interface Inter.

For example, if Derived is an InHousePurchaseOrder, then I'd say that
it's certainly a special case of an abstract PurchaseOrder. Should
PurchaseOrder derive from another base class called Document? That's a
tougher decision: there are lots of other documents in my system that
have nothing in particular to do with purchase orders, other than that
they are also documents. I don't think that I would want to build up my
inheritance hierarchy by relating classes that are otherwise unrelated
in the real world... the relationship between, say, a purchase order
and a manufacturing drawing is just too tenuous for an important class
relationship like inheritance. I would go instead for an IDocument
interface.

That, to me, is really the crux of it: do these things have a
real-world "is-a" relationship, or not? In Java and C# I have only
single inheritance to work with, so having two classes participate in
that "is-a" relationship is a big deal in these languages. C++
programmers can be a bit more relaxed about the decision.

Yes, I too sometimes create abstract classes just to keep common code
in one place, but I usually do that only with strictly internal,
"housekeeping" classes, and then only in cases in which an interface is
clearly inadequate.

Nov 17 '05 #12

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Jeff Louie <je********@yahoo.com> wrote:
Bradley... After you code for a while you will discover the sudden need
to add a method to an interface. This is a bad place to be. Changing the
interface will break all clients. Soooooo. You need to refactor the
interface so that you can easily extend the framework. You need to be
sure about the interface. If you are not sure about the interface you
may want to start with an abstract class. If you add a method to the
abstract class, you can add a default implementation and not break any
clients.
On the other hand: use mock frameworks for unit testing is *much*
easier with interfaces.


How would it be easier? I don't see how it would be much different then
using an abstract base class?

I do take your point about breaking changes, but it's worth noting that
lots of people are in lots of different deployment situations. In many
cases, you know all the implementors of an interface, and can change
them all appropriately. In many other cases, you really can't do that -
so you have to end up creating another interface, etc. (Icky.)


The MSFT design guidelines (see Krzysztof Cwalina blog) suggest using
abstract base classes rather then interfaces. You get all the advantages of
an interface with fewer limitations. I tend to agree with these guidelines.
From an abstract :-) perspective, how does an interface differ from an
abtract base class with no implementation?

Nov 17 '05 #13
David Levine wrote:
The MSFT design guidelines (see Krzysztof Cwalina blog) suggest using
abstract base classes rather then interfaces. You get all the advantages of
an interface with fewer limitations. I tend to agree with these guidelines.
From an abstract :-) perspective, how does an interface differ from an
abtract base class with no implementation?


I think it comes down to your requirements and how much flexibility you
want to allow. With an abstract base class you certainly do *not* get
all the advantages of an interface. If you use an abstract base class
you are forcing everyone to use that as their base if they want to play
in your game. There are times when this would be desired. However that
means that a class with some other base class won't be able to
participate. If you were to instead use an interface then anyone could
implement your interface regardless of their inheritance chain. The
advantage to that is that two otherwise completely unrelated classes
could plug into your design as long as they implemented your interface.

I don't think anyone can make a blanket recommendation that either an
abstract base class or an interface is always the right answer. Rather
you must understand the strengths and weaknesses of each and make the
best decision based on your requirements.
--
Tom Porterfield
Nov 17 '05 #14
I'm beginning to feel a bit like Gulliver.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Ambiguity has a certain quality to it.

"Tom Porterfield" <tp******@mvps.org> wrote in message
news:Og**************@TK2MSFTNGP12.phx.gbl...
David Levine wrote:
The MSFT design guidelines (see Krzysztof Cwalina blog) suggest using
abstract base classes rather then interfaces. You get all the advantages
of an interface with fewer limitations. I tend to agree with these
guidelines. From an abstract :-) perspective, how does an interface
differ from an abtract base class with no implementation?


I think it comes down to your requirements and how much flexibility you
want to allow. With an abstract base class you certainly do *not* get all
the advantages of an interface. If you use an abstract base class you are
forcing everyone to use that as their base if they want to play in your
game. There are times when this would be desired. However that means
that a class with some other base class won't be able to participate. If
you were to instead use an interface then anyone could implement your
interface regardless of their inheritance chain. The advantage to that is
that two otherwise completely unrelated classes could plug into your
design as long as they implemented your interface.

I don't think anyone can make a blanket recommendation that either an
abstract base class or an interface is always the right answer. Rather
you must understand the strengths and weaknesses of each and make the best
decision based on your requirements.
--
Tom Porterfield

Nov 17 '05 #15

"Tom Porterfield" <tp******@mvps.org> wrote in message
news:Og**************@TK2MSFTNGP12.phx.gbl...
David Levine wrote:
The MSFT design guidelines (see Krzysztof Cwalina blog) suggest using
abstract base classes rather then interfaces. You get all the advantages
of an interface with fewer limitations. I tend to agree with these
guidelines. From an abstract :-) perspective, how does an interface
differ from an abtract base class with no implementation?
I think it comes down to your requirements and how much flexibility you
want to allow. With an abstract base class you certainly do *not* get all
the advantages of an interface. If you use an abstract base class you are
forcing everyone to use that as their base if they want to play in your
game.


Agreed, this is one drawback that interfaces don't have. If C# ever
supported multiple inheritance this would not be an issue.
There are times when this would be desired. However that means that a
class with some other base class won't be able to participate. If you
were to instead use an interface then anyone could implement your
interface regardless of their inheritance chain.
Yes, but you must write the entire implementation; there is no benefit from
using a base class that provides some or most of the functionality. I
consider this to be both a plus and a minus. Not being able to benefit from
default implementations in the base class is very limiting. It can also be a
benefit because now the derived class does not need to know anything at all
about the base class. This cuts both ways.
The advantage to that is that two otherwise completely unrelated classes
could plug into your design as long as they implemented your interface.

They could do that with an abstract base class. They suffer from the
limitation previously discussed, but no more then that I think.
I don't think anyone can make a blanket recommendation that either an
abstract base class or an interface is always the right answer. Rather
you must understand the strengths and weaknesses of each and make the best
decision based on your requirements.


I think we can agree on this.

Nov 17 '05 #16
David Levine <no******************@wi.rr.com> wrote:
On the other hand: use mock frameworks for unit testing is *much*
easier with interfaces.
How would it be easier? I don't see how it would be much different then
using an abstract base class?


Because mock frameworks such as EasyMockNET can only mock interfaces
and classes derived from MarshalByRefObject.

If you're building your own mock objects you can derive from an
abstract base class, but I prefer to get frameworks to do all that at
runtime :)

(Mocking is great, but seems to be less well known than it should be.
The current .NET implementations (EasyMockNET and NMock) are clunky in
a few ways - I intend to fix that when I get some time. Possibly in
December I may start the new project...)
I do take your point about breaking changes, but it's worth noting that
lots of people are in lots of different deployment situations. In many
cases, you know all the implementors of an interface, and can change
them all appropriately. In many other cases, you really can't do that -
so you have to end up creating another interface, etc. (Icky.)


The MSFT design guidelines (see Krzysztof Cwalina blog) suggest using
abstract base classes rather then interfaces. You get all the advantages of
an interface with fewer limitations.


Not sure I agree with that, given that you can implement multiple
interfaces but you can't derive from multiple base classes.
I tend to agree with these guidelines.
From an abstract :-) perspective, how does an interface differ from an
abtract base class with no implementation?


The above, for one thing.

Don't forget - if you use an interface as API (i.e. things require
parameters which are interfaces, and return interfaces) you can always
use abstract classes to implement those interfaces. The reverse is not
true.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #17
How would it be easier? I don't see how it would be much different then
using an abstract base class?
Because mock frameworks such as EasyMockNET can only mock interfaces
and classes derived from MarshalByRefObject.


This sounds like a practical constraint imposed by the current
implementation, not a theoretical one. Still,
it is a problem. Was this done because they needed to communicate with the
object across an appdomain boundary? If so, this probably wont be changed.
If you're building your own mock objects you can derive from an
abstract base class, but I prefer to get frameworks to do all that at
runtime :)
I agree about getting the framework to do the work. However, they could have
defined an abstract base class that itself derived from MBRO.

(Mocking is great, but seems to be less well known than it should be.
The current .NET implementations (EasyMockNET and NMock) are clunky in
a few ways - I intend to fix that when I get some time. Possibly in
December I may start the new project...)

I've used mocking (NMock) but I have used it less-and-less lately. A tool
that autogenerated the
mock object would make it much easier to use; handcoding the mock methods is
tedious. Like all tools/techniques, this one has its pros and cons. For me
the theory of it tended to be better then actually using it.

Another problem is that my understanding of the object that needs to be
mocked is limited, and testing production code against my own misconceptions
does little to validate the correctness of the system. I have started
writing tests against the actual running system using known data files - a
hybrid unit test and integration test. The downside is that the unit test
must account for a number of wildly different environments; e.g. debug,
release, running under the GUI versus running under the console, and also
account for delay signed builds on machines with skip verification turned on
versus resigned versions with skip verification on the build machine turned
off. The upside is that I learned an awful lot about what doesn't work :-)

Unit testing is worth the extra time it takes to write but I cannot say the
same about mock objects.

What improvements would you make to NMock?
> I do take your point about breaking changes, but it's worth noting that
> lots of people are in lots of different deployment situations. In many
> cases, you know all the implementors of an interface, and can change
> them all appropriately. In many other cases, you really can't do that -
> so you have to end up creating another interface, etc. (Icky.)


The MSFT design guidelines (see Krzysztof Cwalina blog) suggest using
abstract base classes rather then interfaces. You get all the advantages
of
an interface with fewer limitations.


Not sure I agree with that, given that you can implement multiple
interfaces but you can't derive from multiple base classes.


I agree - I had forgotten about that. It's one of the biggest drawbacks to
it. OTOH, there are many
designs where this does not impose a burden.

Don't forget - if you use an interface as API (i.e. things require
parameters which are interfaces, and return interfaces) you can always
use abstract classes to implement those interfaces. The reverse is not
true.

Not quite sure what you mean here.

I agree that an abstract base class can be derived from/implement
an interface and that an interface cannot be derived from an abstract base
class, but isn't that
more a limitation of an interface and not of an abstract base class?

I find that one large advantage of using base classes is the ability to
modify the base class (add methods, properties, etc.) without breaking
existing derived classes. I feel that as time passes and systems evolve the
issues of version resilience and version compatibility, both forward and
backward, become more important, and that interfaces become a burden.

Nov 17 '05 #18
David Levine <no******************@wi.rr.com> wrote:
How would it be easier? I don't see how it would be much different then
using an abstract base class?
Because mock frameworks such as EasyMockNET can only mock interfaces
and classes derived from MarshalByRefObject.


This sounds like a practical constraint imposed by the current
implementation, not a theoretical one. Still,
it is a problem. Was this done because they needed to communicate with the
object across an appdomain boundary? If so, this probably wont be changed.


No, it's because it uses RealProxy to do the work. That in itself is
just a practical reason, but think about abstract classes which have
some concrete non-virtual methods - how *could* those be mocked
effectively? Interfaces, being purely virtual, don't have that problem.
I tend to think they give a more flexible design too, but that's a
personal preference.
If you're building your own mock objects you can derive from an
abstract base class, but I prefer to get frameworks to do all that at
runtime :)


I agree about getting the framework to do the work. However, they could have
defined an abstract base class that itself derived from MBRO.


I don't see how that would have helped - I'm not sure I understand what
you're really getting at.
(Mocking is great, but seems to be less well known than it should be.
The current .NET implementations (EasyMockNET and NMock) are clunky in
a few ways - I intend to fix that when I get some time. Possibly in
December I may start the new project...)


I've used mocking (NMock) but I have used it less-and-less lately. A tool
that autogenerated the
mock object would make it much easier to use; handcoding the mock methods is
tedious. Like all tools/techniques, this one has its pros and cons. For me
the theory of it tended to be better then actually using it.


Whereas I've had exactly that behaviour for hand-coded mocks. It takes
a long time to hand-code a mock which is as flexible as a mock
framework in terms of reacting in all kinds of different ways to
different methods, and validating the call order.
Another problem is that my understanding of the object that needs to be
mocked is limited, and testing production code against my own misconceptions
does little to validate the correctness of the system.
That's always true of unit tests though, to a greater or lesser extent.
I have started
writing tests against the actual running system using known data files - a
hybrid unit test and integration test.
Yes, we do that too. Unit test frameworks don't only need to be used
for unit tests, fortunately :)
The downside is that the unit test
must account for a number of wildly different environments; e.g. debug,
release, running under the GUI versus running under the console, and also
account for delay signed builds on machines with skip verification turned on
versus resigned versions with skip verification on the build machine turned
off. The upside is that I learned an awful lot about what doesn't work :-)

Unit testing is worth the extra time it takes to write but I cannot say the
same about mock objects.

What improvements would you make to NMock?
I haven't used NMock, but I believe it doesn't use the "real" interface
for the "record" phase, which is a pain - it breaks refactoring. I find
it really easy to use EasyMock/EasyMock.NET most of the time. It
becomes a bit more of a pain when a single method needs to do an awful
lot, especially against database connections - but dbUnit (which I
don't know an equivalent of for .NET, unfortunately) works fine for
*most* of our tests.
Not sure I agree with that, given that you can implement multiple
interfaces but you can't derive from multiple base classes.


I agree - I had forgotten about that. It's one of the biggest drawbacks to
it. OTOH, there are many designs where this does not impose a burden.


Sure - but there are few designs (IME) where specification using an
interface imposes a burden.
Don't forget - if you use an interface as API (i.e. things require
parameters which are interfaces, and return interfaces) you can always
use abstract classes to implement those interfaces. The reverse is not
true.


Not quite sure what you mean here.


If I specify that a method must return an IList, I can use whatever
implementation I like, potentially using a *completely* different one
for another release. If I specify that it must return CollectionBase, I
can't then decide later to use ArrayList, for instance.
I agree that an abstract base class can be derived from/implement
an interface and that an interface cannot be derived from an abstract base
class, but isn't that more a limitation of an interface and not of an
abstract base class?
Absolutely not - if you specify that you'll use an abstract base class
for parameters or return values, you are "fixing" the implementation of
the API. Using interfaces leaves the implementation much freer.
I find that one large advantage of using base classes is the ability to
modify the base class (add methods, properties, etc.) without breaking
existing derived classes. I feel that as time passes and systems evolve the
issues of version resilience and version compatibility, both forward and
backward, become more important, and that interfaces become a burden.


You can still use abstract base classes when specifying API calls by
interfaces though. There's nothing limiting your implementation to only
use classes derived from System.Object.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #19

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

20 posts views Thread by Ole Hanson | last post: by
10 posts views Thread by Brett | last post: by
10 posts views Thread by Joe | last post: by
5 posts views Thread by Tony Johansson | last post: by
52 posts views Thread by Ben Voigt [C++ MVP] | last post: by
7 posts views Thread by tshad | last post: by
reply views Thread by kglaser89 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.