Different approach to implement state machine
In this article, let’s begin with implementing a state machine. There are different approaches.
Nested switch approach
we also explored this approach in the previous exercise.
This approach uses nested switch statements or if-else conditions to handle different states and inputs. Each switch statement corresponds to a specific state, and the cases inside the switch represent the possible inputs and their associated actions.
The advantage of this approach is its simplicity and readability. It is easy to understand the flow of the state machine by examining the nested switches. However, this approach can become unwieldy and hard to maintain as the number of states and inputs grows.
State table approach
This is an excellent approach, and this approach is mentioned in the book ‘Practical UML Statecharts in C/C++’ written by Miro Samek.
In this approach, you use a data structure (usually a table or matrix) to define the transitions between states. The table represents the current state, the input, and the next state. Each row in the table corresponds to a specific state, and the columns represent the inputs that can trigger state transitions.
The advantage of this approach is its simplicity and ease of understanding. However, it may become less scalable and maintainable as the number of states and inputs increases.
State Handler Approach
In this approach, you define individual state handlers or classes that encapsulate the behavior associated with each state. Each handler is responsible for processing inputs and transitioning to the next state.
A state handler approach is based on function pointers. The pointers to the state handlers. Each state will have its own handler, and that handler itself is considered as a State. The State handler approach is actually based on the usage of function pointers. So, we will also learn the use-case of function pointers in the State handler approach.
The advantage of this approach is its modularity and maintainability. It allows you to separate the logic for each state into distinct units. However, managing the transitions and ensuring correct coordination between the handlers can become complex in larger systems.
Each approach has its own strengths and weaknesses, and the choice depends on the specific requirements and complexity of your system. It’s worth noting that there are also other variations and hybrid approaches that combine elements from these three approaches or utilize different design patterns.
First, we will explore the Nested switch approach and then the State handler approach with the same application and then the State table approach.
FastBit Embedded Brain Academy Courses
click here: https://fastbitlab.com/course1