0

I have done demo implementation using interface:

class Program
{
    static void Main(string[] args)
    {

        #region Calling method without interface
        GreaterThanZeroTest objGreaterThanZeroTest = new GreaterThanZeroTest { SomeTestVariable = 10 };
        Console.WriteLine(objGreaterThanZeroTest.SomeTestMethod().ToString());

        LessThanZeroTest objLessThanZeroTest = new LessThanZeroTest { SomeTestVariable = -1 };
        Console.WriteLine(objLessThanZeroTest.SomeTestMethod().ToString()); 
        #endregion

        #region Calling using interface
        runTest(new GreaterThanZeroTest() { SomeTestVariable = 10 });
        runTest(new LessThanZeroTest() { SomeTestVariable = 10 }); 
        #endregion

        Console.ReadKey();
    }

    public static bool runTest(ITest test)
    {
        return test.SomeTestMethod();
    }
}

public interface ITest
{
    int SomeTestVariable { get; set; }

    bool SomeTestMethod();
}

// Determines whether an int is greater than zero
public class GreaterThanZeroTest : ITest
{
    public int SomeTestVariable { get; set; }

    public bool SomeTestMethod()
    {
        return SomeTestVariable > 0;
    }
}

// Determines whether an int is less than zero
public class LessThanZeroTest : ITest
{
    public int SomeTestVariable { get; set; }

    public bool SomeTestMethod()
    {
        return SomeTestVariable < 0;
    }
}

I see two benefit from the above implementation:

  1. Code will look clean.
  2. It will save one line of code.

What are the other benefits that we will get from such implementation and when we should consider interface in the application architecture?

1 Answers1

0

IMHO, the most important thing for me is it allows you to

  1. Mock some function for unit testing purpose.
  2. It allows the implementation of "Inversion of Control" or IoC

There are plenty of reasons in the universe you can just search it though but these are what I think are important

Ray Krungkaew
  • 6,652
  • 1
  • 17
  • 28