views:

8421

answers:

31

When should I use an interface and when should I use a base class?

Should it always be an interface if I don't want to actually define a base implementation of the methods?

If I have a Dog and Cat class. Why would I want to implement IPet instead of PetBase? I can understand having interfaces for ISheds or IBarks (IMakesNoise?), because those can be placed on a pet by pet basis, but I don't understand which to use for a generic Pet.

+64  A: 

Modern style is to define IPet and PetBase.

The advantage of the interface is that other code can use it without any ties whatsoever to other executable code. Completely "clean." Also interfaces can be mixed.

But base classes are useful for simple implementations and common utilities. So provide an abstract base class as well to save time and code.

Jason Cohen
have your cake and eat it too!
Darren Kopp
yup yup! And with modern IDE's it will even write the boiler-plate code for you (and some languages don't even need THAT)
Jason Cohen
An interface defines how other classes can use your code. A base class helps implementers to implement your interface. Two different things for two different purposes.
Bill Michell
I find this doubtful: is this .NET advice? Do you have a reference? In principle there are just a few reasons why you would create a "Base" class, typically delegation is preferable to inheritance.
andygavin
For example, to create a thread class in Java, you may either extend `java.lang.Thread` **or** implement `java.lang.Runnable`. To create an RMI server, you may either extend `java.rmi.server.UnicastRemoteObject` **or** implement `java.rmi.Remote`, and call `UnicastRemoteObject.exportObject()`.
Kevin Panko
+31  A: 

In general, you should favor interfaces over abstract classes. One reason to use an abstract class is if you have common implementation among concrete classes. Of course, you should still declare an interface (IPet) and have an abstract class (PetBase) implement that interface.Using small, distinct interfaces, you can use multiples to further improve flexibility. Interfaces allow the maximum amount of flexibility and portability of types across boundaries. When passing references across boundaries, always pass the interface and not the concrete type. This allows the receiving end to determine concrete implementation and provides maximum flexibility. This is absolutely true when programming in a TDD/BDD fashion.

The Gang of Four stated in their book "Because inheritance exposes a subclass to details of its parent's implementation, it's often said that 'inheritance breaks encapsulation". I believe this to be true.

Kilhoffer
Yeesh. Personally, I believe this is ass backwards. Interfaces should hold the bare minimum functionality for a type, and base classes should provide a rich framework upon which customization can be built. Put that in an interface and you just made it very hard to implement.
Will
Nobody said your interfaces need to be huge. Smaller, multiple interfaces and richer base classes make a great API.
Kilhoffer
A: 

I usually write both the Interface and the base Abstract Class. That leads to a much more robustly defined class hierarchy.

It also gives the code more flexibility.

jjnguy
+1  A: 

One important difference is that you can only inherit one base class, but you can implement many interfaces. So you only want to use a base class if you are absolutely certain that you won't need to also inherit a different base class. Additionally, if you find your interface is getting large then you should start looking to break it up into a few logical pieces that define independent functionality, since there's no rule that your class can't implement them all (or that you can define a different interface that just inherits them all to group them).

Joel Coehoorn
+1  A: 

It depends on your requirements. If IPet is simple enough, I would prefer to implement that. Otherwise, if PetBase implements a ton of functionality you don't want to duplicate, then have at it.

The downside to implementing a base class is the requirement to override (or new) existing methods. This makes them virtual methods which means you have to be careful about how you use the object instance.

Lastly, the single inheritance of .NET kills me. A naive example: Say you're making a user control, so you inherit UserControl. But, now you're locked out of also inheriting PetBase. This forces you to reorganize, such as to make a PetBase class member, instead.

spoulson
Composition is a good thing!
FlySwat
+2  A: 

@Joel: Some languages (e.g., C++) allow multiple-inheritance.

Einar
Good point. I missed the language-agnostic tag. However, C++ also has no concept of an interface.
Joel Coehoorn
Of course C++ has a concept of interfaces....without virtual functions, too.
Kilhoffer
+1  A: 

