lundi 5 novembre 2018

C# Wrapper class wrapping multiple types and composition pattern

I have a wrapper class as following which wraps TypeA,TypeB and TypeC.

class Wrapper
{
    class TypeA {get;set;}
    class TypeB {get;set;}
    class TypeC{get;set;}
}

Now caller code is not good because of this. As I have to determine based on the different types like this:

Wrapper wrapper = new Wrapper(TypeA);

if (wrapper.TypeA != null && wrapper.TypeA.SomeProperty != null)
{
    return wrapper.TypeA.SomeProperty;
}

if (wrapper.TypeB != null && wrapper.TypeB.SomeProperty != null)
{
    return wrapper.TypeB.SomeProperty;
}

Wrapper cwrapper = new Wrapper(TypeA, TypeB);

if (wrapper.TypeA == null && wrapper.TypeB != null && wrapper.TypeB.SomeProperty != null)
{
    return wrapper.TypeB.SomeProperty;
}

As you see, the caller code has to check for lot of combination of TypeA and TypeB and TypeC as well. I was just thinking to use some composition and expose some strategy or property which will give me desired object such as:

wrapper.As<TypeA>() or something. Any suggestion how to avoid this multiple checks from the caller part?

Aucun commentaire:

Enregistrer un commentaire