views:

323

answers:

5

Hi,

These 2-3 last years, many projects I see, like Cuyahoga open source C# CMS, tends to define persistent and non persistent classes as Interface. Why? Is there a good reason? TDD? Mocking? A design pattern? ...

+17  A: 

The main reason is that this makes techniques like dependency injection easier. This in turn allows for more flexibility in the software and easier reuse and recombination of existing code. Examples for where this is useful include the various forms of unit testing (as you mentioned), but also most other forms of "regular" code reuse.

A simple example:

Say you have a method that calculates emplyoee salaries. As part of its signature, it accepts an object that calculates their benefits, say an instance of BenefitCalculator:

calculateSalary(... BenefitCalculator bc, ...)

Originally, your design has only one class BenefitCalculator. But later, it turns out that you need more than one class, e.g. because different parts of the software are supposed to use different algorithms (maybe to support different countries, or because the algorithm is supposed to be user-configurable...). In that case, rather than bloat the existing implementation of BenefitCalculator, it makes sense to create new class(es), e.g. BenefitCalculatorFrance, or BenefitCalculatorSimple etc.

Now if you use the signature

calculateSalary(... BenefitCalculator bc, ...)

, you are kind of screwed, because you cannot supply different implementations. If however you use

calculateSalary(... IBenefitCalculator bc, ...)

you can just have all classes implement the interface.

This is actually just a special case of "loose coupling": Demand as little as possible from other parts of the code. In this case, don't demand a certain class; instead just demand that certain methods exist, which is just what an Interface does.

sleske
IIRC the term for this is [loose coupling](http://en.wikipedia.org/wiki/Loose_coupling).
Chris Charabaruk
@Chris: Yes, it is. See my answer (last paragraph) :-).
sleske
Ah, I missed reading that originally.
Chris Charabaruk
+1  A: 

Interfaces have the advantage that they make you independent from the implementation, which is a good thing.

codymanix
+3  A: 

First of all, you can't define a class as an interface. Your class implements an interface.

Interfaces are used as one way to enable polymorphic behavior. Each class that implements the interface is free to specify its own implementation of the methods defined in the interface. Take the following for example:

You are writing banking software. Your task is to write a Transaction Processor. Now, you know you need to handle different kinds of Transactions (Deposits, Withdraws, Transfers). You could write code that looks like:

public class TransactionProcessor
{
    public void ProcessDeposit( // Process Deposit );
    public void ProcessWithdraw( // Process Withdraw );
    public void ProcessTransfer( // Process Transfer );
}

And then every time somebody adds a new Transaction type, you have to modify your class. Or, you could:

public interface ITransaction { void Process(); }

public class TransactionProcessor
{
    public void ProccessTransaction(ITransaction t) { t.Process(); }
}

Now you don't need to modify your code to Process a new type of transaction. You just need people to create their own class that implements ITransaction and your class will "just handle it".

This allows you to swap implementations of an interface depending on your needs. It also enables things like Dependency Injection and Mocking Frameworks for Unit Testing.

In general though, it really is just another way to make your code more flexible.

Justin Niessner
A: 

During last years IoC containers become quite popular with developers. For example, Unity Container from Microsoft Practices. So, at the start of your application you can register concrete classes which implement interfaces, and then, for example, all classes which contain these interfaces in their constructors, or their properties marked with [Dependency] attribute will be filled, when instancing objects via Unity container's resolve. Its quite useful in the apps with complicated dependencies, when one interface can be implemented in three different classed. And all these things can't be achieved without usage of interfaces.

Kru
A: 

At a really boring level interfaces can also help make for a faster compile.

public class A {
   B b;
}

public class B {
   public int getCount() {
       return 10;
   }
}

In this case every time internal changes to B are made, the compiler needs to re-evaluate A to determine if it needs to be recompiled.

Instead we use interfaces:

class A {
   IB b;
}

interface IB {
   int getCount();
}

class B : IB {
   public int getCount() {
       return 10;
   }
}

In this case A only depends on IB. No change to B requires any consideration of A at compile time.

At scale this effect on short circuiting dependency evaluation can significantly speed up compilation of large code bases. It is particularly powerful when there are a lot of classes depending on a single class that changes a lot.

Clearly this compile time benefit only works if the classes have no static dependency on the implementation classes. Doing the following would totally defeat this benefit:

class A {
    IB b = new B();
}

This is where Dependency Injection comes in. The DI container would construct a B and provide it to A as an IB so A doesn't need to have the static dependency.

Alain O'Dea