I usually don't implement either until I need one. I favor interfaces over abstract classes because that gives a little more flexibility. If there's common behavior in some of the inheriting classes I move that up and make an abstract base class. I don't see the need for both, since they essentially server the same purpose, and having both is a bad code smell (imho) that the solution has been over-engineered.

Bill the Lizard
+38  A: 

Well, Josh Bloch said himself in Effective Java 2d:

Prefer interfaces over abstract classes

Some main points:

  • Existing classes can be easily retrofitted to implement a new interface. All you have to do is add the required methods if they don’t yet exist and add an implements clause to the class declaration.

  • Interfaces are ideal for defining mixins. Loosely speaking, a mixin is a type that a class can implement in addition to its “primary type” to declare that it provides some optional behavior. For example, Comparable is a mixin interface that allows a class to declare that its instances are ordered with respect to other mutually comparable objects.

  • Interfaces allow the construction of nonhierarchical type frameworks. Type hierarchies are great for organizing some things, but other things don’t fall neatly into a rigid hierarchy.

  • Interfaces enable safe, powerful functionality enhancements via the wrap- per class idiom. If you use abstract classes to define types, you leave the programmer who wants to add functionality with no alternative but to use inheritance.

Moreover, you can combine the virtues of interfaces and abstract classes by providing an abstract skeletal implementation class to go with each nontrivial interface that you export.

On the other hand, interfaces are very hard to evolve. If you add a method to an interface it'll break all of it's implementations.

PS.: Buy the book. It's a lot more detailed.

Marcio Aguiar
Bloch, not Block.
vitule
Whenever a change needs to be made to an interface, the non-breaking way to do so is to create a new interface that inherits from the old one. This preserves existing implementations and lets you do whatever you wish in the new one.
Scott A. Lawrence
Thank @vitule! You got that right @Scott. Josh mentions this technique in the book too.
Marcio Aguiar
A: 

In addition to those comments that mention the IPet/PetBase implementation, there are also cases where providing an accessor helper class can be very valuable.

The IPet/PetBase style assumes that you have multiple implementations thus increasing the value of PetBase since it simplifies implementation. However, if you have the reverse or a blend of the two where you have multiple clients, providing a class help assist in the usage of the interface can reduce cost by making it easier to use an interface.

Torlack
+2  A: 

Interfaces should be small. Really small. If you're really breaking down your objects, then your interfaces will probably only contain a few very specific methods and properties.

Abstract classes are shortcuts. Are there things that all derivatives of PetBase share that you can code once and be done with? If yes, then it's time for an abstract class.

Abstract classes are also limiting. While they give you a great shortcut to producing child objects, any given object can only implement one abstract class. Many times, I find this a limitation of Abstract classes, and this is why I use lots of interfaces.

Abstract classes may contain several interfaces. Your PetBase abstract class may implement IPet (pets have owners) and IDigestion (pets eat, or at least they should). However, PetBase will probably not implement IMammal, since not all pets are mammals and not all mammals are pets. You may add a MammalPetBase that extends PetBase and add IMammal. FishBase could have PetBase and add IFish. IFish would have ISwim and IUnderwaterBreather as interfaces.

Yes, my example is extensively over-complicated for the simple example, but that's part of the great thing about how interfaces and abstract classes work together.

Jarrett Meyer
+109  A: 

Let's take your example of a Dog and a Cat class, and let's illustrate using C#:

Both a dog and a cat are animals, specifically, quadruped mammals (animals are waaay too general). Let us assume that you have an abstract class Mammal, for both of them:

public abstract class Mammal

This base class will probably have default methods such as:

  • Hunt
  • Feed
  • Mate

All of which are behavior that have more or less the same implementation between either species. To define this you will have:

public class Dog : Mammal
public class Cat : Mammal

Now let's suppose there are other mammals, which we will usually see in a zoo:

