Search code examples
c#refactoringcode-duplicationduplication

How can i factor out this code to avoid code duplication in C#?


I have the following code:

private int AllFeb(Forecast f, IRepository repository)
{
    return All(f, repository, f.Feb);
}

private int AllJan(Forecast f, IRepository repository)
{
    return All(f, repository, f.Jan);
}

private int All(Forecast f, IRepository repository, int callBk)
{
    var otherForecasts = repository.Query<Forecast>().Where(r => r.PersonId == f.PersonId);
    if (otherForecasts.Any())
    {
        return otherForecasts.Sum(r => r.Feb) + callBk;
    }
    return 0;
}

As you can see, I am trying to come up with a shared function that can be reused for every month. The issue is that I need the following line in the All method:

otherForecasts.Sum(r => r.Feb)

to be generic but I need the callback inside the Sum method to be passed from outside (since I don't want it to be hardcoded as r.Feb.

Is there any way to avoid having code duplication here?


Solution

  • Pass an Expression<Func<Forecast, int>> into the All() method.

    private int AllFeb(Forecast f, IRepository repository)
    {
        return All(f, repository, f.Feb, r => r.Feb);
    }
    
    private int AllJan(Forecast f, IRepository repository)
    {
        return All(f, repository, f.Jan, r => r.Jan);
    }
    
    private int All(Forecast f, IRepository repository, int callBk, Expression<Func<Forecast, int>> projection)
    {
        var otherForecasts = repository.Query<Forecast>().Where(r => r.PersonId == f.PersonId);
        if (otherForecasts.Any())
        {
            return otherForecasts.Sum(projection) + callBk;
        }
        return 0;
    }