tags:

views:

366

answers:

13

I know that an interface does not have a body just a method definition. But when should I use interfaces? If I provide someone a set of interfaces with no body, why would they feel a need to write the function body? Would they be better off writing their own abstract class with abstract methods in it.

Edited:

I guess the use of Interfaces is more when you are a part of a team. Suppose Team A writes a code for something and they wanted to see if a call to a method. with name getRecords(), is done or not. This will help Team B to write the body of the interface provided to them and Team B has to keep the method name similar so that code of Team A runs.

Just a thought. I might be wrong. I think Interfaces have no use for a single developer.

Edited:

Thanks all for the answers. With what you all have replied, I think Interfaces have more use when you are making something like API?

+2  A: 

an insterface is better then an abstract classbecause you can implement multiple interfaces, and you can only inherit from 1 abastract class...

so you can say:

class MyRow extends AbstractRow implements ISearchable, ISortable
{
}

also, search SO for other similar questions like http://stackoverflow.com/questions/1620771/need-of-interfaces-in-c

Nicky De Maeyer
A: 

One reason to use interfaces is when a class will implement a number of interfaces. An abstract class cannot do that.

One example is a class which handles mouse movement and key presses will implement both the (ficticious) IMouseMove and IKeyPress interfaces.

paul
+1  A: 

Also, using interfaces eases unit testing. In order to test classes that depend on interfaces, and as long as you are using some sort of dependency injection, you can create stub classes that implement the depended interfaces, or you can use a mocking engine.

Konamiman
+3  A: 

To add to previous answers, interfaces help you during unit testing by allowing you to inject a mock object based on an interface into your code, allowing you to simulate specific scenarios and also to isolate your unit test to a specific component without relying on external components.

For example, suppose you have a business logic class that uses a data logic class to retrieve data from a data source and then process it. By creating an interface for the data logic class which it then inherits, you could create a mock/fake instance of that class based on the interface and inject that into the business logic class you're unit testing. The mocked instance can be defined so as to expect certain method/property calls, throw exceptions at certain points, return valid outputs etc etc. This means, your unit tests can run quicker/potentially more reliably as they are not reliant on the underlying data source being available/don't actually have to connect to it. And you're isolating the unit test down to a specific unit of code.

AdaTheDev
+4  A: 

At first glance, abstract classes and interfaces seem like a no-brainer. Why provide just an interface when you can also provide some base implementation? After investigation, you'll find that there is more to this.

That said, there are a number of reasons to use interfaces. You can find a decent blog post about the differences here.

That said, consider the fact that you can create an interface (a "contract" that says your class definitely supports certain calls/method signature invocations), but you can only provide a single abstract class. Also consider the fact that you can create an abstract class that also implements one or many interfaces, and inherit from this. This isn't a edge-case. This is actually done quite frequently in API's meant for high extensibility.

Check out the blog post I pointed you to and you should get a thorough understanding of when to use each and why you would use them. I would also highly recommend a good book such as "CLR via C#" by Microsoft Press. You'll learn a great deal!

tobint
+4  A: 

In languages such as Java and C# interfaces provide a means for a class to be have in a polymorphic manner. That is to say a class can satisfy more than one contract - it can behave as multiple different types, a class of one type can be substituted for another. In other languages this can also be provided by multiple inheritance, but there are various disadvantages to this approach. However, having a class behave as more than one type is not the most common motivation for using interfaces.

By programming to interfaces instead of classes you can also decouple your program from specific implementations. This makes it much easier to substitute one class implementation for another. This is particularly useful when writing unit tests where you may wish to swap some heavyweight class implementation with a lightweight mock object. If your program only expects an interface type, and both the heavyweight object and mock object implement said interface, then they are very easy to substitute.

Also, consider a simple Java example where I say have a program that displays pages of data on the screen. Initially I want it to get the data from a database or XML files. If I write my program so that it uses interfaces I can define an interface like so:

public interface PageDatasource {
    public List<Page> getPages();
}

And use it like so:

PageDatasource datasource = // insert concrete PageDatasource implementation here
List<Pages> pages = datasource.getPages();
display(pages);

I can then write separate database and XML implementations that adhere to this interface:

public class DatabasePageDatasource implements PageDatasource {
    public List<Page> getPages() {
        // Database specific code
    }
}

public class XmlPageDatasource implements PageDatasource {
    public List<Page> getPages() {
        // XML specific code
    }
}

Because I used an interface I can now use either implementation - Database or XML - interchangeably without having to change the parts of my program that ask for the page data. The XML and Database implementations likely do completely different things but all my program cares about is that the object supplying the page data implements the PageDatasource interface.

teabot
If you are going the interface road then define public IList<Page> getPages() or public IEnumerable<Page> getPages():)
AZ
Ah, it's a Java example - have updated the answer now for clarity :)
teabot
+1  A: 

Java lang does not support multiple inheritance since interfaces are used to achieve the goal.

For a class to be abstract only 1 method has to be abstract ; Whereas in case of interface all methods are abstract .

Ashish
+3  A: 

The reason interfaces exist is due to the 2 principle concepts of OOP, which is "identity" and "functionality"

Classes have functionality and an identity. With inheritance, objects instantiated can have a lot of functionality and multiple identities.

Interfaces are an identity without functionality. The functionality will be provided by the class instantiated.

The third form, a "mixin" is functionality without identity. Programming languages like ruby provide this third form of inheritance.

How you use an interface differs by the context of your programming language and your circumstances, but just remember, interfaces are used to define identities which are enforced onto objects.

Andrew Keith
+1  A: 

Even as a single developer interfaces can be a very useful tool. Let me try to illustrate with an example.

