1

Should we avoid multiple interface if possible? Because I think at most cases a class with multiple interfaces can be replaced with another version with composition and single interface only e.g.:

multiple interface:

public class C implements A,B{
    @Override
    public void a(){
    }
    public void b(){
    }
}

composition and single interface:

public class ConcreteA implements A{
    @Override
    public void a(){
    }
}

public class ConcreteB implements B{
    @Override
    public void b(){
    }
}

public class C{
    ConcreteA a;
    ConcreteB b;
}

and if 2 interfaces have common parts, I can separate the common parts from the original class:

multiple interface:

public class C implements A,B{
    @Override
    public void a(){
    }

    @Override
    public void b(){
        a();
    }
}

composition and single interface:

public class ConcreteA implements A{
    @Override
    public void a(){
    }
}
public class C implements B{
   ConcreteA a;
   @Override
   public void b(){
       a.a();
   }
}

And even implement serializable:

public class C implements A,Serializable{
    String name;
    int userId;
    @Override
    public void a(){
    }
}

Actually I can wrap the Serializable part into a new class:

public class CData implements Serializable{
    public String name;
    public int userId;
} 

public class C{
    public CData;
    public ConcreteA a;
}

So my question is, should we prefer composition over multiple interface, i.e. : limit the class to implement at most one interface only , just like prefer composition over inheritance, if possible?

10

It's not really a question of which is preferred. They are different solutions to different problems.

You would do this if a C is an A and a B:

public class C implements A, B { ... }

You would do this if a C shares some of the behavior of A and B, but is not an A or a B:

public class C {
    private A a;
    private B b;
}

This decision should be based on what the classes conceptually represent, not some notion of which approach is "better."

However, implementing many interfaces strongly hints at the interface bloat anti-pattern, which is a violation of the single responsibility principle. A good rule of thumb is that if you can't describe what the class does without using the word "and", you're violating the SRP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.