public class Giraffe : Mammal
public class Rhinoceros : Mammal
public class Hippopotamus : Mammal

This will still be valid because at the core of the functionality, Hunt(), Feed() and Mate() will still be the same.

However, giraffes, rhinoceros, and hippos are not exactly animals that you can make pets out of. That's where an interface will be useful:

public interface IPettable
{
    IList<Trick> Tricks{get; set;}
    void Bathe();
    void Train(Trick t);
}

The implementation for the above contract will not be the same between a cat and dog; putting their implementations in an abstract class to inherit will be a bad idea.

Your Dog and Cat definitions should now look like:

public class Dog : Mammal, IPettable
public class Cat : Mammal, IPettable

Theoretically you can override them from a higher base class, but essentially an interface allows you to add on only the things you need unto a class without the need for inheritance.

Consequently, because you can usually only inherit from one abstract class (in most statically typed OO languages that is... exceptions include C++) but be able to implement multiple interfaces, it allows you to construct objects in a strictly as required basis.

Jon Limjap
I don't think it is that simple. You have slightly changed the question (requirements) so that interface makes more sense. You should always ask yourself whether you are defining a contract (interface) or a shared implementation (base class).
David Pokluda
The interface is a contract. You're only exposing the part of the contract that a service requires. If you have a 'PettingZoo', you certainly don't want to expose 'Mate'-ing to the user!
Anthony Mastrean
@ajmastream you can always add a Castrate() method to some method so that Mate() will return no result! :P
Jon Limjap
@David Touche, although I did it to better illustrate what an interface is for and what an abstract class is for vis-a-vis his understanding. A dog and a cat does not appear to be a rigid requirement!
Jon Limjap
Really enjoyed the explanation. Thanks for taking the time!
Scott Saad
@Jon Wow, I love your solution to the petting zoo problem
smaclell
+8  A: 

Interfaces

  • Defines the contract between 2 modules. Cannot have any implementation.
  • Most languages allow you to implement multiple interfaces
  • Modifying an interface is a breaking change. All implementations need to be recompiled/modified.
  • All members are public. Implementations have to implement all members.
  • Interfaces help in Decoupling. You can use mock frameworks to mock out anything behind an interface
  • Interfaces normally indicate a kind of behavior
  • Interface implementations are decoupled / isolated from each other

    Base classes

  • Allows you to add some default implementation that you get for free by derivation

  • Except C++, you can only derive from one class. Even if could from multiple classes, it is usually a bad idea.
  • Changing the base class is relatively easy. Derivations do not need to do anything special
  • Base classes can declare protected and public functions that can be accessed by derivations
  • Abstract Base classes can't be mocked easily like interfaces
  • Base classes normally indicate type hierarchy (IS A)
  • Class derivations may come to depend on some base behavior (have intricate knowledge of parent implementation). Things can be messy if you make a change to the base implementation for one guy and break the others.
Gishu
+19  A: 

This is pretty .NET specific, but the Framework Design Guidelines book argues that in general classes give more flexibility in an evolving framework. Once an interface is shipped, you don't get the chance to change it without breaking code that used that interface. With a class however, you can modify it and not break code that links to it. As long you make the right modifications, which includes adding new functionality, you will be able to extend and evolve your code.

Krzysztof Cwalina says on page 81:

Over the course of the three versions of the .NET Framework, I have talked about this guideline with quite a few developers on our team. Many of them, including those who initially disagreed with the guidelines, have said that they regret having shipped some API as an interface. I have not heard of even one case in which somebody regretted that they shipped a class.

That being said there certainly is a place for interfaces. As a general guideline always provide an abstract base class implementation of an interface if for nothing else as an example of a way to implement the interface. In the best case that base class will save a lot of work.

fryguybob
Love that quote!
Benjol
A: 

An inheritor of a base class should have an "is a" relationship. Interface represents An "implements a" relationship. So only use a base class when your inheritors will maintain the is a relationship.

