How can I validate a C++ object's state upon access without duplication - c++

I have a C++ object running in a separate thread, with its state being updated in an asynchronous manner. The code resembles the following:
class Controller : public Listener {
public:
// Controller methods, to be called by the user from the main thread
// My problem is that I am obliged to duplicate the call to validateState() in all methods
void doAction1() {
validateState(); // explicit call to validate state
}
void doAction2() {
validateState(); // explicit call to validate state duplicated here and in every doActionX() method.
}
...
private:
// Override Listener virtual methods(which are used as callbacks), called in an async manner
void onXYZ() override;
void onError(std::string) override { /* update m_error */ }
...
// validate that no error has occurred
void validateState() {
if(m_error) throw m_error;
}
private:
Error m_error; // updated
};
I thought of a solution, to overload operator-> and call validateState() once inside, and thus removing the duplicated calls. However, the problem is that the user must do controller->doAction1() and be prohibited from doing controller.doAction1().
I can also think of other semantic issues with this approach:
One would expect overloading operator-> would be done for memory management issues (such as having a custom allocator), and not just any random operation.
the lack of symmetry between -> and .
Is duplicating the call for validateState() on newly added methods OK here? The intent being to avoid over-engineered designs.
What would be a plausible approach/design here?

It's perfectly fine for all the public functions of a class to call the same private function. Your function is just making sure the implicit this parameter is valid, which is the same as any other parameter validation
void Controller::doAction1(Arg1 arg1)
{
// ensure preconditions hold
validateState();
validateArg1(arg1);
// "real" code
}
void Controller::doAction2(Arg2 arg2, Arg3 arg3)
{
// ensure preconditions hold
validateState();
validateArg2(arg2);
validateArg3(arg3);
// "real" code
}

Related

C++ freertos Call overriden function of base class from subclass after getting semaphore failes

