最好的做法,良好的模式,以避免DRY违规

时间:2015-05-28 17:56:43

标签: refactoring dry

我想就以下功能的重构提出一些建议:

有三个功能执行几乎相同的逻辑。

public SendResult ExecuteSendMessageByEmployee(Employee emp, SendingOptions options) {
  var result = SendMessage(emp);

  if (options.DepictEmpData)
  {
    _generator.DepictData(emp);
  }

  if (options.DepictResult)
  {
    _generator.DepictData(result);
  }
}

public SendResult ExecuteSendMessageByID(int employeeID, SendingOptions options) {

  var result = SendMessage(employeeID);

  var emp = _empService.GetByID(employeeID);

  if(emp == null)
  {
     _generator.NotifyNoEmployeeFound(employeeID);
     return new SendResult(){Success = false};
  } 

  if (options.DepictEmpData)
  {
    _generator.DepictData(emp);
  }

  if (options.DepictResult)
  {
    _generator.DepictData(result);
  }

  return result;
}

public SendResult ExecuteSendMessageByDNA(list<byte> dna, SendingOptions options) {

  var result = SendMessage(dna);

  var emp = _empService.GetByID(dna);

  if(emp == null)
  {
     _generator.NotifyNoEmployeeFound(dna);
  }      

  if (options.DepictEmpData)
  {
    _generator.DepictData(emp);
  }

  if (options.DepictResult)
  {
    _generator.DepictData(result);
  }

  return result;
}

上述功能非常相似,但系统可以通过不同的数据关联员工。如图所示:有时我有完整的Employee对象,另一次我只有ID,另一次是DNA字节。

上述功能仅用于描述用例。

应用程序需要在许多地方执行具有不同参数的函数; SendOptions也可以改变。

您对减少冗余代码有什么建议吗?更多KISS,不违反DRY模式?

1 个答案:

答案 0 :(得分:3)

只需从后两种方法中调用您的第一种方法。

public SendResult ExecuteSendMessageByEmployee(Employee emp, SendingOptions options) {
  var result = SendMessage(emp);

  if (options.DepictEmpData) {
    _generator.DepictData(emp);
  }

  if (options.DepictResult) {
    _generator.DepictData(result);
  }
}

public SendResult ExecuteSendMessageByID(int employeeID, SendingOptions options) {
   var emp = _empService.GetByID(employeeID);

   if (emp == null) {
       _generator.NotifyNoEmployeeFound(employeeID);
      return new SendResult(){Success = false};
   }

  return ExecuteSendMessageByEmployee(emp, options);
}

public SendResult ExecuteSendMessageByDNA(list<byte> dna, SendingOptions options) {
   var emp = _empService.GetByID(dna);

   if (emp == null) {
       _generator.NotifyNoEmployeeFound(employeeID);
   }

  return ExecuteSendMessageByEmployee(emp, options);
}