We help IT Professionals succeed at work.

Improve syntax in code block

AndyC1000 asked
Dear all,

I'm looking to make my program code more concise is there a better way to write the below code block?


if (((hour == hours) && (min == mins))) {

					if (!weekday) {
						value = s.getWeekend();
					} else {
						if (scenarioNumber == 1) {
							value = s.getScenario1();
						} else if (scenarioNumber == 2) {
							value = s.getScenario2();
						} else if (scenarioNumber == 3) {
							value = s.getScenario3();
						} else if (scenarioNumber == 4) {
							value = s.getScenario4();
						} else if (scenarioNumber == 5) {
							value = s.getScenario5();

Open in new window

Watch Question

Well the most obvious improvement would be to modify all of these getScenario1()...getScenario5() methods to be
     getScenario(int scenarioNumber) { }
and then you can replace all of those ifs with:
     value = s.getScenario(scenarioNumber) ;

That assumes that each scenario has something in common.
If they are completely different then of course it just pushes the if inside getScenario().

But presumably they do have something in common, since they're all in the "s" class?

Other options would be:
 - Use reflection to lookup the method name from a string (super ugly)
 - Create multiple classes derived from a base class, each with a "getScenario" method (overkill perhaps but ultimately cleaner)

Any help?

Top Expert 2015

I would also refactor the call to s.getWeekend() into the new method described by Doug above... but perhaps rename it if getScenario() doesnt quite describe the weekend case.
CPColinSenior Java Architect

Hi AndyC1000,

That code looks clear and concise enough to me. You don't need to worry.
Jim CakalicSenior Engineer

I agree with Doug that the preferable ("ultimately cleaner" and more object-oriented) refactoring would appear to be Replace Conditional with Polymorphism. It's hard to say without greater context whether, in fact, this would be helpful or not.  I'll let the refactoring page speak for itself. I think you'll see a fairly strong resemblance between the structure of your problem above and the structure of the code example there.

Best Regards,
Jim Cakalic