IMZRH的日志

努力成为一个有用的人

导航

31天重构指南之十五:移除重复内容

Posted on 2009-09-29 15:43  张荣华  阅读(409)  评论(0编辑  收藏  举报

这是最常用的重构之一,我们经常要用到它,因为我们的代码中经常因为这或那的原因产生重复代码,让我们来看下面的例子:

   1: public class MedicalRecord
   2: {
   3:     public DateTime DateArchived { get; private set; }
   4:     public bool Archived { get; private set; }
   5:  
   6:     public void ArchiveRecord()
   7:     {
   8:         Archived = true;
   9:         DateArchived = DateTime.Now;
  10:     }
  11:  
  12:     public void CloseRecord()
  13:     {
  14:         Archived = true;
  15:         DateArchived = DateTime.Now;
  16:     }
  17: }
下面是我们重构后的代码,请记住只要有可能就请应用该重构,因为这可以帮你减少代码中的bug数量,另外请牢记DRY(don’t repeat yourself)原则,尽量不要复制/粘贴代码。
   1: public class MedicalRecord
   2: {
   3:     public DateTime DateArchived { get; private set; }
   4:     public bool Archived { get; private set; }
   5:  
   6:     public void ArchiveRecord()
   7:     {
   8:         SwitchToArchived();
   9:     }
  10:  
  11:     public void CloseRecord()
  12:     {
  13:         SwitchToArchived();
  14:     }
  15:  
  16:     private void SwitchToArchived()
  17:     {
  18:         Archived = true;
  19:         DateArchived = DateTime.Now;
  20:     }
  21: }
原文链接:http://www.lostechies.com/blogs/sean_chambers/archive/2009/08/15/refactoring-day-15-remove-duplication.aspx