[英]C# refactoring in class library
在我的類庫中有一個類 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
}
}
}
我的問題是
如何重構“Add”方法,以便我們不直接實例化新的 RePositoryA 、 RePositoryB 和 CheckStock? 2.我知道一種方法做三件事違反了“只做一件事”的政策,所以上面的代碼可能需要分解為三種方法? 喜歡
bool Add(){ CheckStock(); GetUserID(); AddInvoice();
}
謝謝您的幫助 !!!
你應該使用依賴注入
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;
}
}
對我來說,我不會更多地重構那個方法,因為它很短。 重構在這里(在當前狀態下)不會導致更易讀的代碼。
如果該方法增長,這可能會改變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.