I am planning to move the validations to a separate function for granularity and easy to maintain unit tests. However, I would need some variables which are hitting the database in the Validate method to be reused in Process method and make sure it is unit testable.
Current Implementation
interface ICustomerService
{
void Process();
}
public class CustomerService: ICustomerService
{
ICustomerDbService db;
public CustomerService(ICustomerDbService customerDbService)
{
db = customerDbService;
}
public void Process()
{
//validations
var customer = db.GetCustomer(customerId);
if(customer == null)
return "Not found";
//processing
}
}
//Usage
ICustomerService service = new CustomerService(dbService);
service.Process();
Future Implementation
interface ICustomerService
{
bool Validate(int customerId);
void Process();
}
public class CustomerService: ICustomerService
{
ICustomerDbService db;
public CustomerService(ICustomerDbService customerDbService)
{
db = customerDbService;
}
public bool Validate(int customerId)
{
var customer = db.GetCustomer(customerId);
if(customer == null)
return "Not found";
//other processing with multiple(3-4) common variables
}
public void Process()
{
var customer = db.GetCustomer(customerId); // How to avoid this call
}
}
//Usage
ICustomerService service = new CustomerService(dbService);
bool isValid = service.Validate(10)
if(isValid)
{
service.Process();
}