tags:

views:

232

answers:

3

I am sure someone may have already asked this type of questions before, but I can't seem to find a similar question.

I have something like this:

client = Client.GetInstance(type.objectA));
if (client != null)
{
  result += client.SaveObjectA(object);
}


client = Client.GetInstance(type.objectB));
if (client != null)
{
  result += client.SaveObjectB(object);
}


client = Client.GetInstance(type.objectC));
if (client != null)
{
  result += client.SaveObjectC(object);
}


client = Client.GetInstance(type.objectD));
if (client != null)
{
  result += client.SaveObjectD(object);
}

I wanna find a good way to reduce this repetitive code.

Please let me know your good thoughts.

Thank you

*** Additional to what i put in previously Forgot to mention a very important part Those methods were generated from a webservice. Here is the interface.

public interface Client
    {
        string SaveObjectA(object);
        string SaveObjectB(object);
        string SaveObjectC(object);
        string SaveObjectD(object);

    }
+9  A: 

Sounds like inheritance would do the trick. Let each client inherit from the same Interface consisting of the method

SaveObject(object o);

then you can just write:

if (client!=null)
{
    result+=client.SaveObject(object);
}

and the polymorphism selects the correct version of SaveObject, depending on the type of the client.

Tobias Langner
+2  A: 

It depends on where you want to put the responsibility for saving objects, but I can think of a couple of different ways using interfaces or a factory that knows both how to create and save objects, perhaps a combination of the two.

string result = string.Empty;
foreach (var type in new Type[] { type.objectA, type.objectB, type.objectC, type.objectD })
{
   var client = Client.GetInstance(type) as IPersistable;
   result += client.Save();
}

where each client implements the IPersistable interface which defines a Save() method.

or

string result = string.Empty;
foreach (var type in new Type[] { type.objectA, type.objectB, type.objectC, type.objectD })
{
   var client = Client.GetInstance(type);
   result += Client.Save( client );
}

where the Client class knows how to Save each type of object it creates.

tvanfosson
+1 I've done this before as well.
Pwninstein
One thing I forgot to mention is those methods were generated from a webservice and they are all located within an interface.I am not sure if it's possible, but I will take a look
junk
+1  A: 
Danny Varod