Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the practical usage of interface not directly implemented in class?

Tags:

c#

oop

I think I have a very naive question here that I didn't knew before that it was even possible. Forgive me if my title question is a bit vague because I don't even know how to describe it. Here is the code that looks weird to me.

public interface IMyInterface
{
    void ImplementMe();
}

public class StandAlone
{
    public void ImplementMe()
    {
        Console.writeline("It works!");
    }
}

public class SubClass : StandAlone, IMyInterface
{
    // no need to implement IMyInterface here but it still work!!!
}

IMyInterface myInterface = new SubClass();
myInterface.ImplementMe();   // Output : "It works!"

I just want to know the following :

  • What is the right term to describe this approach?
  • What is the practical benefit of this kind of approach?
  • What kind of problem it tries to solve? or What scenario this will be applicable?
like image 257
jtabuloc Avatar asked Dec 18 '22 09:12

jtabuloc


1 Answers

Well, first case that comes to my mind - when you don't own source code of StandAlone class, but later you decided to introduce interface which describes behavior of StandAlone class. E.g. for unit-testing (it's not best practice to mock code which you don't own, but sometimes it might be helpful) or you want to provide alternative implementation of StandAlone behavior in some cases. So either you have no options for unit-testing such code:

public class SUT
{
    private readonly StandAlone dependency;

    public SUT(StandAlone dependency)
    {
        this.dependency = dependency;
    }

    // ...
}

But if you'll introduce interface, you can actually switch to dependency from IMyInterface instead of StandAlone. And provide SubClass as implementation of interface with zero efforts.

public class SUT
{
    private readonly IMyInterface dependency;

    public SUT(IMyInterface dependency)
    {
        this.dependency = dependency;
    }

    // ...
}
like image 190
Sergey Berezovskiy Avatar answered Dec 24 '22 01:12

Sergey Berezovskiy