Search code examples
c#solid-principles

Improve generic type checks (factory-ish pattern) to more SOLID oriented?


I was wondering how to better write code like this so that it leverages more SOLID principles...

public static T TransformXmlToEntity<T>(string xml) {
    if(typeof(T) == typeof(EntityA)) {
        return TransformXmlToEntityA(xml);
    } else if (typeof(T) == typeof(EntityB)) {
        return TransformXmlToEntityB(xml); 
    }
}

private static T TransformXmlToEntityA(string xml) {
    var entityA = new EntityA();
    //mapping occurs; sudo code
    entityA.Person = xml.element(Person).value;
    ...
    return entityA;
}
private static T TransformXmlToEntityB(string xml) {
    var entityB = new EntityB();
    //mapping occurs; sudo code
    entityB.Product = xml.element(Product).value;
    ...

    return entityB;
}

This code just feels wrong. But I can't think of how to do it better.


Solution

  • How about a conversion map ?

    private static Dictionary<Type, Func<string,object>> conversionMap = new Dictionary<Type, Func<string,object>> 
    { 
        {typeof(EntityA), TransformXmlToEntityA},
        {typeof(EntityB), TransformXmlToEntityB},
        // ....
    }
    
    public static T TransformXmlToEntity<T>(string xml) 
    {
        return (T)conversionMap[typeof(T)](xml);
    }