41

I use interfaces rarely and find them common in others code.

Also I create sub and super classes (while creating my own classes) rarely in my code.

  • Is it a bad thing?
  • Would you suggest changing this style?
  • Does this style have any side-effects?
  • Is this because I have not worked on any large projects?
6
  • 10
    Which language is this?
    – user1249
    Jun 19, 2011 at 17:01
  • 2
    Besides what language, what paradigm is this?
    – Armando
    Jun 19, 2011 at 17:26
  • 1
    Doesn't the concept of an "interface" transcend language? Java has the built-in Interface type, but C++ developers often create interfaces too (prefixing them with I) and they all serve the same purpose.
    – Ricket
    Jun 20, 2011 at 1:37
  • 4
    @Ricket: No, not really. The trouble is that C++ offers multiple class inheritance. In C++ an "interface" is much more conceptual and in reality we mostly use what they would define as an abstract base class.#
    – DeadMG
    Jun 20, 2011 at 8:39
  • 2
    @Ricket no, especially if you are working in a functional language rather than a procedural or OOP one. Jun 20, 2011 at 12:03

11 Answers 11

36

There are several reasons why you might want to use interfaces:

  1. Interfaces are suited to situations in which your applications require many possibly unrelated object types to provide certain functionality.
  2. Interfaces are more flexible than base classes because you can define a single implementation that can implement multiple interfaces.
  3. Interfaces are better in situations in which you do not need to inherit implementation from a base class.
  4. Interfaces are useful in cases where you cannot use class inheritance. For example, structures cannot inherit from classes, but they can implement interfaces.

http://msdn.microsoft.com/en-us/library/3b5b8ezk(v=vs.80).aspx

Interfaces are like anything else in programming. If you don't need them, don't use them. I've seen them used extensively as a matter of style, but if you don't need the special properties and capabilities that an interface provides, I don't see the benefit of using them "just because."

4
  • 13
    His language isn't specified, and yours is too specific- for example, in C++, a structure can indeed inherit from a class, and you can multiply inherit non-abstract bases.
    – DeadMG
    Jun 19, 2011 at 18:33
  • 2
    This answer seems to be C# but also pertains to Java if you take out #4, and only sort of applies to C++ because of course multiple inheritance is allowed in C++.
    – Ricket
    Jun 20, 2011 at 1:38
  • 2
    Also, I disagree with the last statement. I think there are a lot of good practices that programmers should do but don't because they feel they don't need them. I think the asker is very wise in looking around, seeing everyone else doing this thing, and thinking maybe he should be doing it too but asking "why" first.
    – Ricket
    Jun 20, 2011 at 1:39
  • 3
    @Ricket: The why is in the four bullet points of my answer. If none of those reasons apply, then you don't need an interface. Jun 20, 2011 at 1:50
17

Both class inheritance and interfaces both have their place. Inheritance means "is a" while an interface provides a contract that defines what something "behaves like".

I would say that using interfaces more often is not a bad practice at all. I am currently reading "Effective C# - 50 Specific Ways to Improve Your C#" by Bill Wagner. Item number 22 states, and a I quote, "Prefer Defining and Implementing Interfaces to Inheritance".

Generally I use base classes when I need to define a specific implementation of common behavior between conceptually related types. More often I use interfaces. In fact, I normally start by defining an interface for a class when I start to create one...even if in the end I don't compile the interface, I find that it helps to start off by defining the public API of the class from the get go. If I find that I have multiple classes both implementing the interface, and the implementation logic is identical, only then will I ask myself whether or not it would make sense to implement a common base class between the types.

A couple of quotes from Bill Wagners book...

"Abstract base classes can supply some implementation for derived types, in addition to describing the common behavior. You can specify data members, concrete methods, implementation for virtual methods, properties, events, and indexers. A base class can provide implementation for some of the methods, thereby providing common implementation reuse. Any of the elements can be virtual, abstract, or nonvirtual. An abstract base class can provide an implementation for any concrete behavior; interfaces cannot. This implementation reuse provides another benefit: If you add a method to the base class, all derived classes are automatically and implicitly enhanced. In that sense, base classes provide a way to extend the behavior of several types efficiently over time: By adding and implementing functionality in the base class, all derived classes immediately incorporate that behavior. Adding a member to an interface breaks all the classes that implement that interface. They will not contain the new method and will no longer compile. Each implementer must update that type to include the new member. Choosing between an abstract base class and an interface is a question of how best 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. The two models can be mixed to reuse implementation code while supporting multiple interfaces."

"Coding interfaces provides greater flexibility to other developers than coding to base class types."

"Using interfaces to define APIs for a class provides greater flexibility."

"When your type exposes properties as class types, it exposes the entire interface to that class. Using interfaces, you can choose to expose only the methods and properties you want clients to use."

"Base classes describe and implement common behaviors across related concrete types. Interfaces describe atomic pieces of functionality that unrelated concrete types can implement. Both have their place. Classes define the types you create. Interfaces describe the behavior of those types as pieces of functionality. If you understand the differences, you will create more expressive designs that are more resilient in the face of change. Use class hierarchies to define related types. Expose functionality using interfaces implemented across those types."

