I'm writting a program to show a collection of questions to an user, collect his responses and print them.
I have different types of questions depending on the kind of response they require: integer, boolean or text.
I started writing this code:
abstract class Question
{
string text;
}
class IntegerQuestion : Question
{
int response;
}
class TextQuestion : Question
{
string response;
}
class BooleanQuestion : Question
{
bool response;
}
Well, now we have to print the questions and responses.
My first approach was to define a new abstract Print function in Question class to force subclasses to define the Print method, and then a Printer class:
abstract class Question
{
string text;
abstract string Print();
}
class Printer
{
string PrintQuestions(List<Question> questions)
{
string result = "";
foreach(var question in Questions)
result += question.Print() + "\r\n";
return result;
}
}
Another approach I thought about was to forgive the abstract method and create Printer class like this:
class Printer
{
string PrintQuestions(List<Question> questions)
{
string result = "";
foreach(var question in Questions)
{
if(question is IntegerQuestion)
{
var integerQuestion = (IntegerQuestion)question;
result += integerQuestion.text + integerQuestion.response;
}
if(question is TextQuestion)
{
...
}
...
}
return result;
}
}
Clearly, the second approach doesn't follow the OCP for Printer class and first does it.
But, what about SRP?
If then I need to write questions and responses in HTML:
abstract class Question
{
string text;
abstract string Print();
abstract string PrintHTML();
}
class HTMLPrinter { ... }
¿Aren't question subclasses violating SRP because they know how to print them in plain text and html?