Aaron Fischer
A: 

Use your own judgement and be smart. Don't always do what others (like me) are saying. You will hear "prefer interfaces to abstract classes" but it really depends. It depends what the class is.

In the above mentioned case where we have a hierarchy of objects, interface is a good idea. Interface helps to work with collections of these objects and it also helps when implementing a service working with any object of the hierarchy. You just define a contract for working with objects from the hierarchy.

On the other hand when you implement a bunch of services that share a common functionality you can either separate the common functionality into a complete separate class or you can move it up into a common base class and make it abstract so that nobody can instantiate the base class.

Also consider this how to support your abstractions over time. Interfaces are fixed: You release an interface as a contract for a set of functionality that any type can implement. Base classes can be extended over time. Those extensions become part of every derived class.

David Pokluda
+4  A: 

I recommend using composition instead of inheritence whenever possible. Use interfaces but use member objects for base implementation. That way, you can define a factory that constructs your objects to behave in a certain way. If you want to change the behavior then you make a new factory method (or abstract factory) that creates different types of sub-objects.

In some cases, you may find that your primary objects don't need interfaces at all, if all of the mutable behavior is defined in helper objects.

So instead of IPet or PetBase, you might end up with a Pet which has an IFurBehavior parameter. The IFurBehavior parameter is set by the CreateDog() method of the PetFactory. It is this parameter which is called for the shed() method.

If you do this you'll find your code is much more flexible and most of your simple objects deal with very basic system-wide behaviors.

I recommend this pattern even in multiple-inheritence languages.

A: 

Interfaces have the distinct advantage of being somewhat "hot swappable" for classes. Changing a class from one parent to another will often result in a great deal of work, but Interfaces can often be removed and changed without a great deal of effect on the implementation class. This is especially useful in cases where you have several narrow sets of behaviour that you "may" want a class to implement.

This works especially well in my field: game programming. Base classes can get bloated with tons of behaviours that "may" be needed by inherited objects. With interfaces different behaviours can be added or removed to objects easily and readily. For example, if I create an interface for "IDamageEffects" for objects that I want to reflect damage, then I can easily apply that to various game objects, and easily change my mind later. Say I design an initial class that I want to use for "static" decorative objects and I initially decide they are non-destructible. Later on, I may decide it would be more fun if they could blow up so I alter the class to implement the "IDamageEffects" interface. This is much easier to do than switching base classes or creating a new object hierarchy.

Mark
A: 

There are other advantages to inheritance as well - such as the ability for a variable to be able to hold an object of either the parent class or the inherited class (without having to declare it as something generic, like "Object").

For example, in .NET WinForms, most UI components derive from System.Windows.Forms.Control, so a variable declared as that could "hold" just about any UI element - be it a button, a ListView, or what have you. Now, granted, you won't have access to all the properties or methods of the item, but you'll have all the basic stuff - and that can be useful.

Keithius
Your example doesnt support the concept. You can do the same thing with an interface. You don't just have to have a base class for that.
Kilhoffer
+2  A: 

Juan,

I like to think of interfaces as a way to characterize a class. A particular dog breed class, say a YorkshireTerrier, may be a descended of the parent dog class, but it is also implements IFurry, IStubby, and IYippieDog. So the class defines what the class is but the interface tells us things about it.

The advantage of this is it allows me to, for example, gather all the IYippieDog's and throw them into my Ocean collection. So now I can reach across a particular set of objects and find ones that meet the criteria I am looking at without inspecting the class too closely.

I find that interfaces really should define a sub-set of the public behavior of a class. If it defines all the public behavior for all the classes that implement then it usually does not need to exist. They do not tell me anything useful.

This thought though goes counter to the idea that every class should have an interface and you should code to the interface. That's fine, but you end up with a lot of one to one interfaces to classes and it makes things confusing. I understand that the idea is it does not really cost anything to do and now you can swap things in and out with ease. However, I find that I rarely do that. Most of the time I am just modifying the existing class in place and have the exact same issues I always did if the public interface of that class needs changing, except I now have to change it in two places.

