Search code examples
c#c#-5.0code-duplication

Can this be simplified in C#?


I have some duplicated code, but not sure of the best way to simplify it.

private void CheckData(long PKID, int ExpectedResult, string Server)
{
    var a = _ARepo.GetAll();
    var b = _BRepo.GetAll();

    if(Server == "A")
    {
        a.Find(x => x.PKID == PKID).Result.ShouldBe(ExpectedResultId);
    }

    if (Server == "B")
    {
        b.Find(x => x.PKID == PKID).Result.ShouldBe(ExpectedResultId);
    }
}

This is a unit test project and I'm using the Shouldly library. Any ideas appreciated.


Solution

  • private void CheckData(long PKID, int ExpectedResult, string Server)
    {
        //Setting to empty because I don't know what happens if it is not "A" nor "B"
        IEnumerable<YourType> data = Enumerable.Empty<YourType>();
    
        if(Server == "A")
            data = _ARepo.GetAll();
        else if(Server == "B")
            data = _BRepo.GetAll();
    
        data.Find(Find(x => x.PKID == PKID).Result.ShouldBe(expectedId);
    }
    

    If the Server value can be only A or B then you can replace with an if else or better still a ?: operator Then it will look like:

    var data = Server == "A" ? _ARepo.GetAll() : _BRepo.GetAll();
    data.Find(Find(x => x.PKID == PKID).Result.ShouldBe(expectedId);
    

    In the case that both Repos implement the same interface a better design will be to get the IRepo as a parameter of the function. That way the function has only 1 role - which is to check data (and not also to decide which data to check)