Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best design I can use to define methods with same name?

There is a design problem like this.

Suppose you have a set of class that implements similar methods but not identical ones.

Example : The ClassA has methods like this.

void Add(string str);
void Delete(string str);
List<string> GetInfo(string name);

Another class, ClassB has the following methods.

void Add(Dictionary Info);
void Delete(string str);
Dictionary GetInfo(string name);

So the nature of the methods are similar but the return types/ input parameters are different. If I develop an interface to keep the consistency I can only define Delete operation there. Alternatively I can think about a set of independant class without any relationships with each other (Of course no interface implementations) but I don't think it is a good design.

  1. What is the approach I can use to implement this?
  2. I am new to generic interfaces. Does it help in this case? If so I am going to learn and implement using them.
like image 703
Chathuranga Chandrasekara Avatar asked Nov 19 '10 09:11

Chathuranga Chandrasekara


2 Answers

You can use generic interface here. An example:

interface IModifiable<T>
{
  void Add(T Info);
  void Delete(T item);
  T GetInfo(string name);
}
public class MyClass : IModifiable<List<string>>
{
   public void Add(List<string> list)
   { 
      //do something
   }

   public void Delete(List<string> item)   {  }
   public List<string> GetInfo(string name)  {  }
}
like image 100
Cheng Chen Avatar answered Oct 23 '22 20:10

Cheng Chen


Generics would help you if you can change your design slightly:

interface IFoo<TKey, TValue>
{
    void Add(TKey name, TValue value);
    void Delete(TKey name);
    IEnumerable<TValue> GetInfo(TKey name);
}

This doesn't quite fit your examples, but very nearly. If you can't make this change then I'd say that your classes aren't similar enough that it makes sense for them to have a common interface.

You should also note that this design is very similar to the IDictonary or ILookup interface. Perhaps you can use existing interfaces instead of creating a new one.

like image 33
Mark Byers Avatar answered Oct 23 '22 20:10

Mark Byers