Please see the code below . Here based on the String constants , I am instantiating different types of component classes . Now there are atleast 15 different types of String constants . So if I follow this pattern there will be 15 different cases and those many if -else blocks . Is there a better way of doing this ? I want to have the flexibility of being able to add and delete cases by doing the minimum possible code change.
public UIComponent initCellEditor(String editorType) {
UIComponent editControl = null;
if ("TbComboBoxCellType".equals(editorType)) {
editControl = new WebListEntryField();
editControl.setId("ComboBox");
} else if ("TbStringCellType".equals(editorType)) {
editControl = new WebInputEntryField();
editControl.setId("String");
} else if ("TbDateCellType".equals(editorType)) {
editControl = new WebDateEntryField();
editControl.setId("Date");
} else if ("TbDateTimeCellType".equals(editorType)) {
editControl = new WebDateTimeEntryField();
editControl.setId("DateTime");
} else {
//default editor is allways a text input
editControl = new WebInputEntryField();
editControl.setId("Input");
}
return editControl;
}
P.S: We are using JDK 6 . So can’t use switch on String feature.
you could transform those string constants to Enums, and add a builder method on the enum, for example
The beauty of this approach is that it replaces
IFswith polymorphism (which in my opnion is very OO).Sorry, I just realised that you have a default type (the last else in your code), so you might need to add an
ifsomewhere :(.