2009-10-25 261 views
1

我确定有人可能以前已经问过这种类型的问题,但我似乎无法找到类似的问题。C#避免重复代码

我有这样的事情:

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

我想找到一个好办法来减少这种重复的代码。

请让我知道你的好想法。

谢谢

***其他什么,我把前面 忘了提从web服务产生 这些方法非常重要的一部分。这是接口。

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

    }  
+0

名称相似的事实并不一定表示代码可以被重构。你可以发布各种'SaveObject *'函数的代码吗? – 2009-10-25 13:43:35

+0

没有冒犯......但上面的代码让我想起了每天的WTF入口......不记得哪个...... – Graviton 2009-10-25 15:22:05

回答

9

听起来像继承会做的伎俩。让每一个客户选自方法

SaveObject(object o); 

的相同的接口继承,那么你可以这样写:

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

和多态性选择SaveObject正确的版本,这取决于客户端的类型。

2

这取决于你想要把保存对象的责任放在哪里,但是我可以用接口或工厂的几种不同方式来思考如何创建和保存对象,或许是这两者的组合。

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

其中每个客户端实现定义Save()方法的IPersistable接口。

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

在客户端类知道如何保存每种类型的对象它创建。

+0

+1我之前也做过这个。 – Pwninstein 2009-10-25 13:58:14

+0

我忘记提到的一件事是那些方法是从web服务生成的,它们都位于一个界面中。 我不确定是否有可能,但我会看看 – junk 2009-10-25 21:57:58

1

如果你必须有一个不同的名称为每个保存方法
(给每个保存方法的不同名称,通常是不好的设计),
使用最佳的性能和更少的重复代码哈希表(字典):

(如果您将散列表添加到使用类而不是静态扩展类,则最终代码会更少)。

static ClientExtensions : class 
{ 
    private delegate string MyDelegate(IClient, object); 

    private static Dictionary<Type, MyDelegate> myDictionary 
     = new Dictionary<Type, MyDelegate>(); 

    /// <summary>Static Contstructor</summary> 
    static MyExtenderType() 
    { 
     myDictionary.Add(typeof(ClientA), SaveObjectAExtensionMethod); 
     myDictionary.Add(typeof(ClientB), SaveObjectBExtensionMethod); 
     myDictionary.Add(typeof(ClientC), SaveObjectCExtensionMethod); 
     myDictionary.Add(typeof(ClientD), SaveObjectDExtensionMethod); 
    } 

    // TODO: copy for B, C & D 
    public static string SaveObjectAExtensionMethod(this IClient client, object obj) 
    { 
     return client.SaveObjectA(obj); 
    } 

    public static string SaveObject(this IClient client, object obj) 
    { 
     MyDelegate dele; 
     if (this.myDictionary.TryGetValue(typeof(client), out dele)) 
      return dele(client, obj); 

     throw new NotSupported... 
    } 
}