I\'ve struggled for the last couple of months to come up with some clean code to report progress to a user. Everything always seems to boil down to:
ReportProgr
A fairly simple and clean way would be to create an abstract class that has a do()
method and abstract doTask() and getName() methods:
do() {
ReportProgress("Starting " + this.getName());
doTask();
ReportProgress("Finished " + this.getName());
}
Then in your tasks:
class Task1 extends Task {
getName(){return "Task 1";}
doTask() {
//do stuff here
}
}
You could then have a Task that has a doTask() method that runs do()
on a whole bunch of other tasks. This could easily be recursive, in that any Task might then run a number of sub-Tasks.
set up your tasks as an event stream, and have the event-processing 'engine' report progress. Each event instance can have its own name, progress-reporting blurb/template, etc. if you want to go that far
if this is a pattern that occurs often, it is worth the effort for the infrastructure. When you're done, the usable code might look something like:
EventQueue tasks = new EventQueue();
tasks.Add(new TaskEvent(this.doTask1,"Foo-ing the bar"));
tasks.Add(new TaskEvent(this.doTask2,"Bar-ing the foo"));
tasks.Add(new TaskEvent(this.doTask3,"Glitching and whinging"));
...
tasks.Execute(this.ProgressEventHandler);
You could create a Task class with a name property and delegate. Put each task in a collection, then iterate through it, printing the message and invoking the delegate for each task.
It depends how much config is needed on the fly, I would expect the code to be very general, and have the tasks be setup via spring or any ioc container.
This would all be in a spring config: The xml config would supply the task object with its name and parameters. then add these tasks to a collection, and hand that collection to the taskrunner.
The task runner is then code that signals the stop and start of each task, but each task then is free to give specific status of how it is going. Also the taskrunner will catch any exceptions and keep going if something errs out. It could be made configurable to say that certain tasks depend on the completion of others, and some tasks should halt everything if they fail.
I disagree that AOP should be used here. overkill.
It would be natural to have the reporting inside the doTask() calls.
Typically the reporter would be a singleton that all the objects sent messages to and a reporter class was reponsible for deciding if and where to show it - statusbar, log file, stderr etc.
Assuming the pattern in what you're doing is:
you can have a "Task" class (parent for all your tasks), whose do() method is subclassed and automatically logs start and end of task.
Just an idea.