I built an Async task service executor that execute tasks by external request.
Each task contains the function void run(), so any programmer who want’s to add a task to the system needs to inherit From BaseTask.
interface ITask{
void run();
}
abstract BaseTask : ITask{
//force "run()" to set Result
public ResultContainer Result {set; get;}
void run();
}
class SomeTask : BaseTask {
void run(){
////run the operation here, in the end, set the result.
//force the programmer to set the Result;
this.Result = new ResultContainer("task ok");
}
}
For internal reasons, the run() must be void.
Is there any way that I can force a programmer who wants to add a task to invoke Result in BaseTask and set its value?
Do you think it is a bad practice?
Thanks
Yes, this is something to be avoided. Rules like this should be in place such that they’re enforced by the compiler (rather than convention) when possible and practical.
In your case, you should do something like this:
This will accomplish what you want semantically (that invoking the
Runfunction externally will always cause theResultproperty to be set), and it forces the developer who inherits fromBaseTaskto supply the value that’s being used. The only difference is that they will override (or, rather, implement) theRunInternalfunction instead ofRun.