【问题标题】:How to remove duplicate code if I create array with different number of elements? [closed]如果我创建具有不同数量元素的数组,如何删除重复代码? [关闭]
【发布时间】:2013-02-27 09:32:12
【问题描述】:

我有一些重复的代码:

var client = new RSClient.RSClient();

var Params = new RsParameter[1];
Params[0] = new RsParameter {Key = "order_id", Value = orderId};
var result = client.GetPreparedReportSimple(login, password, "CREDO_ORDER", Params);

var client = new RSClient.RSClient();

var Params = new RsParameter[2];
Params[0] = new RsParameter {Key = "calculation_id", Value = calculationId};
Params[1] = new RsParameter {Key = "calculation_date", Value = calculationDate};
var result = client.GetPreparedReportSimpleExport(login, password, "CREDO_RSV_ACTIVE", Params, "XLS");

我怎样才能做得更好?

【问题讨论】:

  • 您能否具体说明“更好”的含义?
  • 更好的意思就是Oscar Mederos推荐的内容
  • 重复代码在哪里?
  • Otiel 我认为他认为这是重复的行 var result = client.GetPreparedReportSimple(login, password, "CREDO_ORDER", Params); & var result = client.GetPreparedReportSimpleExport(login, password, "CREDO_RSV_ACTIVE", Params, "XLS");

标签: c# .net


【解决方案1】:

第一件事,

 1- move the export and simple display functionality into 2 different methods.
 2- Create a Client Object exactly once by using Singleton Pattern.

【讨论】:

    【解决方案2】:

    如果您有超过两种情况,您可以执行循环来迭代和跳过重复代码。只需为每次迭代使用不同的数据(字符串等)创建一个 var:

    keys= new[]
    {
        "order_id",
        "calculation_id",
        //etc
    }
    

    【讨论】:

      【解决方案3】:

      您可以重构代码并提取方法。应该是这样的:

      public __?___ Method(string login, string password, string something, string[] parameters, string extra = null) {
          var client = new RSClient.RSClient();
      
          if (extra == null)
              return client.GetPreparedReportSimple(login, password, something, parameters);
          else
              return client.GetPreparedReportSimple(login, password, something, parameters, extra);
      }
      

      一旦你拥有它,你可以这样称呼它:

      var Params = new [] 
          {
              new RsParameter {Key = "order_id", Value = orderId} 
          };
      var result = Method(login, password, "CREDO_ORDER", Params);
      
      ....
      
      var Params = new [] 
          {
              new RsParameter {Key = "calculation_id", Value = calculationId},
              new RsParameter {Key = "calculation_date", Value = calculationDate}
          };
      var result = Method(login, password, "CREDO_ORDER", params, "XLS");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-12
        • 2018-05-30
        • 2016-12-08
        相关资源
        最近更新 更多