1

I have a database-driven application that runs different surveys. Most of the behaviour of each of the surveys is similar and can be represented using common patterns. But occasionally, I would like to have some special code to implement some of the functionality for a particular survey.

Now, this is done like this:

switch (SurveyId.ToLower())
{
    case "surveya":
        _testModule = new SurveyA(this);
        await _testModule.Init();
        break;
    case "surveyb":
        _testModule = new SurveyB(this);
        await _testModule.Init();
        break;
    default:
        break;
}

So basically with a switch identifying the exceptions.

Later in this code, I call some methods on the _testModule class.

I understand I could do this by overriding a base implementation. Then I would not have this switch, but I would call the standard method, and have this overridden in a derived class. But that would mean the same switch comes at a higher level, calling a class that overrides the base class instead of the base class itself. Basically, it would just move this switch-up in the stack, but it would not reduce complexity.

At other points in the code in a web API, inheritance does not seem to help at all, and I see no other way than this switch.

So what is the best way to handle this?

Ondiek Elijah
  • 547
  • 8
  • 15
Pieter van Kampen
  • 1,957
  • 17
  • 21
  • So, you have the same API with slightly different behavior? - Interfaces come to mind, various behavioral design patterns ... but basically you'll _always_ have to have one place where it's a decision between A or B. – Fildor May 25 '21 at 16:35
  • "Best way" is opinion based. It's not clear what the objection to the `switch` is, especially if you're just talking about _instantiating_ the object, and after that you do take advantage of polymorphic behavior. You can use reflection to instantiate a type based on a name, or you can create a dictionary with factory methods to perform the work, but none of these are clearly _better_ than just using a `switch`. – Peter Duniho May 25 '21 at 21:16

0 Answers0