简体   繁体   中英

C# refactoring in class library

in my class library there is a class A have method "Add"

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

 }    

my question is

  1. how to refactor the method "Add" so we do not directly instantiate the new RePositoryA , RePositoryB and CheckStock? 2.I know one method do three thing violate "only do one thing policy" so above code might need to breakdown in three methods? Like

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

    }

Thanks for the help !!!

You should use Dependency Injection

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

To me, I would not refactor that method more, as it is very short. Refactoring would here (at that current state) not result in more readable code.

That may change if the method will grow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM