Search code examples
c#refactoring

How to refactor this switch construction


I have generic service IService<T> and some implementation ServiceA: IService<A>, ServiceB: IService<B> that provides different types data A and B. Depends on type I need to call appropriate service, get data from service , check for null and map to type IWidget. Also, i have extension methods for mapping each type, for example

   public static class Mapper 
   {
      public static IWidget Map(this A data)
      { 
          return new WidgetA{......};
      }
      public static IWidget Map(this B data)....
   }

Because of after GetData I get unknow type, I can't to call apropriate mapping. How can i refactor this construction

        IWidget widget;
        switch (currentItem.Type)
        {
            case "A":
                {
                    var data = ServiceA.GetData(ProductAlias);
                    if (data == null)
                    {
                        return EmptyContent;
                    }
                    widget = data.Map();
                    break;
                };
            case "B":
                {
                    var data = ServiceB.GetData(ProductAlias);
                    if (data == null)
                    {
                        return EmptyContent;
                    }
                    widget = data.Map();
                    break;
                };
        }

I would like to get somthing like this

        object data = currentItem.Type switch
        {
            "A" => ServiceA.GetData(),
            "B" => ServiceB.GetData(),
            _ => null
        };
        if (data == null)
        {
            return EmptyContent;
        }

        var widget = data.Map();  - Mapping can't be called from Object type

Solution

  • Map cannot be called because it doesn't belong to object.

    Maybe object data = ... should have a different type or maybe an interface?

    IMyType data = currentItem.Type switch
    

    Or, maybe you can cast data, as in:

    var widget = ((MyTypeWithMapFunction)data).Map();