I am trying to make a base class that holds a semaphore and wait until it can take the semaphore and then call a function in a derived class. (I want to have a number of different base classes that implement the function different but all of them schuld execute this function only after acquiring the semaphore.
I am not very familiar with freertos, so i think probably the error is related to that.
I made some attempts but so far with no success.
Here is the basic code:
The Base class:
class CommandMode{
public:
CommandMode(xSemaphoreHandle* smphr_calc_steps);
virtual ~CommandMode(){};
virtual int GetNextState()=0;
protected:
static void TSK_CalcSteps(void* params);
xSemaphoreHandle* smphr_calc_steps;
virtual void CalculateSteps(){};
};
CommandMode::CommandMode(xSemaphoreHandle* smphr_calc_steps):smphr_calc_steps(smphr_calc_steps){
xTaskCreate(&TSK_CalcSteps, "output data calc", 2048, this, 1, NULL);
}
void CommandMode::TSK_CalcSteps(void* params){
CommandMode* cm = (CommandMode*) params;
while(true){
//force reevaluation at least every 60s
xSemaphoreTake(cm->smphr_calc_steps, 60*1000/portTICK_PERIOD_MS); // i think the problem is related to that line
cm->CalculateSteps();
}
}
and here the derived class:
class Mode1:public CommandMode{
public:
Mode1(xSemaphoreHandle* smphr_calc_steps);
~Mode1(){};
int GetNextState() override;
protected:
void CalculateSteps() override;
};
Mode1::Mode1(xSemaphoreHandle* smphr_calc_steps) : CommandMode(smphr_calc_steps){}
void Mode1::CalculateSteps(){
Serial.println("Mode1::CalculateSteps");
}
int Mode1::GetNextState(){
Serial.println("Mode1::GetNextState");
return 5;
}
Then i try to invoke them similar to this:
CommandMode* current = nullptr;
xSemaphoreHandle smphr = xSemaphoreCreateBinary();
//xSemaphoreHandle smphr2 = xSemaphoreCreateBinary();
Serial.println("init with mode1");
delay(200);
Mode1* a = new Mode1(&smphr);
a->GetNextState(); //This will work
current = a;
current->GetNextState(); //This will work as well
xSemaphoreGive(smphr); //This does not work as intended/causes the issue
Im also not sure about the line cm->CalculateStepes(). Since i passed 'cm' as a void* will it still be evaluating the correct subclass's module? I am running this on an ESP32 with Plattform IO in case this is important.
So far i sometimes got a watchdog error, but mostly i get the following two errors:
/home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/freertos/queue.c:1443 (xQueueGenericReceive)- assert failed!
abort() was called at PC 0x40087f1d on core 0
assertion "res == coreID || res == portMUX_FREE_VAL" failed: file "/home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/freertos/portmux_impl.inc.h", line 105, function: vPortCPUAcquireMutexIntsDisabledInternal
abort() was called at PC 0x400d8cf3 on core 0
I tried use the whole code out of a task itself and experimented with multiple delays(), but I never got it working.
I would be glad if someone could tell me where the problem is, or has a suggestion how to implement this behavior in a better way?
I want to have other functions and values in the base class as well. This works without a problem but the calling of the derived class's function based upon the semaphore is not working at all.
xSemaphoreTake expects the handle to be passed by value, you pass it by pointer, that is definitely wrong.
The code compiles because SemaphoreHandle_t itself is a hidden pointer (hence this not being a good practice, but occurs often in low-level stuff for other good reasons). This also means that you can and should pass and store smphr_calc_steps as a value in your class, being a pointer its cheap to copy. The extra indirection is not needed and only complicates stuff.
FreeRTOS allocates the semaphore on the heap and returns a pointer(=the handle) to you, your only responsibility is to call vSemaphoreDelete sometime in the future to free up the memory.

In what situation should we adopt state pattern?

In what situation should we adopt state pattern?
I've been assigned to maintain a project, the project state machine was implemented by switch-case that are 2000+ lines long. It will be hard to expand function, so I would like to refactor it.
I'm surveying state design pattern, but I have some confusions.
A simple example:
1. Initial state "WAIT", wait user send download command
2. While user send download command, move to "CONNECT" state, connect to server
3. After connection is created, move to "DOWNLOADING" state, keep receive data from server
4. While the data download complete, move to "DISCONNECT", disconnect link with server
5. After disconnect, move to "WAIT" state, wait user send download command
A simple state machine pic
Method 1: Before I survey state pattern, I think a trivial method --- wrapper different state behavior in different function, use a function pointer array to point each state function, and change state by call function.
typedef enum {
WAIT,
CONNECT,
DOWNLOADING,
DISCONNECT
}state;
void (*statefunction[MAX_STATE])(void) =
{
WAITState,
CONNECTState,
DOWNLOADINGState,
DISCONNECTState
};
void WAITState(void)
{
//do wait behavior
//while receive download command
//statefunction[CONNECT]();
}
void CONNECTState(void)
{
//do connect behavior
//while connect complete
//statefunction[DOWNLOADING]();
}
void DOWNLOADINGState(void)
{
//do downloading behavior
//while download complete
//statefunction[DISCONNECT]();
}
void DISCONNECTState(void)
{
//do disconnect behavior
//while disconnect complete
//statefunction[WAIT]();
}
Method 2: The state pattern encapsulates different state and its behavior in different class (object-oriented state machine), uses polymorphism to implement different state behavior, and defines a common interface for all concrete states.
class State
{
public:
virtual void Handle(Context *pContext) = 0;
};
class Context
{
public:
Context(State *pState) : m_pState(pState){}
void Request()
{
if (m_pState)
{
m_pState->Handle(this);
}
}
private:
State *m_pState;
};
class WAIT : public State
{
public:
virtual void Handle(Context *pContext)
{
//do wait behavior
}
};
class CONNECT : public State
{
public:
virtual void Handle(Context *pContext)
{
//do connect behavior
}
};
class DOWNLOADING : public State
{
public:
virtual void Handle(Context *pContext)
{
//do downloading behavior
}
};
class DISCONNECT : public State
{
public:
virtual void Handle(Context *pContext)
{
//do disconnect behavior
}
};
I'm wondering whether the state pattern batter than function pointer in this case or not...
Using function pointer only also can improve readability (compare with switch-case), and more simple.
The state pattern will create several class, and more complex than using function pointer only.
What's the advantage of using state pattern?
Thanks for your time!
What's the advantage of using the state pattern?
First, one needs to notice, that both of the methods you've provided, are in fact examples of the very same pattern. One of the methods describes a function-based implementation, while the other one takes more of an object oriented approach.
That being said, the pattern itself has a few advantages:
It limits the number of states, a program can be in, and thus - eliminates undefined states,
It allows for easier expansion of the application, by adding new states, instead of refactoring the whole code,
From a company perspective, it is safe, even when multiple people work on the same class,
Since you tagged the question as related to c++, it is best to take into account what the language both gives and requires. While classes offer inheritance, a large number of classes can greatly increase the compilation time. Hence, when it comes to implementations, if your state machine is large, static polymorphism may be the way to go.

Why do I have the option to *not* call Concurrency::agent::done inside run?

This is in the context of the Microsoft C++ Concurrency API.
There's a class called agent (under Concurrency namespace), and it's basically a state machine you derive and implement pure virtual agent::run.
Now, it is your responsibility to call agent::start, which will put it in a runnable state. You then call agent::wait*, or any of its variants, to actually execute the agent::run method.
But why do we have to call agent::done within the body? I mean, the obvious answer is that agent::wait* will wait until done is signaled or the timeout has elapsed, but...
What were the designers intending? Why not have the agent enter the done state when agent::run returns? That's what I want to know. Why do I have the option to not call done? The wait methods throw exceptions if the timeout has elapsed.
About the only reason I can see is that it would let you state you are done(), then do more work (say, cleanup) that you don't want your consumer to have to wait on.
Now, they could have done this:
private: void agent::do_run() {
run();
if (status() != agent_done)
done();
}
then have their framework call do_run() instead of run() directly (or the equivalent).
However, you'll note that you yourself can do this.
class myagent: public agent {
protected:
virtual void run() final override { /* see do_run above, except call do_run in it */ }
virtual void do_run() = 0;
};
and poof, if your do_run() fails to call done(), the wrapping function does it for you. If this second virtual function overhead is too high for you:
template<typename T>
class myagent: public agent {
private:
void call_do_run()
{
static_cast<T*>(this)->do_run();
}
protected:
virtual void run() final override { /* see do_run above, but call_do_run() */ }
};
the CRTP that lets you do compile-time dispatch. Use:
class foo: public myagent<foo>
{
public:
void do_run() { /* code */ }
};
... /shrug

Cancelling a thread running a long operation

I'm trying to work out a design predicament I have.
ClassWithLongOperation
{
Run()
{
RecrusiveOperation();
}
RecrusiveOperation()
{
/* RECURSION */
}
}
MyThread
{
ClassWithLongOperation Op1(10);
Op1.Run(); // Takes several minutes.
ClassWithLongOperation Op2(20);
Op2.Run();
SomeOtherClassWithLongOperation Op3;
Op3.Run();
// Do some other stuff
}
The GUI starts MyThread, which runs for a good 5-6 minutes. I want to be able to have a big fat Cancel button on my GUI, so the user can cancel the operation.
I could create a global boolean variable bCancelled, and check if its been set in RecursiveOperation, but I want to be a good C++ & OO programmer and avoid global variables. Especially if they would have to spread across multiple files.
So how would I (following good design) safely cancel MyThread? What could I change in my setup to allow this?
I'm also using _beginthreadex to start the thread, but I could use boost if it would allow for an easier solution.
Your flag not need to be global to your entire program, but it needs to be visible to your class code. Create the flag to be a private instance member and a public function to change it to false/true. In your recursive function, test its value to verify if the task should continue. When you want, set its value to false (through the function of course) to stop the recursive calls, i.e., when the user clicks the button you call the function in the desired instance. This way you will not break any OO principle, since you have a private flag and a public member function to safely change it.
Using a global variable is actually not the worst thing in the world. Having a proliferation of unnecessary global variables leads to maintenance nightmares, but it actually sounds like a quick and easy-to-understand solution here. But if you want a clean OO solution, this is certainly possible:
EDIT My original post overlooked the fact that you want to be able to run several operations in sequence, and if any of them is cancelled, none of the remaining operations are performed. This means it's more useful to keep the bool flag inside the canceller, instead of separately in each cancellable operation; and exceptions are the nicest way to handle the actual control flow. I've also tightened up a few things (added volatile for the flag itself, made names clearer, restricted unnecessary access rights).
// A thing that can cancel another thing by setting a bool to true.
class Canceller {
public:
Canceller : cancelledFlag(false) {}
void RegisterCancellee(Cancellee const& c) {
c.RegisterCanceller(cancelledFlag);
}
void Cancel() {
cancelledFlag = true;
}
private:
volatile bool cancelledFlag;
};
class CancelButton : public Canceller {
...
// Call Cancel() from on-click event handler
...
};
class Cancellation : public std::exception {
public:
virtual const char* what() const throw() {
return "User cancelled operation";
}
};
// A thing that can be cancelled by something else.
class Cancellee {
friend class Canceller; // Give them access to RegisterCanceller()
protected:
Cancellee() : pCancelledFlag(0) {}
// Does nothing if unconnected
void CheckForCancellation() {
if (pCancelledFlag && *pCancelledFlag) throw Cancellation();
}
private:
void RegisterCanceller(volatile bool& cancelledFlag) {
pCancelledFlag = &cancelledFlag;
}
volatile bool* pCancelledFlag;
};
class Op1 : public Cancellee { // (And similarly for Op2 and Op3)
...
// Poll CheckForCancellation() inside main working loop
...
};
MyThread
{
CancelButton cancelButton("CANCEL!");
try {
ClassWithLongOperation Op1(10);
cancelButton.RegisterCancellee(Op1);
Op1.Run(); // Takes several minutes.
ClassWithLongOperation Op2(20);
cancelButton.RegisterCancellee(Op2);
Op2.Run();
SomeOtherClassWithLongOperation Op3;
cancelButton.RegisterCancellee(Op3);
Op3.Run();
} catch (Cancellation& c) {
// Maybe write to a log file
}
// Do some other stuff
}
The "double bouncing" registration allows the canceller to give access to a private flag variable.
The most important thing is to not use thread termination functions, except in very specialised cases. Why? They don't run destructors. Nor do they give the target thread any chance to "clean up".
Instead of using a global variable, add a method to ClassWithLongOperation and/or MyThread, something like cancelOperation() that will set an internal boolean variable. The appropriate class methods would then need to check the variable at appropriate moments.
You could implement a Stop() method for your ClassWithLongOperation and have the event handler for BigFatCancelButton to call this Stop() method for the current operation.
... Or add a Stop() method to the Thread class and make the work objects be aware of the threads they're running in. You may as well throw in a Stop() method for the work objects. Depending on what's more important: Stop the thread or the work object.

Clean-up code in the C++ exception's destructor

Can we use the destructor of an exception as a place to put some clean-up code?
In this manner we may allow the client to control the finalization step as opposed to RAII.
Is this a good or a bad design?
Is this a correct solution in the context of OOP and C++?
I'm currently working on an asynchronous procedure which itself starts asynchronously multiple tasks.
The pattern looks as follows:
struct IAsyncResult
{
...
virtual void EndCall() const;
}
typedef std::shared_ptr<IAsyncResult> IAsyncResultPtr;
struct IAsyncTask
{
virtual IAsyncResultPtr BeginTask() = 0;
virtual void EndTask(IAsyncResultPtr async) const = 0;
}
class CompositeTask : public IAsyncTask
{
…
}
Unfortunately I’m unable to guarantee that each subtask’s BeginTask method will not fail. So it is possible that N-1 subtasks would start successfully and the Nth fail.
In general it is vital to be sure that no background tasks are running before the client’s code finishes. But sometimes the client doesn’t care if some tasks fail.
So my current solution involves a custom exception which is thrown from the CompositeTask’s BeginAsync method in case if one task failed to start. This allows a client to control the clean-up stage:
class composite_async_exception : public std::exception
{
std::vector<IAsyncResultPtr> successfully_started_tasks;
mutable bool manage_cleanup;
public:
composite_async_exception(std::vector<IAsyncResultPtr> const& _successfully_started_tasks)
: successfully_started_tasks(_successfully_started_tasks)
, manage_cleanup(true)
{
}
virtual ~composite_async_exception() throw()
{
if(!manage_cleanup)
return;
for( auto task = successfully_started_tasks.begin(); task != successfully_started_tasks.end(); ++task)
{
task->CancelTask();
}
}
void Giveup() const throw()
{
manage_cleanup = false;
}
};
And the client uses the code as shown:
try
{
compositeTask.BeginAsync();
}
catch(composite_async_exception const& ex)
{
//prevent the exception to cancel tasks
ex.Giveup();
// some handling
}
Are there some best practices to handle such a situation?
The exception is eligible to be copied, the destructor would be called multiple times then. In your case that seem not to be a problem.
Exception handling mechanism might stop your tasks by destroying temporary exception object aborting your tasks at throw point, not at handling one.
To verify this one should read standard, which I'm too lazy to do.