7
  • 2
    Well, I read it and thought it was a good answer.
    – Eric King
    Jun 19, 2011 at 17:55
  • 1
    @mc10 Not sure what the problem is. He referenced a book and the bottom half of his answer is just quotes from that book which he clearly lets you know in case you don't want to waste your time.
    – Pete
    Jun 19, 2011 at 18:18
  • @Pete I didn't say that the answer is bad, but only that it was a bit too long. I doubt that you needed the entire quote sometimes.
    – Kevin Ji
    Jun 19, 2011 at 20:04
  • 3
    haha, if this is tl;dr, I'm not sure you're going to like this whole StackExchange-high-quality-answers thing.
    – Nic
    Jun 20, 2011 at 1:25
  • haha, thanks guys. Yes it did occur to me that the answer was a bit long winded, but I thought I would qualify my answer by including relevant quotes from Mr. Wagner that expound upon the advantages and disadvantages of interfaces vs. inheritance, as well as the scenarios where each is more appropriate. Perhaps quoting the book directly did not add a lot of value to my answer. Jun 20, 2011 at 3:47
9

One thing that hasn't been mentioned is testing: in all C# mocking-libraries, as well as some for Java, classes can't be mocked unless they implement an interface. This leads many projects following Agile/TDD practices to give every class its own interface.

Some people consider this best practice, because it "reduces coupling," but I disagree - I think it's just a workaround to a deficiency in the language.


I think interfaces are best used when you have two or more classes which, abstractly, do the "same thing," but in different ways.

For instance, the .Net framework has multiple classes that store lists of stuff, but they all store that stuff in different ways. Thus, it makes sense to have an abstract IList<T> interface, which can be implemented using different methods.

You should also use it when you want 2+ classes to be interchangeable, or replaceable in the future. If a new way of storing lists comes out in the future, AwesomeList<T>, then assuming you used IList<T> throughout your code, changing it to use AwesomeList<T> would mean only changing a few dozen lines, rather than a few hundred/thousand.

5

The main result of not using inheritance and interfaces when they are appropriate is tight coupling. This can be a little difficult to learn to recognize, but usually the most obvious symptom is when you make a change, you find you frequently have to go through a whole bunch of other files to make changes in a ripple effect.

4

No, this isn't bad at all. Explicit interfaces should be used, if and only if, two classes with a common interface need to be interchangeable at run-time. If they don't need to be interchangeable, then don't have them inherit. It's as simple as that. Inheritance is fragile and should be avoided wherever possible. If you can avoid it or use generics instead, then do.

The trouble is, in languages like C# and Java with weak compile-time generics, you can end up violating DRY because there's no way to write one method that can deal with more than one class unless all classes inherit from the same base. C# 4's dynamic can deal with this, though.

The thing is, inheritance is like global variables- once you add it and your code depends on it, God help you taking it away. However, you can add it at any time, and you can even add it without altering the base class by using a wrapper of sorts.

2
  • 1
    Reason for downvote?
    – DeadMG
    Jun 20, 2011 at 8:39
  • Not sure, have an upvote. It was a good answer. Jul 8, 2011 at 13:37
3

Yes, not (or too rarely) using interfaces is probably a bad thing. Interfaces (in the abstract sense, and the C#/Java language construct is a pretty good approximation of that abstract sense) define explicit interaction points between systems and subsystems. This helps reduce coupling and makes the system more maintainable. As with anything that improves maintainability, it becomes the more important the bigger a system is.

3

I haven't used an interface in years. Of course this is because I've been programming almost exclusively in Erlang now for years and the whole concept of an interface simply doesn't exist. (The closest you get is a "behaviour" and that's not really the same thing unless you squint really hard and look at them out of the corner of your eye.)

So, really, your question is paradigm-dependent (OOP in this case) and, further, is really quite language-dependent (there are OOP languages without interfaces).

2

If you're talking about using Java, one reason for using interfaces is that they enable the use of proxy objects without code generation libraries. This can be a substantial advantage when you are working with a complex framework like Spring. Moreover, some functionality requires interfaces: RMI is the classic example of this, as you have to describe the functionality you're providing in terms of interfaces (that inherit from java.rmi.Remote) however you go about implementing them.

1

Things are changing (MS Moles), but the main reason that I think it is good to code almost exclusively to interfaces is that they are easy to mock and fit naturally into an IoC architecture.

IMO you should only ever work with interfaces, or completely dumb DAOs wherever possible. Once you get into this mindset, and you start using a library that does not expose itself through interfaces and does everything via concrete objects I've got to be honest, it does all feel a bit clunky.

0

For old fashion projects, one uses interfaces to avoid circular references, because circular references could become huge maintenance problem in the long run.

Bad:

class B; // forward declaration
class A
{
  B* b;
};

class B
{
  A* a;
}

Not Bad:

class PartOfClassB_AccessedByA
{
};

class A
{
  PartOfClassB_AccessedByA* b;
};

class B : public PartOfClassB_AccessedByA
{
  A* a;
}

Usually A, B, PartOfClassB_AccessedByA implemented with separate files.

0

Interface based programming helps to make code more flexible and easier to test. The implementation classes can be changed without touching client code[Flexibility]. While testing code one can replace actual oInterface based programming helps to make code more flexible and easier to test. The implementation classes can be changed without touching client code[Flexibility]. While testing code one can replace actual object with mock objects[Testability].bject with mock objects[Testability].

Not the answer you're looking for? Browse other questions tagged or ask your own question.