rohit rohit - 2 months ago 8
C# Question

How to refactor the following code without killing OOPS in C#

I have 3 interfaces with 2 methods each doing the same job.

Interface A
{
Void M1()
Void M2()
}

Interface B
{
Void M1()
Void M2()
}

Interface C
{
Void M1()
Void M2()
}


Now, There are 3 classes implementing each of these interfaces.

Public Class A1:A
{
Public void M1()
{

}
Public void M2()
{

}
}

Public Class B1:B
{
Public void M1()
{

}
Public void M2()
{

}
}

Public Class C1:C
{
Public void M1()
{

}
Public void M2()
{

}
}


Functionality of M1 and M2 is exactly same in 3 classes. Interfaces are a part of library, I cannot change the interface and also cannot declare a new interface.

I want to refactor this code so that this duplication can be removed. I thought of creating a common class containing this functionality and then calling common class from each of these classes.

Please suggest.

Answer

It sounds like you should declare your own interface, and then create an adapter - or possibly multiple adapters. For example:

public interface IUnified
{
    void M1();
    void M2();
}

public class UnifiedAdapter : IUnified
{
    private Action m1;
    private Action m2;

    public UnifiedAdapter(A a)
    {
        m1 = () => a.M1();
        m2 = () => a.M2();
    }

    public UnifiedAdapter(B b)
    {
        m1 = () => b.M1();
        m2 = () => b.M2();
    }

    public UnifiedAdapter(C c)
    {
        m1 = () => c.M1();
        m2 = () => c.M2();
    }

    public M1()
    {
        m1();
    }

    public M2()
    {
        m2();
    }
}

(This uses delegates to avoid having to create multiple adapter classes. The best approach depends on your exact situation.)

Comments