0

I have ~100 tasks described in Tasks.xml. Each task, has some fields such as name, index and priority. In the program eventually each task is represented by the Class Task. I got a requirement to add the ability to run a handler per each task (there are ~15 different possible handlers, some are common). I decided to add to each task in the xml a Handler attriblute:

<Task Name="Task1" Handler="TaskHandler_A">

and to the Class Task add a method named as the Handler attribute value:

public class Task
{
    string name;
    // some more fields

    void TaskHandler_A()
    {
    }

    // some more handlers
    //
    void TaskHandler_P()
    {
    }    
}

That i should run in the program to handle this task at some point (each handler method is about 10 code lines). This should solve the requirfement, however it doesn't seem generic enough, since the code discloses the name of the handlers. Is there a more elegant/generic solution for this requirement, such that i will not need to disclose the Handler names inside the Code?

Grant Winney
  • 65,241
  • 13
  • 115
  • 165

1 Answers1

0

One way is use only one method with a switch statement:

void handler(String handler){
  switch (handler){
    case "TaskHandler_A":
    //relevant code for handler TaskHandler_A
    break;
    case "TaskHandler_B":
    //relevant code for handler TaskHandler_B
    break;
    // other cases
  }
}

Also making a generic method for this scenario depends on the event handling codes in case of how much they have common codes or exactly what do you want the handling code to do

void
  • 7,760
  • 3
  • 25
  • 43