lundi 23 juillet 2018

Removing dependency from a method

I'm currently in the middle of learning DI & IoC principles. So, I stumbled upon such scenario where I have a method with a dependency that can not be injected via constructor. Also, I can not pass it as a method parameter because creation of that instance is conditional + it can only be instanciated with parameters of its own. Here is a super-simplified version of my Employee and WorkYear classes:

public abstract class Employee
{
    public List<WorkYear> WorkYears { get; set; }

    public void StartWorking(DateTime joinedCompany)
    {
        List<PayPeriod> periods = // Calculating periods...
        WorkYear year = WorkYears.FirstOrDefault(y => y.CurrentYear == joinedCompany.Year);

        if (year == null)
        {
            // Here is the problem:
            year = new WorkYear(joinedCompany.Year, this, periods);

            WorkYears.Add(year);
        }
        else
        {
            // Logic when year not null
        }

        year.RecalculateAllTime();
    }

    // More code...
}


public class WorkYear  
{ 
    public WorkYear(int currentYear, Employee employee, List<PayPeriod> periods)
    {
        Employee = employee;
        EmployeeId = employee.Id;
        CurrentYear = currentYear;
        PayPeriods = periods ?? new List<PayPeriod>();

        foreach (PayPeriod period in PayPeriods)
        {
            period.WorkYear = this;
            period.WorkYearId = Id;
        }
    }

     // More code...
}

As you can see I only need a new instance of a WorkYear if Employee doesn't already have it. I found a thread that suggested to use simple factory class to solve similar issue. Such solution could work, but how do I handle parameters without which the WorkYear can not be instantiated?

Would be great to see an example of how to approach this problem.

Aucun commentaire:

Enregistrer un commentaire