Home » c# » Why I should go for Interfaces in C# when I can implement the methods directly

Why I should go for Interfaces in C# when I can implement the methods directly

Posted by: admin November 29, 2017 Leave a comment

Questions:

I am aware that this is a very basic question, but an interviewer asked me in a very trick way and I was helpless 🙁

I know only material or theoretical definition for an interface and also implemented it in many projects I worked on. But I really don’t understand why and how is this useful.

I also don’t understand one thing in interface. i.e for example, we use

conn.Dispose(); in finally block. But I don’t see that class is implementing or inheriting IDisposable interface (SqlConnection) class I mean. I am wondering how I can just call the method name. Also in the same thing, I am not understanding how Dispose method works as because, we need to implement the function body with our own implementation for all interface methods. So how Interfaces are accepted or named as contracts? These questions kept on rolling in my mind till now and frankly I never saw any good thread that would explain my questions in a way that I can understand.

MSDN as usual looks very scary and no single line is clear there (Folks, kindly excuse who are into high level development, I strongly feel that any code or article should reach the mind of anyone who see it, hence like many others say, MSDN is not of use).

The interviewer said:

He has 5 methods and he is happy to implement it in the class directly, but if you have to go for Abstract class or interface, which one you choose and why ? I did answered him all the stuffs that I read in various blog saying advantage and disadvantage of both abstract class and interface, but he is not convinced, he is trying to understand “Why Interface” in general. “Why abstract class” in general even if I can implement the same methods only one time and not gona change it.

I see no where in net, I could get an article that would explain me clearly about interfaces and its functioning. I am one of those many programmers, who still dont know about interfaces (I know theoretical and methods I used) but not satisfied that I understood it clearly.

Answers:

Interfaces are excellent when you want to create something like it:

 using System;

namespace MyInterfaceExample
{
    public interface IMyLogInterface
    {
        //I want to have a especific method that I'll use in MyLogClass
        void WriteLog();       
    }

    public class MyClass:IMyLogInterface
    {

        public void WriteLog()
        {
            Console.Write("MyClass was Logged");
        }
    }

    public class MyOtherClass :IMyLogInterface
    {

        public void WriteLog()
        {
            Console.Write("MyOtherClass was Logged");
            Console.Write("And I Logged it different, than MyClass");
        }
    }

    public class MyLogClass
    {
        //I created a WriteLog method where I can pass as parameter any object that implement IMyLogInterface.
        public static void WriteLog(IMyLogInterface myLogObject)
        {
            myLogObject.WriteLog(); //So I can use WriteLog here.
        }
    }

    public class MyMainClass
    {
        public void DoSomething()
        {
            MyClass aClass = new MyClass();
            MyOtherClass otherClass = new MyOtherClass();

            MyLogClass.WriteLog(aClass);//MyClass can log, and have his own implementation
            MyLogClass.WriteLog(otherClass); //As MyOtherClass also have his own implementation on how to log.
        }
    }
}

In my example, I could be a developer who write MyLogClass, and the other developers, could create they classes, and when they wanted to log, they implement the interface IMyLogInterface. It is as they were asking me what they need to implement to use WriteLog() method in MyLogClass. The answer they will find in the interface.

Questions:
Answers:

Interfaces are contracts that implementers must follow. Abstract classes allow contracts plus shared implementations – something that Interfaces cannot have. Classes can implement and inherit multiple interfaces. Classes can only extend a single abstract class.

Why Interface

  • You don’t have default or shared code implementation
  • You want to share data contracts (web services, SOA)
  • You have different implementations for each interface implementer (IDbCommand has SqlCommand and OracleCommand which implement the interface in specific ways)
  • You want to support multiple inheritance.

Why Abstract

Questions:
Answers:

One reason I use interfaces is because it increases the flexibility of the code. Let’s say we got a method that takes an object of class type Account as parameter, such as:

  public void DoSomething(Account account) {
  // Do awesome stuff here.
}

The problem with this, is that the method parameter is fixed towards an implementation of an account. This is fine if you would never need any other type of account. Take this example, which instead uses an account interface as parameter.

public void DoSomething(IAccount account) {
  // Do awesome stuff here.
}

This solution is not fixed towards an implementation, which means that I can pass it a SuperSavingsAccount or a ExclusiveAccount (both implementing the IAccount interface) and get different behavior for each implemented account.

Questions:
Answers:

In one word – because of Polymorphism!

If you “Program to an Interface, not an Implementation” than you can inject different objects which share the same interface(type) into the method as an argument. This way your method code is not coupled with any implementation of another class which means it’s always open to work with newly created objects of the same interface. (Open/Close Principle)

  • Look into Dependency Injection and definitely read Design Patterns – Elements of Reusable Object-Oriented Software by GOF.
Questions:
Answers:

