Replacing Conditional With Polymorphism

public boolean CheckVaccineEligibility(String vaccineChosen)
{
if(vaccineChosen=="Covaxin")
{

if(user.age<18 || (user.hasTakenSecondDose) || (user.hasTakenFirstDose &&(CurrentDate - user.firstDose<28)))
return false;

return true;
}
else if(vaccineChosen=="Covishield")
{

if(user.age<18 || (user.hasTakenSecondDose) || (user.hasTakenFirstDose &&(CurrentDate - user.firstDose<56)))
return false;

return true;
}
else if(vaccineChosen=="Johnson&Johnson")
{

if(user.age<18 || (user.hasTakenFirstDose))
return false;

return true;
}}
public boolean CheckVaccineEligibility(String vaccineChosen)
{
switch(vaccineChosen)
{
case "Covaxin":{
if(user.age<18 || (user.hasTakenSecondDose) || (user.hasTakenFirstDose &&(CurrentDate - user.firstDose<28)))
return false;

return true;
}
case "Covishield":{
if(user.age<18 || (user.secondDose) || (!user.firstDose && CurrentDate - user.firstDoseDate <56))
return false;

return true;
}
case "Johnson&Johnson":{
if(user.age<18 || (user.hasTakenFirstDose))
return false;

return true;
} }}
public abstract class VaccineType{
public abstract boolean CheckEligibility();
public static VaccineType Create(String vaccineChosen) {
switch(vaccineChosen)
{
case "Cowaxin":
return new Cowaxin;

case "Covishield":
return new Covishield;

case "Johnson&Johnson":
return new Johnson&Johnson;

default:
return new Default();
}
}
}
public class Cowaxin : VaccineType
{
public override boolean CheckEligibility()
{
if(user.age<18 || (user.hasTakenSecondDose) || (user.hasTakenFirstDose &&(CurrentDate - user.firstDose<28)))
return false;

return true;
}}public class Covishield : VaccineType
{
public override boolean CheckEligibility()
{
if(user.age<18 || (user.hasTakenSecondDose) || (user.hasTakenFirstDose &&(CurrentDate - user.firstDose<56)))
return false;

return true;
}}public class Johnson&Johnson : VaccineType
{
public override boolean CheckEligibility()
{
if(user.age<18 || (user.hasTakenFirstDose))
return false;

return true;
}}public class Default : VaccineType
{
public override boolean CheckEligibility()
{
throw new Exception("Please choose a valid vaccine name");
}}
public boolean CheckVaccineEligibility(String vaccineChosen)
{
var type = VaccineType.Create(vaccineChosen);
return type.CheckEligibility();
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store