0

Possible Duplicate:
How will I know when to create an interface?

Hi guys,

This will sound a bit thick, I guess, but I am battling to understand the reason to use interfaces. People keep saying that they are 'contracts' for classes. But, why use them? If I was a single developer, on an application, that I knew no one would ever work on (I know - not a common example, but I am just trying to understand), would I use Interfaces? They seem to just duplicate work. It seem I define what a class must implement, and then go an implement it. I'm doing it twice - why?

Please note: I am not in anyway saying they're useless... I'm just tying to find out why, in projects I work on, they define an IClass, and then based on that, define the class which they use...

Sorry if it's very basic... Just hoping someone can help me out.

3

2 Answers 2

3

I use interfaces because it makes my code a lot more modular. Using interfaces in combination with an inversion of control container (http://code.google.com/p/autofac/) will allow you to swap in various implementations of an interface easily.

Also, interfaces are easier to unit test.

Those are just a couple good reasons; really, there are more. But those are strong enough to make me want to use interfaces.

1

if you want to have several classes that all support the same set of methods. For example you might have a class that stores data and the code that calls them does not care about the details of which class its working with. They must implement methods store and fetch. In this case you can either have an interface with those 2 methods or you can have a common base class.

Why not have a comon base class.

  1. you can only have 1 common base class and you need that for something else
  2. they are really quite different that having a common base class feels forced

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