C# doesn’t have duck typing – just because you know a certain method is implemented across a set of concrete classes doesn’t mean you can treat them all the same with regards to calling that method. Implementing an interface allows you to treat all classes implementing it as the same type of thing, with regards to what that interface defines.

Questions:
Answers:

You can only inherit from one abstract class. You can inherit from multiple interfaces. This determines what I use for most of the cases.

The advantage of abstract class would be that you can have a base implementation. However, in the case of IDisposable, a default implementation is useless, since the base class does not know how to properly clean things up. Thus, an interface would be more suitable.

Questions:
Answers:

With an interface you can do the following:

1) Create segregated interfaces which offer differing cuts of your implementation, allowing for a more cohesive interface.

2) Allow for multiple methods with the same name between interfaces, because hey, you have no conflicting implementation, just a signature.

3) You can version and hive off your interface independantly of your implementation, ensuring a contract is met.

4) Your code can rely on abstraction rather than concretion, allowing for smart dependency injection, including injecting test Mocks etc.

There are many more reasons I’m sure, these are just a few.

An abstract class allows you to have a partially concrete base to work from, this is not the same as an interface but has its own qualities such as the ability to create partial implementation using the template method pattern.

Questions:
Answers:

Both abstract class and interface are contracts.

The idea of a contract is you specify some behavior. If you say you’ve implemented you’ve agreed to the contract.

The choice of abstract over interrface is.

Any non abstract descendant of the abstract class will implement the contract.

versus

Any class that implements the interface will implement the contract.

So you use abstract when you want to specify some behavior all descendants must implement and save yourself defining a separate interface, but now everything that meets this effectively aggregated contract must be a descendant.

Questions:
Answers:

I believe that many blood was already spilled in asking this questions, and many tries to resolve this issues by explaining robot-like terms that no normal human can understand.

So First. to learn why interface and why abstract you need to learn what are them for. I personnaly learned this two when applying Factory Class. you find a good tuturial on this link

Now let’s dig-in base on the link I already gave.

You have Vehicle class that might change upon user requirement (like adding Truck, Tank, Airplane, etc. And given we have

public class clsBike:IChoice
{
   #region IChoice Members
    public string Buy()
    {
       return ("You choose Bike");
    }
    #endregion
}

and

public class clsCar:IChoice
{
   #region IChoice Members
    public string Buy()
    {
       return ("You choose Car");
    }
    #endregion
}

and both has Contract IChoice that simply say My Class should have Buy method

public interface IChoice
{
    string Buy();
}

Now, you see, that interface only enforce the method Buy() but let the inherited class decide what to do when they implement it. This is the limitation of Interface, using purely interface, you might end up repeating some task that we can implement automatically using abstact. On our example let say, buying each vehicle has a discount.

public abstract class Choice
{
    public abstract string Discount { get; }
    public abstract string Type { get; }
    public string Buy()
    {
       return "You buy" + Type + " with " + Discount;
}
public class clsBike: Choice
{
    public abstract string Discount { get { return "10% Discount Off"; } }
    public abstract string Type { get { return "Bike"; } }
}

public class clsCar:Choice
{
    public abstract string Discount { get { return " $15K Less"; } }
    public abstract string Type { get { return "Car"; } }
}

Now using the Factory Class, you can achieve the same thing but in using abstract, you let the base class execute the Buy() method.

In Summary : Interface contracts let the inherit class do the implementation
while Abstract class Contracts may initialize the implementation (which can override by Inherit class)

Questions:
Answers:

enter image description here

So in this example, the PowerSocket doesn’t know anything else about the other objects. The objects all depend on Power provided by the PowerSocket, so they implement IPowerPlug, and in so doing they can connect to it.

Interfaces are useful because they provide contracts that objects can use to work together without needing to know anything else about each other.

Questions:
Answers:

Interfaces allow the class designer to make the available methods very clear for the end user. They are also an integral part of polymorphism.

Questions:
Answers:

I won’t post the definition of an interface against an abstract class because I think you know very well the theory and I assume you know the SOLID principles so let’s get practical.

As you know interfaces cannot have any code so the dis-vantage are quite simple to understand.

if you need to initialize the property of your class providing a constructor or you want to provide part of the implementation an abstract class would be a good fit against an interface which would not allow you to do that.

So in very general you should prefer abstract class to interfaces when you need to provide a constructor or any code to the client which will inherit/extend your class

Questions:
Answers:

Abstract class are crated for related entities where as Interfaces can be used for unrelated entities.

For e.g if I have two entities say Animal and Human then i will go for Interface where as if i have to go in detail say Tiger,lion and want to relate with Animal then will choose Animal Abstract class..

will look like below

   Interface             
   ____|____
  |        |
Animal   Human



  Animal (Abstract class)
   __|___
  |      |
Tiger   Lion