I have a use case with 7-8 if else. Sample use case:
String type;
List < Entity > entityList;
if (type.equals(\"A\")) {
ClassA a = new ClassA();
Introduce an interface for all tasks and use a factory pattern. The factory can use a map internally. E.g.
public class TaskFactory {
private Map> taskTypeMap = new HashMap>();
public TaskFactory() {
taskTypeMap.put("A", ATask.class);
taskTypeMap.put("B", BTask.class);
}
public Task createTask(String type) {
Class extends Task> taskType = taskTypeMap.get(type);
if (taskType == null) {
throw new IllegalArgumentException("Task type " + type
+ " is not supported");
}
try {
return taskType.newInstance();
} catch (Exception e) {
throw new IllegalStateException(
"Unable to instantiate Task of type " + taskType, e);
}
}
}
Your client code will then change to
String type = ...;
List entityList = ...;
TaskFactory taskFactory = new TaskFactory();
Task task = taskFactory.createTask(type);
task.performTask();
for (Entity e: entitylist) {
// do some task
}