views:

130

answers:

4

The argument to my function f() must implement two different interfaces that are not related to each other by inheritance, IFoo and IBar. I know of two different ways of doing this. The first is to declare an empty interface that inherits from both:

public interface IFooBar : IFoo, IBar
{
    // nothing to see here
}

public int f(IFooBar arg)
{
    // etc.
}

This, of course, requires that the classes declare themselves as implementing IFooBar rather than IFoo and IBar separately.

The second way is to make f() generic with a constraint:

public int f<T>(T arg) where T : IFoo, IBar
{
    // etc.
}

Which of these do you prefer, and why? Are there any non-obvious advantages or disadvantages to each?

+2  A: 

Second is quite shorter and more expressive.

Pablo Castilla
A: 

I would suggest the generic method. It frees the implementing object from having to know that two of its interfaces are used together.

Bryan Watts
+2  A: 

The second option is more flexible. By introducing a new interface, you're forcing classes to implement a third interface, which will only be possible if they have a reference to your library (where the interface is defined).

By using generic constraints, the class only needs a reference to the library containing IFoo and IBar, and not IFooBar.

Reed Copsey
Also, create an interface, release it in the wild, never touch it again is a bit harder to accomplish than a generic method...
Will
+1  A: 

The first way you mentioned by creating a super interface appeals OO code because it allows one to express a class as the combined interfaces and interact with it as such.

Since there is a need for such expression, why not make it official and tie the knot by making it a super interface and having it documented for possible future maintenance. IMHO

OmegaMan
Additionally, if you have multiple methods that need the combined interface, it's less verbose to declare the combined interface once than to restate the generic constraint multiple times.
JSBangs