So if you think like me you would definitely say that Cat and Dog are IPettable. It is a characterization that matches them both.

The other piece of this though is should they have the same base class? The question is do they need to be broadly treated as the same thing. Certainly they are both Animals, but does that fit how we are going to use them together.

Say I want to gather all Animal classes and put them in my Ark container.

Or do they need to be Mammals? Perhaps we need some kind of cross animal milking factory?

Do they even need to be linked together at all? Is it enough to just know they are both IPettable?

I often feel the desire to derive a whole class hierarchy when I really just need one class. I do it in anticipation someday I might need it and usually I never do. Even when I do, I usually find I have to do a lot to fix it. That’s because the first class I am creating is not the Dog, I am not that lucky, it is instead the Platypus. Now my entire class hierarchy is based on the bizarre case and I have a lot of wasted code.

You might also find at some point that not all Cats are IPettable (like that hairless one). Now you can move that Interface to all the derivative classes that fit. You will find that a much less breaking change that all of a sudden Cats are no longer derived from PettableBase.

Flory
+1  A: 

Previous comments about using abstract classes for common implementation is definitely on the mark. One benefit I haven't seen mentioned yet is that the use of interfaces makes it much easier to implement mock objects for the purpose of unit testing. Defining IPet and PetBase as Jason Cohen described enables you to mock different data conditions easily, without the overhead of a physical database (until you decide it's time to test the real thing).

Scott A. Lawrence
+2  A: 

Don't use a base class unless you know what it means, and that it applies in this case. If it applies, use it, otherwise, use interfaces. But note the answer about small interfaces.

Public Inheritance is overused in OOD and expresses a lot more than most developers realize or are willing to live up to. See the Liskov Substitutablity Principle

In short, if A "is a" B then A requires no more than B and delivers no less than B, for every method it exposes.

theschmitzer
A: 

You should use a base class if there really isn't any reason for other developers to desire using their own base class in addition to your type's members and you foresee versioning issues (see http://haacked.com/archive/2008/02/21/versioning-issues-with-abstract-base-classes-and-interfaces.aspx).

If inheriting developers have any reason to use their own base class to implement your type's interface and you don't see the interface changing, then go with an interface. In this case, you can still throw in a default base class that implements the interface for sake of convenience.

Mark Cidade
A: 

That's an easy one. If you're programming in C++ always use base classes ;)

Dmitry Shechtman
I like it. You brought up a simplifying point of view, that interfaces are just abstract classes with multiple inheritance. Multiple inheritance gets a bad rap in blogs for introducing complexity but it's actually the opposite. Not having interfaces is a very scheme-like simplification in C++. Instead of two concept you have a general one that unifies them. The complexity comes from the user.
Samuel Danielson
+3  A: 

Also keep in mind not to get swept away in OO (see blog) and always model objects based on behavior required, if you were designing an app where the only behavior you required was a generic name and species for an animal then you would only need one class Animal with a property for the name, instead of millions of classes for every possible animal in the world.

Sijin
+6  A: 

Interfaces and base classes represent two different forms of relationships.

Inheritance (base classes) represent an "is-a" relationship. E.g. a dog or a cat "is-a" pet. This relationship always represents the (single) purpose of the class (in conjunction with the "single responsibility principle"[1]).

Interfaces, on the other hand, represent additional features of a class. I'd call it an "is" relationship, like in "Foo is disposable", hence the IDisposable interface in C#.

[1]: References of the most important principles of software engineering

Thomas Danecker
+1, this makes sense to me
Jason
+1, right to the point
Juan Calero
excellent way of thinking about it.
dviljoen
+2  A: 

