Could all Code ever written be improved by applying the State Machine Pattern?
I was working on a project that was a mass of horrendous awful, buggy, broken spaghetti code. I copied Martin Fowler's example State Machine code from this blog and transformed the whole heap of crap into a series of statements. Literally just a list of States, Events, Transitions and Commands.
I can't believe the transformation. The code is now clean, and works. Of course i was aware of State Machines before and have even implemented them but in the Martin Fowler example the separation of model/configuration is amazing.
This makes me think that almost everything i've ever done could have benefitted in some way from this approach. I want this functionality in every language i use. Maybe this should even be a language level feature.
Anyone think this is wrong? Or anyone have a similar experience with a different pattern?
State design pattern is used when an Object changes its behavior based on its internal state. If we have to change behavior of an object based on its state, we can have a state variable in the Object and use if-else condition block to perform different actions based on the state.
The state pattern is a behavioral software design pattern that allows an object to alter its behavior when its internal state changes. This pattern is close to the concept of finite-state machines.
A finite state machine describes a computational machine that is in exactly one state at any given time. It can change from one to another state in response to some input / trigger / event. The emphasis of the state design pattern is on encapsulation of behavior to create reusable, maintainable components (the states).
The main purpose of the state design pattern is to allow objects to change their behaviour based on the current state. The state information is determined at and can be changed at runtime, which allows behaviour to be modified dynamically, making it seem as if the object has changed classes.
Finite state machines (FSM's) and more specifically domain specific languages (DSL's) make it easier to match a problem to one specific solution domain, by describing the solution in a specialised language.
The limitations of the State Machine pattern is that it itself constitutes a programming language, but one for which you have to write your own execution, testing and debugging tools; and one which any maintainer has to learn. You have moved the complexity of your code into a complex FSM configuration. Occasionally, this is useful, but certainly not universally.
And since any von Neumann computer is itself a FSM, then certainly any program can be recast in this fashion.
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