vendredi 5 avril 2019

How to avoid switch case while implementing functionality similar to reddits posts sort

I have interface ISortPostsStrategy for all sorting strategies (SortPostsByTop, SortPostsByBest, SortPostsByNew) I need sorting with option to choose timeframe for all sorting types without one and I tried using strategy pattern but the problem is that ISortPostsStrategy have timeframe parameter that SortPostByNew dont need and it end up being unused.

public interface ISortPostsStrategy
{
    Task<IEnumerable<Post>> SortAsync(string userId, DateTime startDate);
}


public class SortPostsByNew : ISortPostsStrategy
{
    private readonly UnitOfWork unitOfWork;

    public SortPostsByNew(UnitOfWork unitOfWork)
    {
        this.unitOfWork = unitOfWork;
    }

    public async Task<IEnumerable<Post>> SortAsync(string userId, DateTime startDate)
    {
        var dbPosts = await this.unitOfWork.Posts.GetBySubcribedUserOrderedByNewAsync(userId);
        return dbPosts;
    }
}

public class SortPostsByBest : ISortPostsStrategy
{
    private readonly UnitOfWork unitOfWork;

    public SortPostsByBest(UnitOfWork unitOfWork)
    {
        this.unitOfWork = unitOfWork;
    }

    public async Task<IEnumerable<Post>> SortAsync(string userId, DateTime startDate)
    {
        var dbPosts = await this.unitOfWork.Posts.GetBySubscribedUserOrderedByBestAsync(userId, startDate);
        return dbPosts;
    }
}

Aucun commentaire:

Enregistrer un commentaire