Conceptually, an Interface is used to formally and semi-formally define a set of methods that an object will provide. Formally means a set of method names and signatures, semi-formally means human readable documentation associated with those methods. Interfaces are only descriptions of an API (after all, API stands for Application Programmer Interface), they can't contain any implementation, and it's not possible to use or run an Interface. They only make explicit the contract of how you should interact with an object.

Classes provide an implementation, they can declare that they implement zero, one or more Interfaces. If a Class is intended to be inherited, the convention is to prefix the Class name with "Base".

There is a distinction between a Base Class and an Abstract Base Classes (ABC). ABCs mix interface and implementation together. Abstract outside of computer programming means "summary", that is "Abstract == Interface". An Abstract Base Class can then describe both an interface, as well as an empty, partial or complete implementation that is intended to be inherited.

Opinions on when to use Interfaces versus Abstract Base Classes versus just Classes is going to vary wildly based on both what you are developing, and which language you are developing in. Interfaces are often associated only with statically typed languages such as Java or C#, but dynamically typed languages can also have Interfaces and Abstract Base Classes. In Python for example, the distinction is made clear between a Class, which declares that it implements an Interface, and an object, which is an instance of a Class, and is said to provide that Interface. It's possible in a dynamic language that two objects that are both instances of the same Class, can declare that they provide completely different interfaces. In Python this is only possible for object attributes, while methods are shared state between all objects of a Class. However in Ruby, objects can have per-instance methods, so it's possible that the Interface between two objects of the same Class can vary as much as the programmer desires (however, Ruby doesn't have any explicit way of declaring Interfaces).

In dynamic languages the Interface to an object is often implicitly assumed, either by introspecting an object and asking it what methods it provides (Look Before You Leap) or preferably by simply attempting to use the desired Interface on an object and catching exceptions if the object doesn't provide that Interface (Easier to Ask Forgiveness than Permission). This can lead to "false positives" where two Interfaces have the same method name but are semantically different, however the trade-off is that your code is more flexible since you don't need to over specify up-front to anticipate all possible uses of your code.

Wheat
+1  A: 

Here is the basic and simple definiton of interface and base class:

  • Base class = object inheritance.
  • Interface = functional inheritance.

cheers,

RWendi

RWendi
+4  A: 

Explained well in this Java World article

Personally I tend to use interfaces to define interfaces - i.e. parts of the system design that specify how something should be accessed.

It's not uncommon that I will have a class implementing 1 or more interfaces.

Abstract classes I use as a basis for something else.

The following is an extract from the above mentioned article JavaWorld.com article, author Tony Sintes, 04/20/01


Interface vs. abstract class

Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.

Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.

Many developers forget that a class that defines an abstract method can call that method as well. Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.

Class vs. interface

Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme. I use interfaces when I see that something in my design will change frequently.

For example, the Strategy pattern lets you swap new algorithms and processes into your program without altering the objects that use them. A media player might know how to play CDs, MP3s, and wav files. Of course, you don't want to hardcode those playback algorithms into the player; that will make it difficult to add a new format like AVI. Furthermore, your code will be littered with useless case statements. And to add insult to injury, you will need to update those case statements each time you add a new algorithm. All in all, this is not a very object-oriented way to program.

With the Strategy pattern, you can simply encapsulate the algorithm behind an object. If you do that, you can provide new media plug-ins at any time. Let's call the plug-in class MediaStrategy. That object would have one method: playStream(Stream s). So to add a new algorithm, we simply extend our algorithm class. Now, when the program encounters the new media type, it simply delegates the playing of the stream to our media strategy. Of course, you'll need some plumbing to properly instantiate the algorithm strategies you will need.

This is an excellent place to use an interface. We've used the Strategy pattern, which clearly indicates a place in the design that will change. Thus, you should define the strategy as an interface. You should generally favor interfaces over inheritance when you want an object to have a certain type; in this case, MediaStrategy. Relying on inheritance for type identity is dangerous; it locks you into a particular inheritance hierarchy. Java doesn't allow multiple inheritance, so you can't extend something that gives you a useful implementation or more type identity.

