Home > Blockchain >  Is this considered as good approach of using interface type in class
Is this considered as good approach of using interface type in class

Time:11-05

Say i have a code as follows

interface Interface1
{
    void method1();
}

interface Interface2
{
    void method2();
}

class ClassWithInterfaces : Interface1,Interface2
{
    void method1(){}
    void method2(){}
}

Now in my "manager" class i implement this as follows :

public OtherClass
{
  Interface1 interface1;
  Interface2 interface2;

  public void someMethod()
  {
    ClassWithInterfaces  classWithInterfaces  = new ClassWithInterfaces();
    interface1 = classWithInterfaces;
    interface2 = classWithInterfaces
  }
}

I don't feel that this is the right way to do it hovewer i can't come up with other solutions i can't use Dependency Injection Frameworks in my project if you ask about that. Can you tell me wheter apart from DI there is a better way of doing that?

CodePudding user response:

Hello and welcome to Stack Overflow :-)

You don't have to use a framework in order to do DI. In fact, there are some languages that make it impossible to use a framework for DI - e.g., C . Any way, in your case, the proper way to do DI is like this:

interface Interface1
{
    void method1();
}

interface Interface2
{
    void method2();
}

interface Interface3 : Interface1, Interface2
{
    void method1();
    void method2();
}

class ClassWithInterfaces : Interface3
{
    void method1(){}
    void method2(){}
}

public OtherClass
{
    Interface3 m_interface3;

    OtherClass(Interface3 interface3)
    {
        m_interface3 = interface3;
    }
 
    public void someMethod()
    {
        m_interface3.method1();
        
        m_interface3.method2();
    }
}

// And now the usage:
public main()
{
    ClassWithInterfaces classWithInterfaces = new ClassWithInterfaces();
    OtherClass otherClass = new OtherClass(classWithInterfaces);
}
  • Related