Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
Some thoughts about your design / code (not repeating what was already said by Derek): You have chosen member _observers of class State to be a list, and member function register to append to ...
Answer
#1: Initial revision
Some thoughts about your design / code (not repeating what was already said by Derek): * You have chosen member `_observers` of class `State` to be a list, and member function `register` to append to that list. Consequently, the same observer can be registered more than once, and the order of execution is defined. This may certainly be intended - if not, you might consider to ignore attempts to register an observer a second time or even use a set to store the observers. In any case, I recommend describing the desired semantics of `register` more explicitly. * Somehow the existence of the `register` method feels a bit asymmetric anyway, since this is the only interface to make adjustments to the state machine at runtime. Everything else is statically defined at construction time, including the initial set of observers. Maybe `register` is not even necessary at all? * In your code, state transitions are triggered by what you call "actions". This nomenclature may be fine for your usage of the state machine, but it appeared a bit unusual to me: I would have expected state transitions to be triggered by "events". The `_action_map` could from my point of view also just be called "transitions". * The name of the method `enter` seems a bit unfortunate: The name does not describe very well what the method does. From looking at the comment for the function, a name like `notify_observers` would appear more natural. * The string "initial state" does not fit well for neither an action nor an event. Maybe just "init" or a special object (to avoid any conflict with user defined actions)? It would also make sense to provide this via an API rather than have this string literal directly in the client code. * There are already some error checks. There is nothing to detect unreachable states, though. Apart from the above remarks, I find the approach well suited to define certain types of small state machines. It is in fact fairly flexible due to the fact that you call observers with the action, the previous state and the new state: This allows a user to realize state-oriented reactions (Moore-machine) as well as transition-oriented reactions (Mealy-machine). Your example is nicely chosen to demonstrate the configuration and use of the state machine: The configuration of the example state machine and the client code are really easy to understand.