When should one use interfaces?

OopInterface

Oop Problem Overview


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?

Oop Solutions


Solution 1 - Oop

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.

Solution 2 - Oop

Interface Real Life analogy:

Let say you want to Issue a Book from Library. What you will do:
1) Go to Library
2) Find the Book which interests you
3) Select the Book
4) Go to Librarian Desk to request them to Issue the Book.

Now here Librarian is an Interface, which means you are not interested in who the hell is Librarian, you are only interested in that person sitting on Librarian desk(is the person who agreed to a contract to act as Librarian, which means that person agreed to implement all the behaviors of Librarian)

So let say: Behavior of Librarian are:
1) Issue book
2) Re-Issue Book
3) Return Book.
the person who is designated as Librarian (which means agreed to adapt the above three behaviors), must implement the behaviors in his own way.

Let say PersonA wants to play a part of Librarian, then he needs to adapt the above 3 Behaviors. We as Client don't care how he is performing his Librarian behaviors, we are only interested in that personA is Librarian and he abides to perform the Librarian tasks.
Therefore what you will do, is Reference by Interface[go to Librarian Desk(which will leads you to persons acting as Librarian)] and let say in Future one person left the Librarian post, then as client it won't affect you if you have approached the Librarian desk, instead of specific person acting as Librarian.So code to Interface instead of Concreteness is beneficial.

class PersonA implements Librarian {
	public void IssueBook(){...}
	public void ReIssueBook(){...}
	public void ReturnBook(){...}
	
	//Other person related tasks...
}	

Solution 3 - Oop

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.

Solution 4 - Oop

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.

Solution 5 - Oop

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. Loose 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 maintain a constant, intimate knowledge of the entire system, not just the one piece on which you're working.

There's also the benefit of a single class implementing multiple interfaces, which is somewhat 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 an abstract base class instead of an interface above, then your flexibility is limited.

Solution 6 - Oop

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!

Solution 7 - Oop

An interface is better than an abstract class because you can implement multiple interfaces, and you can only inherit from one abstract class.

So you can do:

class MyRow extends AbstractRow implements ISearchable, ISortable
{
    
}

Also, search StackOverflow for other similar questions like https://stackoverflow.com/questions/1620771/need-of-interfaces-in-c

Solution 8 - Oop

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.

Solution 9 - Oop

Let us assume I have class FoodEstablishment, now I want to do simple CRUD operation, so how do I do it? I define an interface for service, but why?

public interface IFoodEstablishmentService
{
    Task<int> AddAsync(FoodEstablishment oFoodEstablishment);
    FoodEstablishment SelectByFoodEstablishmentId(long id);
    Task<int> UpdateAsync(FoodEstablishment oFoodEstablishment);
    Task<int> DeleteAsync(FoodEstablishment oFoodEstablishment);
}

Then I will implement that contract or interface for that particular service

public class FoodEstablishmentService : IFoodEstablishmentService
{
    public async Task<int> AddAsync(FoodEstablishment oFoodEstablishment)
    {
       // Insert Operation
        return result;
    }

    public FoodEstablishment SelectByFoodEstablishmentId(long id)
    {
        // Select Logic
        return oFoodEstablishment;
    }
    
    public async Task<int> UpdateAsync(FoodEstablishment oFoodEstablishment)
    {
        // Update Logic
        return result;
    }
    
    public async Task<int> DeleteAsync(FoodEstablishment oFoodEstablishment)
    {
        // Delete Logic
        return result;
    }

}

So in my main program or where I wish to use Service, I will do

IFoodEstablishmentService oFoodEstablishmentService =  new FoodEstablishmentService();
FoodEstablishment oFoodEstablishment = // Input might be from views;
oFoodEstablishmentService.AddAsync(oFoodEstablishment);

So till now it seems like an extra step, when we could have directly done

FoodEstablishmentService oFoodEstablishmentService =  new FoodEstablishmentService();
FoodEstablishment oFoodEstablishment = // Input might be from views;
oFoodEstablishmentService.AddAsync(oFoodEstablishment);

But wait what if I might need to pass my insert logic through queue rather than directly to server, wait for insert operation to complete and then return result, rather pass on queue and then the queue worker handles those operation, might not be best idea to queue insert but yes definitely good for interface example :-). So now what I do is, create another class FoodEstablishment implementing same contract IFoodEstablishment.

public class FoodEstablishmentQueueService : IFoodEstablishmentService
{
    public async Task<int> AddAsync(FoodEstablishment oFoodEstablishment)
    {
       // Insert Queue Operation
        return result;
    }

    public FoodEstablishment SelectByFoodEstablishmentId(long id)
    {
        // Select Queue Logic
        return oFoodEstablishment;
    }

    public async Task<int> UpdateAsync(FoodEstablishment oFoodEstablishment)
    {
        // Update Queue Logic
        return result;
    }

    public async Task<int> DeleteAsync(FoodEstablishment oFoodEstablishment)
    {
        // Delete Queue Logic
        return result;
    }
}

So now if I want to use the queue version, I would just do

IFoodEstablishmentService oFoodEstablishmentService =  new FoodEstablishmentQueueService();
FoodEstablishment oFoodEstablishment = // Input might be from views;
oFoodEstablishmentService.AddAsync(oFoodEstablishment);

We could do that with the older way using class but that bounds the class instantiation with a particular class which is kind of rigid to extension, now FoodEstablishmentQueueService can do other things too, create another method until the contract is valid so interface is contact for consistency, Imaging one guy doing the normal version and other doing the queue version or someone doing cache version, there might be problems regarding signature unless its pre-specified about the working contract and people don't end up cross checking everything.

