Reputation: 5
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
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 !!!
Upvotes: 0
Views: 229
Reputation: 19096
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.
Upvotes: 1