Richard Harrison
Thanks for moving it, I've voted your answer up.
Ash
+1  A: 

Another option to keep in mind is using the "has-a" relationship, aka "is implemented in terms of" or "composition." Sometimes this is a cleaner, more flexible way to structure things than using "is-a" inheritance.

It may not make as much sense logically to say that Dog and Cat both "have" a Pet, but it avoids common multiple inheritance pitfalls:

public class Pet
{
    void Bathe();
    void Train(Trick t);
}

public class Dog
{
    private Pet pet;

    public void Bathe() { pet.Bathe(); }
    public void Train(Trick t) { pet.Train(t); }
}

public class Cat
{
    private Pet pet;

    public void Bathe() { pet.Bathe(); }
    public void Train(Trick t) { pet.Train(t); }
}

Yes, this example shows that there is a lot of code duplication and lack of elegance involved in doing things this way. But one should also appreciate that this helps to keep Dog and Cat decoupled from the Pet class (in that Dog and Cat do not have access to the private members of Pet), and it leaves room for Dog and Cat to inherit from something else--possibly the Mammal class.

Composition is preferable when no private access is required and you don't need to refer to Dog and Cat using generic Pet references/pointers. Interfaces give you that generic reference capability and can help cut down on the verbosity of your code, but they can also obfuscate things when they are poorly organized. Inheritance is useful when you need private member access, and in using it you are committing yourself to highly coupling your Dog and Cat classes to your Pet class, which is a steep cost to pay.

Between inheritance, composition, and interfaces there is no one way that is always right, and it helps to consider how all three options can be used in harmony. Of the three, inheritance is typically the option that should be used the least often.

Parappa
+1  A: 

The case for Base Classes over Interfaces was explained well in the Submain .NET Coding Guidelines:

Base Classes vs. Interfaces An interface type is a partial description of a value, potentially supported by many object types. Use base classes instead of interfaces whenever possible. From a versioning perspective, classes are more flexible than interfaces. With a class, you can ship Version 1.0 and then in Version 2.0 add a new method to the class. As long as the method is not abstract, any existing derived classes continue to function unchanged.

Because interfaces do not support implementation inheritance, the pattern that applies to classes does not apply to interfaces. Adding a method to an interface is equivalent to adding an abstract method to a base class; any class that implements the interface will break because the class does not implement the new method. Interfaces are appropriate in the following situations:

  1. Several unrelated classes want to support the protocol.
  2. These classes already have established base classes (for example, some are user interface (UI) controls, and some are XML Web services).
  3. Aggregation is not appropriate or practicable. In all other situations, class inheritance is a better model.
YeahStu
+1  A: 

When I first started learning about object-oriented programming, I made the easy and probably common mistake of using inheritance to share common behavior - even where that behavior was not essential to the nature of the object.

To further build on an example much used in this particular question, there are lots of things that are petable - girlfriends, cars, fuzzy blankets... - so I might have had a Petable class that provided this common behavior, and various classes inheriting from it.

However, being petable is not part of the nature of any of these objects. There are vastly more important concepts that are essential to their nature - the girlfriend is a person, the car is a land vehicle, the cat is a mammal...

Behaviors should be assigned first to interfaces (including the default interface of the class), and promoted to a base class only if they are (a) common to a large group of classes that are subsets of a larger class - in the same sense that "cat" and "person" are subsets of "mammal".

The catch is, after you understand object-oriented design sufficiently better than I did at first, you'll normally do this automatically without even thinking about it. So the bare truth of the statement "code to an interface, not an abstract class" becomes so obvious you have a hard time believing anyone would bother to say it - and start trying to read other meanings into it.

Another thing I'd add is that if a class is purely abstract - with no non-abstract, non-inherited members or methods exposed to child, parent, or client - then why is it a class? It could be replaced, in some cases by an interface and in other cases by Null.