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;
}
}
Absolutely. I’ve been taking the polymorphic approach more often myself, and I really like it. Because of Java the language, this will look kind of bloated. We really need lambda expressions to do this properly!
A huge benefit of this approach is the simplicity of your getNextScreen() method. With some thought, it may be possible to make the screenProviders() method more compact–perhaps by adding an abstract class that implements ScreenProvider and pulls out some of the work.