0

Would it be considered bad to pass an interface to itself through a method on that interface? To me this seems like it would be bad practice but if someone can help that would be great?

an example

ISomeInterface someInterface1 = new SomeObject1();
ISomeInterface someInterface2 = new SomeObject2();

var someReturnedValue = someInterface.DoSomeWork(someInterface2);
chuckd
  • 13,460
  • 29
  • 152
  • 331

2 Answers2

4

Here is an example where it is totally what we want:

public interface ITree
{
    void AddSubTree(ITree subTree);
}

So yes you may need to do it.

EDIT:

To be complete, you may want to use an object with itself too:

public class NetworkInterface
{
    public void ConnectTo(NetworkInterface otherInterface)
    {
    }
}

...

NetworkInterface localhost = new NetworkInterface();
localhost.ConnectTo(localhost);
Pragmateek
  • 13,174
  • 9
  • 74
  • 108
  • The reasoning behind this logic used is to avoid the original logic used which was to pass two objects into a method and have the called method determine which combination of the two objects was passed in. Leading to a long if-else statement in the called method. – chuckd Jun 16 '13 at 02:21
  • Have you a concrete example? Because seems like you could do this with **inheritance**, overriding a given method in sub-classes or with the **visitor pattern** if what you want is **double-dispatch**. – Pragmateek Jun 16 '13 at 13:15
0

It depends on what you do with that. If you know what are you doing it's good, if you don't know what are you doing try and create a prototype see if your design work.

As a general guideline using the same interface within itself is NOT a bad practice.

Good example of interface that use object of the same interface inside themself are given by the composite pattern and the decorator pattern.

Fabio Marcolini
  • 2,315
  • 2
  • 24
  • 30