Are Finite State Machines generally considered as bad design in OOP ?
I hear that a lot. And, after I had to work on a really old, undocumented piece of C++ making use of it, I tend to agree. It was a pain to debug.
what about readability/maintainability concerns?
FSMs should never be considered bad. They are far too useful, but people whom aren't accustomed to them will often consider them burdensome.
There are numerous ways to implement one with OOP. Some are uglier than others. Your low-level guys will use switch statements, jump tables or even "goto."
If you're looking for a cleaner way to do it, I'd recommend Boost's State Chart library, which is built just for implementing UML state diagrams in C++. It makes use of modern template techniques, to make things more readable. It also performs very well.
Finite state machines are a tool to achieve certain end. As any tool, they can be abused too.
They are not the most gracious of tools, but the work they are good at is about impossible to achieve by other means (and usually any other approach is then doomed to be a horrible mess thousand times worse than the machine).
The job is operating in conditions where classic wait states are forbidden.
I have to read touchscreen. To read the position, I have to exchange about 15 commands over SPI. I need good 100 readouts a second. I have to wait about 1 microsecond after each command, for respective busy flag to vanish before I can continue. There is also a number of other operations that must be attainable over the same interface, like setting contrast, changing modes, turning backlight on or off, reading temperature. If I performed while(BUSY_BIT);
for each wait, I would eat up all the CPU in matter of moments. If I did sched_yield()
or usleep(1)
, I would never attain the number of readouts I want. The only way is a finite state machine.
But there are ways to make the finite state machine play nice too. Hide the machine behind the scenes and give the developers functions to work with.
My job experience so far was dominated by 2 systems based on 3 different finite state machines.
The code would be twice as simple and three times clearer if written structurally or sequentially. Except it would't work, or would work with abysmal performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With