Let's suppose you're developing a system to manage a library catalog and the library will lend both books and DVDs. You decide to create classes Book and Dvd to model items being lent but now you want to implement polymorphism so that you can deal with items rather than books or DVDs. The question is should Item be an abstract class or an Interface ?

In this instance you probably want to use an abstract class since there is functionality common to both Book and Dvd that you can provide by a parent class, for example checking out or returning an item.

Now let's say you want to implement a persistence mechanism for your library catalog. You've decided you want to store some data in a database, some data in XML files and some data in comma delimited files. So the question now is how can you go about doing this in a polymorphic way that allows you to deal with a general persistence API ?

In this case you should probably define an Interface that can be implemented by each of your classes providing the database, XML and comma delimited persistence since each of these persistence mechanisms provides similar features i.e. storing and retrieving data, but each will be implemented very differently. This will allow you to easily change which persistence mechanism you are using without having to make lots of changes to the code that uses the persistence mechanism.

Tony
@Tony: That's well illustrated. Thanks.
RPK
+1  A: 

Abstract class v/s interface is always a point of discussion among developers. I would add my 5 cents. Use abstract class when you want to extend a comman base and where you want to provide a default implementation to the abstract method.

Use interface when you want to exactly implement all the abstract methods to the class implementaing the interface and no default body to a method can be provided.

Sachin Chourasiya
+1  A: 

Interfaces and abstract classes serve different purposes. For a start, an abstract class is only good for inheriting from - it cannot be instantiated directly. You can put implementation code in an abstract class, but that code can only be called from the class that extends it, or through the class that extends it.

example:

public abstract class A {
    public void myFunc() {
        //do some work
    }
}

public class B : A {
    private void someOtherFunc() {
        base.myFunc();
    }
}

public class Z {
    public void exampleFunc() {
        //call public base class function exposed through extending class:
        B myB = new B();
        myB.myFunc();

        //explicitly cast B to A:
        ((A) myB).myFunc();

        //'A' cannot be created directly, do implicit cast down to base class:
        A myA = new B();
        myA.myFunc();
    }
}

The purpose of an interface is to provide a contract - this means the class that implements it has to provide implemetation for the properties or functions declared in the interface, and it has to use the exact same function signatures. This provides surety when i write some code that calls a class that implements an interface, and it is irrelevant what the classes are derived from, or even what language they are written in, or where i got them from. Another cool feature is that i can have several different implementations of the same function signature for different interfaces. Check this example, which uses some of the same classes from the previous sample:

public class Z {
    public void exampleFunc() {
        C myC = new C();
        //these two calls both call the same function:
        myC.myFunc();
        ((IExampleInterface1)myC).myFunc();

        D myD = new D();
        //hmmm... try and work out what happens here, which myFunc() gets called?
        //(clue: check the base class)
        myD.myFunc();

        //call different myFunc() in same class with identical signatures:
        ((IExampleInterface1)myD).myFunc();
        ((IExampleInterface2)myD).myFunc();
    }
}

interface IExampleInterface1
{
    void myFunc();
}

interface IExampleInterface2
{
    void myFunc();
}

public class C : IExampleInterface1
{
    public void myFunc()
    {
        //do stuff
    }
}

public class D : A, IExampleInterface1, IExampleInterface2
{
    void IExampleInterface1.myFunc()
    {
        //this is called when D is cast as IExampleInterface1
    }

    void IExampleInterface2.myFunc()
    {
        //this is called when D is cast as IExampleInterface2
    }
}
slugster
+1  A: 

It's a problem of design (I speak about java world).

The interface allow you to define the behaviour and structure of component (class) of your software without give you constraint in run-time.

The abstract class, instead, gives you a behaviour by default for a method: usefull if you're sure that this code might not change in the lyfe-time of application.

Example:

You have a web application of the commercial system that send an email in some situation (sign up of a new user).

You can use the abstract class SenderCommunication with method boolean sendWithSuccefull(...) if you're sure that the behaviour not will change oftern.

You can use the interface InterfaceSenderCommunication with method boolean sendWithSuccefull(...) if you're not sure that the behaviour not will change often.

Of course, the judice of "change often - not often" depends by 2 elements:

  • How much time I must spent for sync the old code with the new specs?
  • How much the customer pays? ;)
alepuzio
+1  A: 

Interfaces help to clarify the distinction between different functional units. One unit depends on another unit to do something, not to be something. As long as that other can do what's stipulated in the interface (think contract), then it can be anything behind the scenes.

For example, I have a entry processor that reads entries from one place, and writes them to another place. It doesn't care from what/where, or to what/where. All it cares is that it's getting the entry from some type of reader (using the IReader interface) on once side, and handing them off to some type of writer (using the IWriter interface).

In my first implementation, the IReader implementer gets stuff from a SQL database, and the IWriter implementer posts it via a web service client. However, we'll eventually create other implementers on either end to access other repositories (FTP sites, directories of files on a local network drive, etc.).

All this time the processor in the middle doesn't care and doesn't change. It just talks through those standard interfaces.

Theoretically you could use a base class (preferably an abstract one) instead of an interface, but that's starts to lock your modules more tightly together, which makes your system harder to maintain. Lose coupling really does make your life easier, even if you aren't on a team of programmers. Consider yourself as a different programmer, every time you work on a different part of your system. Each time you revisit a given section, you have to relearn what it does to maintain it. If every piece of your system is tightly coupled with every other piece, then you must have a constant, intimate knowledge of the entire system, not just the one piece on which you're working.

There's also the concept of a single class implementing multiple interfaces, which is almost like multiple inheritance. In this situation a single class can perform multiple jobs (which can be argued is not very wise, but at least it's possible). If you chose to use a base class instead of an interface above, then this would not be possible.

Mike Hanson