Reputation: 497
I need some suggestion on OOD. Below is my situation.
Class A{
private B service_;
private StopWatch timer_;
private Const int MinTimeToWait;
public SomeOperation(){
timer_.start();
//call another method on service_ async and subsribe to event for callback
}
private SomeOperationCallback()
{
timer_.stop();
int elapsedTime = timer_.elapsedTime();
if(elapsedTime < MinTimeToWait)
Thread.sleep(MinTimeToWait - elapsedTime)
//Continue after thread resumes
}
}
I have a class that fires an async operation, and after the async operation returns I need to check if the asycn operation returned in less than the MinTimeToWait, if yes wait for the MinTimeToWait completes and then proceed with other operations.
Now, am doing the right thing by including the logic to check the times and wait in the SomeOperationCallback, or should I create a new class that encapsulates the logic and StopWatch and use that class to do this check and wait?
Thanks in advance for your replies.
Upvotes: 2
Views: 104
Reputation: 815
As, Kelly S. French said your approach is well enough. If you want to use this approach in the other classes, it would be better to define base class with methods SomeOperation() and OperationCallback. After that you can inherit from base class and by calling superclass methods achieve reusability. Something like that:
Class Base {
private B service_;
private StopWatch timer_;
private Const int MinTimeToWait;
public SomeOperation(){
timer_.start();
}
protected SomeOperationCallback()
{
timer_.stop();
int elapsedTime = timer_.elapsedTime();
if(elapsedTime < MinTimeToWait)
Thread.sleep(MinTimeToWait - elapsedTime)
}
}
}
class A:Base {
SomeOperation() {
super.SomeOperation();
// do some actions here
super.SomeOperationCallback();
}
}
Upvotes: 0
Reputation: 12334
I do not see any problems with your approach. The issue looks more like what to name 'A', maybe 'MinWaitProcess'. Its responsibility is to ensure a process waits a minimum amount of time.
Now, am doing the right thing by including the logic to check the times and wait in the SomeOperationCallback, or should I create a new class that encapsulates the logic and StopWatch and use that class to do this check and wait?
If you did that, I suspect it would look just like what you have with class A.
Upvotes: 1