I am writing a back-end for a program that manages surveys in TypeScript but don’t know how to design my Survey and SurveyRepository class without violating the Open/Closed Principle (OCP)
My survey class looks like this
class Survey {
private readonly metadata: SurveyMetadata
private readonly options: SurveyOptions
private title: string
private description: string
private readonly questions: Question[]
//getter setter
}
class Question {
private readonly metadata: QuestionMetadata
private required: boolean
private question: string
}
Now I have a class for every question type
class TextQuestion extends Question {
//just a super call
}
class ChoiceQuestion extends Question {
private answerOptions: AnswerOptions
private isMultiple: boolean
}
Now to store my data in the database I wrote a repository class
class SurveyRepository extends IRepositroy {
public insert(survey: Survey): number
}
Now if I want to insert a survey into a database I also need to store the questions for that I need to know the type of the question and the only way I know to do this is like this:
for(const question of questions){
switch(instanceof question){
case TextQuestion:
//code to store text question
break;
case ChoiceQuestion:
//code to store choice question
break;
}
}
But this violates the OCP.
Solutions I thought of:
Make a repository for every question type would be an option but that way the survey repository wouldn’t make any sense
I read about the visitor pattern would that work in this case?