问题描述
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
}
}
}
我的问题是
-
如何重构方法“添加”,以便我们不直接实例化新的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;
}
}
对我来说,我不会再重构该方法了,因为它很短。在此处(在当前状态下)重构不会导致代码更具可读性。
如果方法会发展,那可能会改变。