Similarly, let consider other simple example of using predefined types like IEnumerable. Suppose I pass a list of FoodEstablishment collection and return custom sorted list

public FoodEstablishment[] SortFoodEstablishment(FoodEstablishment[] list)
{
    foreach(var oFoodEstablishment in list)
    {
    // some logic
    }
    return sortedList;
}

So we will use it this way

FoodEstablishment[] list = new FoodEstablishment[]{ //some values }
var listSorted = oFoodEstablishmentService.SortFoodEstablishment(list);

But what if we send list instead of array

List<FoodEstablishment> list = //some values;
var listSorted = oFoodEstablishmentService.SortFoodEstablishment(list);

We will get error, because its strict implementation using class so instead we use IEnumerable<> which is implemented by List and that basically removes dependency from List to Interface

public IEnumerable<FoodEstablishment> SortFoodEstablishment(IEnumerable<FoodEstablishment> list)
{
    foreach(var oFoodEstablishment in list)
    {
    // some logic
    }
    return sortedList;
}

So usually implementation hugely depends on situation

Solution 10 - Oop

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
    }
}

Solution 11 - Oop

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? ;)

Solution 12 - Oop

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.

Solution 13 - Oop

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.

Solution 14 - Oop

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 .

Solution 15 - Oop

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.

Solution 16 - Oop

It is considered good style to store a reference to a HashSet or TreeSet in a variable of type Set.

Set<String> names = new HashSet<String>();

This way, you have to change only one line if you decide to use a TreeSet instead.

Also, methods that operate on sets should specify parameters of type Set:

public static void print(Set<String> s)

Then the method can be used for all set implementations.

In theory, we should make the same recommendation for linked lists, namely to save LinkedList references in variables of type List. However, in the Java library, the List interface is common to both the ArrayList and the LinkedList class. In particular, it has get and set methods for random access, even though these methods are very inefficient for linked lists.

You can’t write efficient code if you don’t know whether random access is efficient or not. This is plainly a serious design error in the standard library, and I cannot recommend using the List interface for that reason.

(To see just how embarrassing that error is, have a look at the source code for the binarySearch method of the Collections class. That method takes a List parameter, but binary search makes no sense for a linked list. The code then clumsily tries to discover whether the list is a linked list, and then switches to a linear search!)

The Set interface and the Map interface, are well designed, and you should use them.

Solution 17 - Oop

Interface keeps the definition and implementation Separate.So in case if you want to Vendor specific Implementation then this is the best way to do it .

The real life example of this is JDBC If you see the API Statemnet ,PreparedStatemnet Everything is interface but the implementation is vendor specific like Oracle ojdbc jar has Some other implementation ,mysql had some other.

In case you want to change the Database you just have to chnage the driver nad in connection class name. This is the advantage of using interface

Solution 18 - Oop

Objects that belong to one category can use an Interface.When ever IS-A relationship exists between objects.
E.g. Text,Image,MP3,FLV,MOV belongs FileType category

If our application allows users to upload 4 file types they all belong to one category called FILE TYPE

  1. Text
  2. Image
  3. Audio
  4. Video
Inside code we would have object for each of the above types.

enter image description here

Assume we need to send a file then

With Out Interface       
enter image description here
With Interface 
enter image description here

So we can assume all file types(Text,Audio etc) to be of type FileFormat.So we form a IS-A relationship.

This helps when returning single data type  instead of returning specific type from a function we can send common type that is FileFormat.

enter image description here

Solution 19 - Oop

Uses of interface:

  1. To define a contract
  2. To link unrelated classes with has a capabilities (e.g. classes implementing Serializable interface may or may not have any relation between them except implementing that interface
  3. To provide interchangeable implementation e.g. Strategy_pattern

If you are looking for java as programming language, interface has few more capabilities with addition of default and static methods since Java-8 release.

Refer to this question for more details:

https://stackoverflow.com/questions/8531292/why-to-use-interfaces-multiple-inheritance-vs-interfaces-benefits-of-interface/35970837#35970837

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRKhView Question on Stackoverflow
Solution 1 - OopteabotView Answer on Stackoverflow
Solution 2 - OopbharatjView Answer on Stackoverflow
Solution 3 - OopTonyView Answer on Stackoverflow
Solution 4 - OopAndrew KeithView Answer on Stackoverflow
Solution 5 - OopMike HansonView Answer on Stackoverflow
Solution 6 - OoptobintView Answer on Stackoverflow
Solution 7 - OopNDMView Answer on Stackoverflow
Solution 8 - OopAdaTheDevView Answer on Stackoverflow
Solution 9 - OopSandip BantawaView Answer on Stackoverflow
Solution 10 - OopslugsterView Answer on Stackoverflow
Solution 11 - OopalepuzioView Answer on Stackoverflow
Solution 12 - OoppaulView Answer on Stackoverflow
Solution 13 - OopKonamimanView Answer on Stackoverflow
Solution 14 - OopAshishView Answer on Stackoverflow
Solution 15 - OopSachin ChourasiyaView Answer on Stackoverflow
Solution 16 - Oopcatch23View Answer on Stackoverflow
Solution 17 - OopBrijesh kView Answer on Stackoverflow
Solution 18 - OopSuresh kumarView Answer on Stackoverflow
Solution 19 - OopRavindra babuView Answer on Stackoverflow