I should use polymorphism over conditionals but can I use it in below case ?
Below code returns a Screen object depending on contents of jsonObject.
public static Screen getNextScreen(){
JSONObject jsonObject = RatingsUtils.getCurrentJsonObjectFromServer();
if(isNextProgramScreen(jsonObject)) {
ParentRatingsObject parentRatingsObject = JsonBusinessObjectFactory.createParentRatingsObject(jsonObject);
return new NextProgramScreen(parentRatingsObject);
}
else if(isTimerScreen(jsonObject)) {
ChildWithParentRatingsObject childWithParentRatingsObject = JsonBusinessObjectFactory.createChildWithParentRatingsObject(jsonObject);
return new TimerScreen(childWithParentRatingsObject);
}
else if(isNextContestantPreJudgeScreen(jsonObject)) {
ChildWithParentRatingsObject childWithParentRatingsObject = JsonBusinessObjectFactory.createChildWithParentRatingsObject(jsonObject);
return new NextContestantPreJudgingScreen(childWithParentRatingsObject);
}
else if(isNextContestantJudgeScreen(jsonObject)) {
ChildWithParentRatingsObject childWithParentRatingsObject = JsonBusinessObjectFactory.createChildWithParentRatingsObject(jsonObject);
return new TimerScreen(childWithParentRatingsObject);
}
else {
return null;
}
}
is...Screen()functions do.is...()methods by creating a type enum and using aHashMap<String,JSonObjectType>. You can then have a singlegetJSonObjectType()method that looks the enum value up in the map. And you can replace your if...else chain with a switch-case construct.