views:

561

answers:

18

I work at a company where some require justification for the use of an Interface in our code (Visual Studio C# 3.5).

I would like to ask for an Iron Clad reasoning that interfaces are required for. (My goal is to PROVE that interfaces are a normal part of programming.)

I don't need convincing, I just need a good argument to use in the convincing of others.

The kind of argument I am looking for is fact based, not comparison based (ie "because the .NET library uses them" is comparison based.)

The argument against them is thus: If a class is properly setup (with its public and private members) then an interface is just extra overhead because those that use the class are restricted to public members. If you need to have an interface that is implemented by more than 1 class then just setup inheritance/polymorphism.

+21  A: 

Code decoupling. By programming to interfaces you decouple the code using the interface from the code implementing the interface. This allows you to change the implementation without having to refactor all of the code using it. This works in conjunction with inheritance/polymorphism, allowing you to use any of a number of possible implementations interchangeably.

Mocking and unit testing. Mocking frameworks are most easily used when the methods are virtual, which you get by default with interfaces. This is actually the biggest reason why I create interfaces.

Defining behavior that may apply to many different classes that allows them to be used interchangeably, even when there isn't a relationship (other than the defined behavior) between the classes. For example, a Horse and a Bicycle class may both have a Ride method. You can define an interface IRideable that defines the Ride behavior and any class that uses this behavior can use either a Horse or Bicycle object without forcing an unnatural inheritance between them.

tvanfosson
i was going to write something like that, but im not eloquent enough. so i let someone better do it. Decoupling is the most important part programming it provides for flexibility, manageability and re-usability.
Stan R.
As an addendum to the Horse/Bicycle comment, the nice thing about interfaces is being able to generalize operations on your class without limiting your inheritance: http://stackoverflow.com/questions/558152/asp-net-unfamiliar-with-interfaces/558342#558342
Juliet
If an implementation change involved a new method signature, then the addition of such a method breaks all clients using the Interface. What kind of decoupling is that? Should we aim for a combination of interface and abstract class?
IrishChieftain
Well in that case you're not changing the implementation, but the contract. You shouldn't expect to be decoupled from the contract, just the concrete implementation of the contract.
tvanfosson
+1  A: 

If your shop is performing automated testing, interfaces are a great boon to dependency injection and being able to test a unit of software in isolation.

Alex B
+2  A: 
  • Test Driven Development
  • Unit Testing

Without interfaces producing decoupled code would be a pain. Best practice is to code against an interface rather than a concrete implementation. Interfaces seem rubbish at first but once you discover the benefits you'll always use them.

Finglas
+5  A: 

To enable unit testing of the class.

To track dependencies efficiently (if the interface isn't checked out and touched, only the semantics of the class can possibly have changed).

Because there is no runtime overhead.

To enable dependency injection.

...and perhaps because it's friggin' 2009, not the 70's, and modern language designers actually have a clue about what they are doing?

Not that interfaces should be thrown at every class interface: just those which are central to the system, and which are likely to experience significant change and/or extension.

Pontus Gagge
+2  A: 
  • You can implement multiple interfaces. You cannot inherit from multiple classes.
  • ..that's it. The points others are making about code decoupling and test-driven development don't get to the crux of the matter because you can do those things with abstract classes too.
Matt Howells
not necessarily, abstract classes are to be used when there is common logic to share. I may have 2 classes that implement the same interface but have completely different structure all together.
Stan R.
Why bother with an abstract class if you are only going to override the base implementation? Thus interfaces are better for unit testing. Abstract classes do have their place though.
Finglas
I agree that abstract classes obviously _should_ provide some implementation, otherwise they should be interfaces. But I am directly answering the question.
Matt Howells
+9  A: 

In addition to things explained in other answers, interfaces allow you simulate multiple inheritance in .NET which otherwise is not allowed.

Alas as someone said

Technology is dominated by two types of people: those who understand what they do not manage, and those who manage what they do not understand.

TheVillageIdiot
This is a very good point. Because .NET doesn't support multiple inheritance, the use of interfaces is pretty much mandatory.
Meta-Knight
Meta-Knight: That's the party line, but I'm not sure I believe it. Can't you just structure things differently to not require multiple superclasses in one subclass? Would you also say that "Because .NET doesn't support multiple dispatch, writing your own dispatcher is pretty much mandatory"? There are always more powerful object systems, but you don't always have to emulate all their features just to get something done.
Ken
+2  A: 

Interfaces allow you to declare a concept that can be shared amongst many types (IEnumerable) while allowing each of those types to have its own inheritance hierarchy.

In this case, what we're saying is "this thing can be enumerated, but that is not its single defining characteristic".

Interfaces allow you to make the minimum amount of decisions necessary when defining the capabilities of the implementer. When you create a class instead of an interface, you have already declared that your concept is class-only and not usable for structs. You also make other decisions when declaring members in a class, such as visibility and virtuality.

For example, you can make an abstract class with all public abstract members, and that is pretty close to an interface, but you have declared that concept as overridable in all child classes, whereas you wouldn't have to have made that decision if you used an interface.

They also make unit testing easier, but I don't believe that is a strong argument, since you can build a system without unit tests (not recommended).

Bryan Watts
+4  A: 

Interfaces and abstract classes model different things. You derive from a class when you have an isA relationship so the base class models something concrete. You implement an interface when your class can perform a specific set of tasks.

Think of something that's Serializable, it doesn't really make sense (from a design/modelling point of view) to have a base class called Serializable as it doesn't make sense to say something isA Serializable. Having something implement a Serializable interface makes more sense as saying 'this is something the class can do, not what the class is'

Kevin Jones
+1 for the last sentence alone!
Richard Ev
A: 

I don't understand how its extra overhead.

Interfaces provide flexibility, manageable code, and reusability. Coding to an interface you don't need to worry about the concreted implementation code or logic of the certain class you are using. You just expect a result. Many class have different implementation for the same feature thing (StreamWriter,StringWriter,XmlWriter)..you do not need to worry about how they implement the writing, you just need to call it.

Stan R.
It is extra overhead if you create your own interfaces, because you have to create and maintain more code. For each method you want to pull into the interface, you must duplicate the method signature. Then, every time you need to change the method signature, you will need to change it in at least two places.
toby
You're supporting both arguments here. StreamWriter and StringWriter are implementations of an abstract class (TextWriter); XmlWriter is unrelated except for Object and IDisposable.
Austin Salonen
Yes good point, I wasn't thinking of how .NET actually implements it. I was trying to think of a quick example of classes that share a functionality(Write) but implement them differently..
Stan R.
+1  A: 

The problem with the inheritance argument is that you'll either have a gigantic god class or a hierarchy so deep, it'll make your head spin. On top of that, you'll end up with methods on a class you don't need or don't make any sense.

I see a lot of "no multiple inheritance" and while that's true, it probably won't phase your team because you can have multiple levels of inheritance to get what they'd want.

An IDisposable implementation comes to mind. Your team would put a Dispose method on the Object class and let it propagate through the system whether or not it made sense for an object or not.

Austin Salonen
+13  A: 

The argument against them is thus: If a class is properly setup (with its public and private members) then an interface is just extra overhead because those that use the class are restricted to public members. If you need to have an interface that is implemented by more than 1 class then just setup inheritance/polymorphism.

Consider the following code:

interface ICrushable
{
  void Crush();
}

public class Vehicle
{
}

public class Animal
{
}

public class Car : Vehicle, ICrushable
{
  public void Crush()
  {
     Console.WriteLine( "Crrrrrassssh" );
  }
}

public class Gorilla : Animal, ICrushable
{
  public void Crush()
  {
     Console.WriteLine( "Sqqqquuuuish" );
  }
}

Does it make any sense at all to establish a class hierarchy that relates Animals to Vehicles even though both can be crushed by my giant crushing machine? No.

JP Alioto
+1 for the nice example of sqishing gorillas
usr
A: 

and the clock is ticking... how long before this question is closed?

Badfish
Why would it be closed?
Lazarus
Why Close it? It is a clear question that can have an exact answer.
Vaccano
the same reason many other non-code related questions are closed... in case you didn't know, the answer is arbitrary... thanks for the down votes!
Badfish
how exactly is this question non-code related?? this is definitely code-related and if you haven't noticed its not very subjective, we pretty much all agree on the same thing..
Stan R.
lol, oh ok, in other words the sliding scale of what is and is not 'code related' is subjective...
Badfish
Regardless of the question..your answer is not actually an answer to the question at hand.
Stan R.
and your answer was?
Badfish
+1  A: 

An interface declares a contract that any object implementing it will adhere to. This makes ensuring quality in code so much easier than trying to enforce written (not code) or verbal structure, the moment a class is decorated with the interface reference the requirements/contract is clear and the code won't compile till you've implemented that interface completely and type-safe.

There are many other great reasons for using Interfaces (listed here) but probably don't resonate with management quite as well as a good, old-fashioned 'quality' statement ;)

Lazarus
+1  A: 

Well, my 1st reaction is that if you've to explain why you need interfaces, it's a uphill battle anyways :)

that being said, other than all the reasons mentioned above, interfaces are the only way for loosely coupled programming, n-tier architectures where you need to update/replace components on the fly etc. - in personal experience however that was too esoteric a concept for the head of architecture team with the result that we lived in dll hell - in the .net world no-less !

Kumar
+1  A: 

Please forgive me for the pseudo code in advance!

Read up on SOLID principles. There are a few reasons in the SOLID principles for using Interfaces. Interfaces allow you to decouple your dependancies on implementation. You can take this a step further by using a tool like StructureMap to really make the coupling melt away.

Where you might be used to

Widget widget1 = new Widget;

This specifically says that you want to create a new instance of Widget. However if you do this inside of a method of another object you are now saying that the other object is directly dependent on the use of Widget. So we could then say something like

public class AnotherObject
{
    public void SomeMethod(Widget widget1)
    {
        //..do something with widget1
    }
}

We are still tied to the use of Widget here. But at least this is more testable in that we can inject the implementation of Widget into SomeMethod. Now if we were to use an Interface instead we could further decouple things.

public class AnotherObject
{
    public void SomeMethod(IWidget widget1)
    {
        //..do something with widget1
    }
}

Notice that we are now not requiring a specific implementation of Widget but instead we are asking for anything that conforms to IWidget interface. This means that anything could be injected which means that in the day to day use of the code we could inject an actual implementation of Widget. But this also means that when we want to test this code we could inject a fake/mock/stub (depending on your understanding of these terms) and test our code.

But how can we take this further. With the use of StructureMap we can decouple this code even more. With the last code example our calling code my look something like this

public class AnotherObject
{
    public void SomeMethod(IWidget widget1)
    {
        //..do something with widget1
    }
}

public class CallingObject
{
    public void AnotherMethod()
    {
        IWidget widget1 = new Widget();
        new AnotherObject().SomeMethod(widget1);
    }
}

As you can see in the above code we removed the dependency in the SomeMethod by passing in an object that conforms to IWidget. But in the CallingObject().AnotherMethod we still have the dependency. We can use StructureMap to remove this dependency too!

[PluginFamily("Default")]
public interface IAnotherObject
{
    ...
}

[PluginFamily("Default")]
public interface ICallingObject
{
    ...
}

[Pluggable("Default")]
public class AnotherObject : IAnotherObject
{
    private IWidget _widget;
    public AnotherObject(IWidget widget)
    {
        _widget = widget;
    }

    public void SomeMethod()
    {
        //..do something with _widget
    }
}

[Pluggable("Default")]
public class CallingObject : ICallingObject
{
    public void AnotherMethod()
    {
        ObjectFactory.GetInstance<IAnotherObject>().SomeMethod();
    }
}

Notice that no where in the above code are we instantiating an actual implementation of AnotherObject. Because everything is wired for StructurMap we can allow StructureMap to pass in the appropriate implementations depending on when and where the code is ran. Now the code is truely flexible in that we can specify via configuration or programatically in a test which implementation we want to use. This configuration can be done on the fly or as part of a build process, etc. But it doesn't have to be hard wired anywhere.

Andrew Siemer
+2  A: 

Appologies as this doesn't answer your question regarding a case for Interfaces.

However I suggest getting the person in question to read..

Head First Design Patterns

-- Lee

Lee Englestone
+3  A: 

Interfaces are not 'required for' at all, it's a design decision. I think you need to convince yourself, why, on a case-by-case basis, it is beneficial to use an interface, because there IS an overhead in adding an interface. On the other hand, to counter the argument against interfaces because you can 'simply' use inheritance: inheritance has its draw backs, one of them is that - at least in C# and Java - you can only use inheritance once(single inheritance); but the second - and maybe more important - is that, inheritance requires you to understand the workings of not only the parent class, but all of the ancestor classes, which makes extension harder but also more brittle, because a change in the parent class' implementation could easily break the subclasses. This is the crux of the "composition over inheritance" argument that the GOF book taught us.

toby
What is the GOF book?
Vaccano
http://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional/dp/0201633612
toby
+3  A: 

You've been given a set of guidelines that your bosses have thought appropriate for your workplace and problem domain. So to be persuasive about changing those guidelines, it's not about proving that interfaces are a good thing in general, it's about proving that you need them in your workplace.

How do you prove that you need interfaces in the code you write in your workplace? By finding a place in your actual codebase (not in some code from somebody else's product, and certainly not in some toy example about Duck implementing the makeNoise method in IAnimal) where an interface-based solution is better than an inheritance-based solution. Show your bosses the problem you're facing, and ask whether it makes sense to modify the guidelines to accommodate situations like that. It's a teachable moment where everyone is looking at the same facts instead of hitting each other over the head with generalities and speculations.

The guideline seems to be driven by a concern about avoiding overengineering and premature generalisation. So if you make an argument along the lines of we should have an interface here just in case in future we have to..., it's well-intentioned, but for your bosses it sets off the same over-engineering alarm bells that motivated the guideline in the first place.

Wait until there's a good objective case for it, that goes both for the programming techniques you use in production code and for the things you start arguments with your managers about.

d__