Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring code in Java, alternatives to large if statement

I'm refactoring some code in a project I'm working on and I ran into a large if/else if statement that follows the format:

if (changer instanceof AppleChanger)
{
   panel = new ApplePanel();
}
else if (changer instanceof OrangeChanger)
{
   panel = new OrangePanel();
} 

Now my first impulse was to refactor it using polymorphism to have it appear like

panel = changer.getChangerPanel();

However unfortunately the class package doesn't have access to the panel package.

My next impulse was to create a PanelChooser class with an overloaded method:

PanelChooser.getPanel(changer);

//Overloaded Method
public Panel getPanel(OrangeChanger changer)
{
   Panel orangePanel = new OrangePanel();
   return orangePanel;
}
public Panel getPanel(AppleChanger changer)
{
   Panel applePanel = new ApplePanel();
   return applePanel;
}

Is this a good solution or is there a better way to solve this?

like image 458
FooBar Avatar asked Jan 10 '12 08:01

FooBar


1 Answers

The fundamental 'problem' here is that you have parallel class hierarchies. You're not going to be able to replace that if statement without some fairly heavy refactoring. Some suggestions are on c2 wiki.

The best you can do, and possibly a perfectly fine solution, is to move the if statement into a 'factory' class and make sure it's not duplicated anywhere else.

like image 140
artbristol Avatar answered Sep 20 '22 16:09

artbristol