【问题标题】:C# refactoring in class library类库中的 C# 重构
【发布时间】:2020-09-12 12:13:59
【问题描述】:

在我的类库中有一个类 A 有方法“添加”

 Class A{
        //method A
        bool Add (string Username, string ItemDescription, int Quantity){
              CheckStock checkStock = new CheckStock();
             if (!checkStock.isAvailble) return false;
             RePositoryA rePositoryA= new RePositoryA();
             if (rePositoryA.GetUserID<=0) return false;
             RePositoryB rePositoryB= new RePositoryB();
             if (!rePositoryA.AddInvoice) return false;
             return ture;
        }
    
}
   class RePositoryA {
         
    //get userID based on username 
          int GetUserID (username){
       //connect to database and get id
   }
    
   class RePositoryB {
         
    //add invoice 
          bool AddInvoice(Invoice myInvoice){
       //connect to database and add invoice to dabase
   }
  

     class CheckStock {
             bool isAvailble(string ItemDescription){
             //connect to webAPi and return if its in stock
         }
      }

 }    

我的问题是

  1. 如何重构“Add”方法,使我们不直接实例化新的 RePositoryA 、 RePositoryB 和 CheckStock? 2.我知道一种方法做三件事违反“只做一件事政策”所以上面的代码可能需要分解为三种方法? 喜欢

       bool Add(){
              CheckStock();
              GetUserID();
              AddInvoice();
    

    }

感谢您的帮助!!!

【问题讨论】:

    标签: c# design-patterns refactoring class-library


    【解决方案1】:

    你应该使用依赖注入

    class A
    {
        public A(CheckStock checkStock, RePositoryA repositoryA, RePositoryB repositoryB)
        {
            _checkStock = checkStock;
            _repositoryA = repositoryA;
            _repositoryB = repositoryB;
        }
    
        public bool Add(string Username, string ItemDescription, int Quantity)
        {
            if (!_checkStock.isAvailble) return false;
            if (rePositoryA.GetUserID <= 0 ) return false;
            if (!rePositoryA.AddInvoice) return false;
            return true;     
        }
    }
    

    对我来说,我不会再重构那个方法,因为它很短。在这里(在当前状态下)重构不会产生更具可读性的代码。

    如果方法增长,情况可能会改变。

    【讨论】:

    • 这是否意味着我必须为每个具体类创建接口?如果您将单元测试添加到项目中以测试此方法,这是否意味着可维护和可测试?如果我们不想将接口注入构造函数,我们还能做什么其他方法? (如果我们将这个注入构造函数,这意味着当客户端调用这个类时,它会因为需要这些接口参数而刹车。
    • 你可以,但没必要……你也可以模拟类进行测试。如果你想拥有multiple inheritence,你只需要接口。
    猜你喜欢
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    相关资源
    最近更新 更多