Problem
I have an employeeModel that I'm looking to populate. To do so it involves calling multiple endpoints across multiple clients if certain criteria are met. I was looking for a pattern to apply which would tidy up the multiple if statements into something more concise and extensible. I've approached it using a mixture of the strategy and factory pattern.
-
Does having so many dependencies DI'd into the factory make this an anti pattern?
-
If the strategies themselves are DI'd into the factory, is it breaking the strategy pattern to pass data into them post creation? In this case employee, employeeModel
Original Code
var employee = await employeeClient.GetEmployeeAsync(id);
var employeeModel = mapper.Map<EmployeeModel>(employee);
if(employee.CertificationIds.Count() > 0)
{
var certifications = await employeeClient.GetCertificationsAsync(employee.CertificationIds);
certifications.ForEach(c => employeeModel.Certifications.Add(mapper.Map<CertificationModel>(c)));
}
if(employee.ImageId ! = null)
{
var empImage = await employeeMediaClient.GetEmployeeImageAsync(employee.ImageId);
employeeModel.Image = mapper.Map<ImageModel>(empImage);
}
if(employee.EmploymentActive)
{
var latestSalarySlip = await companyFinancialClient.GetLatestEmployeeSalarySlipAsync(employee.Id);
employeeModel.LatestSalarySlip = mapper.Map<ImageModel>(latestSalarySlip);
}
if(employee.SchemeId != null)
{
var schemeDetails = await schemeClient.GetSchemeAsync(employee.SchemeId);
if(schemeDetails.CompanyFinancing)
{
var schemeFinancialDetails = await companySchemesClient.GetFinancialDetails(schemeDetails.Id)
}
if(schemeDetails.StateFinancing)
{
var schemeFinancialDetails = await stateSchemesClient.GetFinancialDetails(schemeDetails.Id)
}
employeeModel.Scheme = mapper.Map<SchemeModel>(schemeDetails);
employeeModel.Scheme.FinancialDetails = mapper.Map<SchemeFinancialDetails>(schemeFinancialDetails);
}
return employeeModel
Transformed Code
var employee = await employeeClient.GetEmployeeAsync(id);
var employeeModel = mapper.Map<EmployeeModel>(employee);
var strategies = employeeStrategyFactory.Create(employeeModel, employee);
strategyExecutor.Execute(strategies);
EmployeeStrategyFactory
public EmployeeStrategyFactory(IMapper mapper, EmployeeClient employeeClient,
EmployeeMediaClient employeeMediaClient,
CompanyFinancialClient companyFinancialClient,
SchemeClient schemeClient, CompanySchemesClient companySchemesClient,
StateSchemesClient stateSchemesClient, IGetEmployeeCertsStrategy getEmployeeCertsStrategy,
IGetEmployeeMediaStrategy getEmployeeMediaStrategy,
IGetEmployeeSalaryStrategy getEmployeeSalaryStrategy,
IGetEmployeeSchemeDetails getEmployeeSchemeDetails)
{
...
}
public List<IPopulateEmployeeStrategy> GetStrategies(EmployeeModel empModel, Employee emp)
{
if(emp.CertificationIds.Count() > 0)
{
employeeMediaClient.Employee = emp;
employeeMediaClient.EmployeeModel = empModel;
strategies.Add(employeeMediaClient)
}
....
}
Aucun commentaire:
Enregistrer un commentaire