I want to refactor the following code to avoid if...else so that I don't have to change the method every time a new survey type comes in (Open/closed principle). Following is the piece of code I am considering to refactor:
if (surveyType == SurveySubType.Anonymous)
{
DoSomething(param1, param2, param3);
}
else if (surveyType == SurveySubType.Invitational)
{
DoSomething(param1);
}
else if (surveyType == SurveySubType.ReturnLater)
{
DoSomething(param1);
}
To solve the problem, I added the following classes:
public abstract class BaseSurvey
{
public string BuildSurveyTitle()
{
...doing something here
}
public abstract void DoSomething(int? param1,int? param2,int? param3);
}
public class InvitationalSurvey: BaseSurvey
{
public override void DoSomething(int? param1,int? param2,int? param3)
{
//I don't need param2 and param3 here
}
}
public class ReturnLaterSurvey: BaseSurvey
{
public override void DoSomething(int? param1,int? param2,int? param3)
{
//I don't need param2 and param3 here
}
}
public class AnonymousSurvey: BaseSurvey
{
public override void DoSomething(int? param1,int? param2,int? param3)
{
//I need param2 and param3 here
//do something
}
}
And this is what my code ends up:
var survey = SurveyFactory.Create();
survey.DoSomething(param1,param2,param3);
My question is what would be a nice to avoid passing param2 and param3 to InvitationalSurvey and ReturnLaterSurvey classes?
case
switches. Aren't there such an alternative in C#? – StrataC#
does havecase
statements, theswitch
statement which is also mentioned in this question. There's probably some clever way of using delegates or entity references to make it even sleeker though I haven't experienced any yet myself. – Taxexemptswitch
together with default arguments is a solution. In Python you can assign default value to all params and the provide list of updated parameters. Other concern is, if there should be only oneDoSomething
method. Why notProcessLateSurvey
,ProcessAnonSurvey
etc. mehtods? – Lam