Search code examples
c#refactoringsingle-responsibility-principle

Does my function violate SRP or other best practices?


I have this following piece of code, a function that will get a list of objects ( I call it Y Objects) and call another method to transform it into X Objects.

public List<X> GetXObjects()
{
    var yObjects= GetYObjects();
    var transformer = new Transformer();
    var xObjects = transformer.Transform(yObjects);
    return xObjects;
}

The current implementation works, however, I feel that my function may violate SRP or other best practices. Is it possible to refactor the code to be better?


Solution

  • I would call the method TransformObjects and add the the transformer as parameter so it is possible to use different transformers and the transformer is not initialized each time you call the method. The same for the yObjects. So the only responsibility of the method is to transform your objects.

    public List<X> TransformObjects(List<Y> yObjects, Transformer transformer)
    {
        var xObjects = transformer.Transform(yObjects);
        return xObjects;
    }
    

    call of the method:

    var yObjects= _crmWrapper.GetActivitiesByOpportunities();
    var transformer = new Transformer();
    myTransformer.TransformObjects(yObjects, transformer);
    

    If you create an interface ITransformer interface it would be easier to enhance your code by exchanging the transformer.