Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Avoid Repetitive Code

Tags:

c#

refactoring

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);

    }    
like image 583
junk Avatar asked May 01 '26 02:05

junk


2 Answers

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.

like image 184
Tobias Langner Avatar answered May 03 '26 17:05

Tobias Langner


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.

like image 43
tvanfosson Avatar answered May 03 '26 17:05

tvanfosson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!