How I Learned to Stop Worrying and Love the State Machine
raganwald.com
raganwald.com
I absolutely fell in love with them and haven't looked back ever since I learned more about how they work. As the author explains in this post we're implicitly writing state-machines all the times in the form of code. The idea of making them explicit, rather than implicit, helps us visualize the behavior which would've otherwise been hidden in code.
I'd highly suggest to also read this paper by David Harel, the creator of statecharts, On Visual Formalisms: http://www.wisdom.weizmann.ac.il/~harel/SCANNED.PAPERS/Visua...
If you're a frontend developer checkout my post on the subject related to React and Redux specifically: https://medium.freecodecamp.org/how-to-model-the-behavior-of...
I remember that the canonical one was always the Quantum framework, but I never wanted to deal with the licensing aspect of it.
I have some important updates to announce at JSConf Iceland, including the ability to translate to/from SCXML, and an improved visualizer.
Let me know what you think!
Also played around with doing dynamic charts as the code runs, but stopped doing that as it was more novelty value than any other kind of value :)
It's LGPLv3 if you use Qt > 5.6 (LGPLv2 earlier), and 5.6 is getting old now.
Plenty of other stuff I have worked on would have benefited from this as well.
Plenty of stuff I am going to work on in the future will benefit from this.
the top few comments i find compellingly skeptical.
Because state machines are a weaker computational model they are easier to reason about, you can prove things on state machines you can't prove on a general program, you can do things like state minimization etc.
Same for me. In university you really just a get a taste of them, usually limited to one section of a design patterns course. But man, for certain cases they really make it easy to reason about complex workflows, that otherwise would be buried in generic flow control statements spread across multiple classes, or modules. In our app, there was a flaky and bug-prone area. It wasn't always like that. It started very simple but as feature grew the workflow become more complex. Anytime someone added anything related to that module it almost always broke something else, or introduce a leak that we found 3 months later. It was an area where you really had to focus whenever you made a change and even code reviews would miss it.
It took me about a week to document the implicit state machine, another week to roll my own state machine implementation tailored for that component, and one more week to refactor the code. It's been 5 years, our dev team tripled in size and it's been probably the most rock-solid module in that time. I'm not worried that some junior dev will introduce some esoteric regression issue downstream.
A common problem I see in object-oriented design is:
A wizard is a kind of player.
A warrior is a kind of player.
A staff is a kind of weapon.
A sword is a kind of weapon.
A player has a weapon.
But before we get into the details, I just want to point out that I am not really talking about anything specific to the fantasy RPG genre here. Everything in this series applies equally well to Papers and Paychecks, but wizards and warriors are more fun to write about, so there you go.
OK, great, we have five bullet points so let’s write some classes without thinking about it! What could possibly go wrong?
https://ericlippert.com/2015/04/27/wizards-and-warriors-part...
https://ericlippert.com/2015/04/30/wizards-and-warriors-part...
https://ericlippert.com/2015/05/04/wizards-and-warriors-part...
https://ericlippert.com/2015/05/07/wizards-and-warriors-part...
https://ericlippert.com/2015/05/11/wizards-and-warriors-part...
State machines are used extensively by HDL hardware design tools, and are easier to debug.
Eric Lippert is smart, I love his Stack Overflow answers.
When I'm stuck on a software design problem, pick some random part of the program and see what happens if I make it first class.
In this case, Eric takes the game rules and turns them into objects. (Essentially the Command pattern[1], which is close to my heart[2].)
You can go overboard with this, of course, but I've found time and again if it seems like I can't get my code to hang together, it's usually because I'm missing a noun — a reification of some part of my problem that I can pass around and do stuff with.
[1]: https://en.wikipedia.org/wiki/Command_pattern
[2]: http://gameprogrammingpatterns.com/command.html
PS: Another solution to Eric's initial problem with warriors, wizards, swords, and staves is to be more precise about what capability Player has. If Warriors can only wield Swords and Wizards can only wield Staves, then it's not the case that Player's Weapon field can be set with any weapon.
So one option is to make Weapon an abstract getter in Player. Then add setters and fields in Wizard and Warrior for the specific types. If all you have is a Player, you can see what their wielding, but not change it. Then, to wield something, you need to know what kind of player you're dealing with first.
Of course, that doesn't scale very well to lots and lots of business rules as in later in the series. But it works if you have a relatively small number of constraints in your subclasses — you just push them up such that the superclass API only exposes the intersection of all of the subclasses' allowed operations.
Also, since Bob is too humble to say it - http://gameprogrammingpatterns.com is an amazing architecture resource for programmers in all disciplines, not just gamedevs.
He's got another book called http://craftinginterpreters.com/ that I've been eager to check out.
On the topic of state machines, I totally agree with the observation that games are a prime example of their usefulness. I've been working on and off on a relatively simple game that uses a Lua scripting backend to implement the game logic, and over time I've been refactoring this particular part many times, slowly converging to a solution resembling an event driven state machine implemented using reactive programming techniques. It's very interesting to see how even a very simple game already forces you to either apply concepts like state machines, events, etc, or end up with horrible crappy code that is hard to debug and not fun to work on.
Basically, I'm one of those people who might unironically write `class DefaultDog implements Dog extends AbstractAnimal`.
I am suspicious any time I see inheritance in my C# code base. It's rarely needed and causes a lot of pain when used extensively. I'm looking at you Credit Note and Invoice!
Oddly Eric never mentions ECS or SoA in the series, even though it solves the problem. (He only suggests in part 5 to use a Rule Engine, instead of inheritance)
Does anyone know a good code example (preferably C# but anything similar would do) of a rules system like what he describes in the final part?
NRules is possibly what you're after, and maybe http://www.antlr.org/ to parse rules.
OO is fundamentally about messaging not abstract data types. So if you start your design from trying to determine ADTs instead of trying to work out the kinds of message conversations that need to go on you end up with mess of types.
In the wizards and warriors we see a large amount of modelling of a domain with rules. But we, even at the end, still have little idea of what messaging is going to be going on, there is a hint about attacking werewolves. But we've already made a lot of assumptions about what our first class entites are. Often what can happen is we find, while we thought we modelled it ok and even sorted out a rule based system, it still seems difficult for our objects to have conversations.
maybe what would be better is some thing that can attack other things and wizards, weapons, and warriors are all simply modelled by some composable set of stat modifiers.
Sadly when confronted with a problem, the majority of programmers can get no further than writing down lots of nouns, perhaps dozens of them, with no idea how to combine the few actually required into an object-oriented design.
OO isn't fundamentally about messaging. That is incorrectly assuming that object-orientation began with Smalltalk, Alan Kay and Dan Ingalls. Smalltalk's "messaging with objects, all the way down" approach largely ended with its popular use and the widespread adoption of Java. Java's object model is entirely based on Simula (James Gosling Sept 2017).
Technically the latter is about object instances, the former about object/class (data/domain) modelling.
(Now it’s mostly Annotation Oriented Programming, especially with Spring. Which brings its own difficulties.)
Show us some code, how would you solve it with functions and data?
data Player =
Player (Maybe Weapon) Class
data Weapon =
Sword
| Staff
| Dagger
data Class =
Warrior
| Wizard
type Error = String
mkPlayer :: Maybe Weapon -> Class -> Either Error Player
mkPlayer (Just Sword) Warrior = Right (Player (Just Sword) Warrior)
mkPlayer (Just Dagger) Warrior = Right (Player (Just Dagger) Warrior)
mkPlayer Nothing Warrior = Right (Player Nothing Warrior)
mkPlayer (Just Staff) Warrior = Left "A Warrior cannot equip a Staff"
mkPlayer (Just Staff) Wizard = Right (Player (Just Staff) Wizard)
mkPlayer (Just Dagger) Wizard = Right (Player (Just Dagger) Wizard)
mkPlayer Nothing Wizard = Right (Player Nothing Wizard)
mkPlayer (Just Sword) Wizard = Left "A Wizard cannot equip a Sword"
A player is always a defined class(wizard or warrior), but they may not have a weapon equipped. This solution is a bit wordy, but comes with the benefit that if you ever add a new weapon/class, the compiler will scream at you if you haven't handled the case for it properly.You would only export the mkPlayer function in the library and you could potentially have much fancier error handling, such as building a data structure that contains an 'invalid' player anyways (e.g. `Left (Player (Just Sword) Wizard)`) so you can custom build an error message at the call site ("A $class cannot equip a $weapon") or even completely ignore the error if that is a potential usecase (such as building an armor/weapon preview tool, where you don't care whether they can use the weapon/armor).
Modifying it is pretty easy too. Say I wanted to allow for 2handed weapons, plus offhand weapons (shields, orbs, charms, etc.) I could encode that in a data type like:
data EquippedWeapon =
TwoHanded TwoHandWeapon
| OneHanded (Maybe OneHandWeapon) (Maybe Offhand)
| Unequipped
and swap it into the Player definition: data Player =
Player EquippedWeapon Class
And now I wouldn't be able to compile until I fixed the mkPlayer function and any other place that uses a Player and is dependent upon the weapon portion of the data structure.e.g. This function wouldn't need to change
areYouAWizardHarry :: Player -> Bool
areYouAWizardHarry (Player _ Wizard) = True
areYouAWizardHarry (Player _ _) = False mkPlayer :: Maybe Weapon -> Class -> Either Error Player
mkPlayer (Just Staff) Warrior = Left "A Warrior cannot equip a Staff"
mkPlayer (Just Sword) Wizard = Left "A Wizard cannot equip a Sword"
mkPlayer weapon klass = Right (Player weapon klass)If so, is that a practicality issue, or an Haskell limitation?
But better yet, it certainly does have the big guns which you can pull out.
-- Just like before, we define `Class` and `Weapon`:
data Class = Warrior | Wizard
data Weapon = Sword | Staff | Dagger
-- The one really annoying thing is that
-- at the moment you have to use a little bit
-- of annoying boilerplate to define singletons
-- (not related to the OOP concept of singletons, by
-- the way), or use the `singletons` library. In the
-- future, with DependentHaskell, this won't be necessary:
data SWeapon (w :: Weapon) where
SSword :: SWeapon 'Sword
SStaff :: SWeapon 'Staff
SDagger :: SWeapon 'Dagger
-- Now we can define `Player`:
data Player (c :: Class) where
WizardPlayer :: AllowedToWield 'Wizard w ~ 'True => SWeapon w -> Player 'Wizard
WarriorPlayer :: AllowedToWield 'Warrior w ~ 'True => SWeapon w -> Player 'Warrior
This last part shouldn't be to difficult to understand, if you ignore the SWeapon boilerplate: Player is parameterized over the player's class, with different constructors for warriors and wizards. Each constructor has a parameter for the weapon the player is wielding, which is constrained by the type family (read: type-level function) named AllowedToWield.AllowedToWield isn't that complicated either, it's just a (type-level) function that takes a Class and a Weapon and returns a `Bool` using pattern matching:
type family AllowedToWield (c :: Class) (w :: Weapon) :: Bool where
AllowedToWield 'Wizard 'Sword = 'False
AllowedToWield 'Wizard 'Dagger = 'True
AllowedToWield 'Wizard 'Staff = 'True
AllowedToWield 'Warrior 'Sword = 'True
AllowedToWield 'Wizard 'Dagger = 'True
AllowedToWield 'Wizard 'Staff = 'False
And there it is. What do you gain from all this? Something which it is very had to get in certain other languages: compile-time type checking that there is no code that will allow a wizard to equip a sword, or a warrior to equip a staff.Once again, I want to make it clear that you absolutely don't need to do this, even in Haskell. You're absolutely allowed to write the simple code like in the parent post. But in my opinion, this is an extremely powerful and useful tool that Haskell lets you take much further than many other languages.
So long story short, the answer to your question is that it is indeed a "practicality issue", although I don't think that my code is that impracticable. It certainly is absolutely not a Haskell limitation: in fact if anything, Haskell makes it a bit too tempting to go in the other direction, and go way overboard with embedding this kind of thing in the type system.
I'm not a Haskell programmer, but I understood it. It looks like an ML language but with a lack of | and * for guards and tuples. I like your solution a lot.
The main features which allows you to code this solution in such a safe way are the Maybe and Either types. It's high time OO programmers - and OO programming languages - learn the lessons FP languages have taught us and include these constructs in the standard library. They're just so much cleaner than the usual alternatives (nullable types, checked exceptions) and there's no reason they can't be defined as small objects.
I've tried to learn rust a few times, but never with much tenacity. It's on my list because it seems to hit a good point wrt expressiveness and performance.
In oversimplified terms, Rust has objects but not classes. It skews more toward: - from a C dev's perspective: data-driven design - from a Haskell dev's perspective: typeclasses and ADTs
If anyone is curious and would like to see a practical demonstration of this data-oriented approach of modelling problems, I highly recommend this talk from Mark Bastian in Clojure/conj 2015: https://www.youtube.com/watch?v=Tb823aqgX_0
In it, he contrasts the data-oriented modelling approach with a traditional OOP approach for implementing a board game, and was able to come up with a complete implementation of the game with the former approach that was shorter than even the structural boilerplate for the OOP version.
Another related talk that I loved was Chris Granger's 2013 talk on Light Table: https://www.youtube.com/watch?v=V1Eu9vZaDYw
Where he walks through his process of building a game in ClojureScript using an Entity-Component-System architecture, which is very well suited to this data oriented modeling approach.
protocol Weapon {}
class Staff: Weapon {}
class Sword: Weapon {}
protocol Player {
associatedtype T: Weapon
var weapon: T { get set }
}
class Wizard: Player {
var weapon = Staff()
}
class Warrior: Player {
var weapon = Sword()
} trait Weapon
class Sword extends Weapon
class Staff extends Weapon
class Dagger extends Weapon
trait Player {
type T <: Weapon
}
class Wizard extends Player {
type T = Dagger | Staff
var weapon: T = null
}
class Warrior extends Player {
type T = Dagger | Sword
var weapon: T = new Sword
} class Wizard extends Player {
type T = Dagger | Staff
var weapon: T = null
}
The billion-dollar mistake in a new language? What a waste. class Weapon: pass
class Sword(Weapon): pass
class Staff(Weapon): pass
class Dagger(Weapon): pass
class Player:
weapon: Weapon
class Wizard(Player):
weapon: Optional[Union[Dagger, Staff]] = None
class Warrior(Player):
weapon: Optional[Union[Dagger, Sword]] = Sword()warrior can also use a staff
both can use daggers
class Chair: Furniture, Weapon, Firewood {}
What i would do is simply have Item (base for Weapon, Potion, etc) have a "IsUsableBy(Player p)" which returns true in the default implementation (which would be the case for the majority of items) and the objects that have special considerations check the player class themselves.
Similarly an Animal (or Entity or Organism or whatever) class would have a "OnDamage(Animal source, int damage)" that by default calls -say- "ApplyDamage(int damage)", but special animals - like the werewolves - may want to filter the result so that the damage is doubled when they are on holy ground or when the class of source is Paladin.
Also the IsUsableBy and OnDamage functions could check against Item objects in an inventory (e.g. Item could also provide a "FilterDamage" and "VetoUsageOf" so that an HolyCross can multiply all damage from Undead enemies by 0.25 but veto using any UnholyItem based class - truth be told here, you probably need a tag system for some of that stuff instead of relying on classes alone) and on an active Effect list (would also be able to do the same sort of vetoing and filtering and the Animal class could also provide a HasEffect method for use by the other classes to make decisions about - e.g. a PaperDoll might refuse to talk to you if you have the OnFireEffect :-P).
To me that sort of setup feels more natural and intuitive than the user-command-state-rule stuff mentioned in the article. You can't really generalize it in a way that applies to other things (e.g. a MagicSpell would need its own set of functions and such) but i believe that there is a thing as too much generalization.
(note that the above are when talking about the common Java/C++/C#/etc like OOP languages, in something like C i'd go with a more data and/or script driven approach...)
Granted, the author may have taken it a little far, but the sentiment is right.
int a = 1;
int b = 1;
int c = a + b;
And we have the option of writing, alternatively: class Integer { ... }
class Operation { ... }
class Expression { ... }
Or something 'meta' like that. The upside is that it's flexible, powerful, expressive to turn code into data. The downside is that it's slower, and there's a whole extra system to maintain.However, in my experience as a game developer, past a certain large size, pretty much all systems seem to want to converge to Lippert's solution. You want to be able to put the entity data and the rules into tables, and not have to edit code to change the game rules. For small games, not worth it. But for large games, and also for game engines that aspire to be generic, it makes everything a lot easier.
I also think trying to squeegee it into the language's type system is the wrong approach (for this specific problem, I mean - I'm not saying there aren't cases where doing it in the language is useful) purely because we're going to want the art team to add more monster types and player types, and to be able to change the rules for attacks and damage and soforth quickly on the fly to try out new game mechanics. We're going to want it all in data very soon, so it'd be better to just jump straight to a data-driven design.
Generally if you see mod tools for existing games (e.g. Skyrim) you'll see that the engine does have inherent support for the base classes (Weapon, Armor, etc) but it relies on data for the specific items, so what i describe above can be the engine (gameplay code) side of that.
Objects, particularly highly sophisticated objects, generally have minimal requirements that determine who can use them successfully. Requirements can be anything from strength to knowledge. At the same time people have skills (or don't have skills) and attributes which lets them use objects. Some people are more skilled than others.
Modelling this requires both the ability to ask an object "What are the minimal requirements needed for somebody to use you?" and the ability to ask a player "How skilled are you really at using this object?"
As a smell test, it doesn't make much sense to ask a sword "can I use you?" How would the sword know? But you can ask the sword, say, "how heavy are you?" It does make some sense to ask a person "can you use this sword?"
And yes, it's not clear at all that every object type corresponds to a first-class language type. You might have a Sword type... but in reality, unless the game is very sophisticated, all bladed weapons do pretty much the same thing. This is where it's useful to take a step back and focus not so much on nouns but also on verbs in our domain language. Swords, axes, ninja stars -- they are all cutting damage. Spears, knifes, polearms -- they are all stabbing damage.
Does it really? I mean, if we're talking about an actual person then sure, since a person can think about the problem and come up with a creative answer. But the object representing a person in a game? That would imply that the "person" object must know all about swords and the requirements for using each of them. How is that better than requiring the "sword" object to know about people and their capabilities?
Swords have attributes (e.g. weight). People have attributes (e.g. strength). Whether a particular person can wield a particular sword is not a question either a sword or a person can answer without introducing unnatural dependencies. It is a property of the environment in which the player and sword both exist, and IMHO is best modelled as some form of external "rule" object, or via a multiple-dispatch method (if your language supports that paradigm).
* A Sword is a type of weapon.
* A Fire Sword is a type of Sword.
* A Mace is a type of weapon.
* A Mace of Ice is a type of Mace.
* A Sword of Ice and Fire is a type of Sword.
If given
1. Player can have a Weapon
2. Sword is a Weapon
3. Wizard is a Player
The from the statement "Wizard cannot have a Sword" follows a contradiction that "Player cannot have a Sword".
The first post talks about the difficulty of getting compile time errors for Wizard wielding a Sword
The last post completely abandons the notion of statically checking anything about the Weapon assigned to a Player(beyond the most general case of is Player and is Weapon).
I don't actually have enough experience with Erlang/Elixir to know but I thought their function overloading (http://raganwald.com/2014/06/23/multiple-dispatch.html) still provides multiple dispatch with compile time checks?
The proposed Rules solution is more elegant to use(for the programmer, if not the person defining the Rules) but it does nothing(or at least very little) to help you check that the business logic is correctly encoded. Yes, you're likely going to avoid your program crashing, but that's just because you've given up on encoding the business logic entirely. At least where compile time checking is concerned.
Maybe I'm expecting too much of the type system and that's the actual lesson of the blog posts.
http://learnyousomeerlang.com/finite-state-machines
It even got a recent re-write and the new one is called gen_statem: http://erlang.org/doc/man/gen_statem.html
This new version is already is used to handle some of the TLS and SSH stuff from what I've heard. Here is TLS connection code: https://github.com/erlang/otp/blob/11cd0f1d000be5849bba2466b...
I've done them in C and Python before as well. In C I the like the table + function pointers approach when possible. Here is an example: https://stackoverflow.com/questions/133214/is-there-a-typica...
new state = old state + messageIn that particular example, I'd just like to point out how super clever it is to put `NUM_STATES` at the end of the enum in the first line. I'm fairly comfortable in C, but I never really used it with/around people who have been using it forever, so I love seeing these little tricks.
Also, it produces tons of false warnings when you try to enforce exhaustive switch-cases on enum values.
Dispatch tables are the way to go. Nested switch statements turn into a nightmare.
I'd be curious to hear anyone's thoughts/opinions on the desirability/feasibility of these, or any other suggestions. Thanks!
This is usually modeled better on backend systems (a state while waiting for a network response to arrive) but is often modeled poorly in front-end systems (a state while waiting for an animation to finish).
Operator pushes Start
Turn motor on
Motion triggers switch to ON state
Motion triggers switch to OFF state
Turn motor off
Machine changes state to RUNNING
The time between pushing Start and RUNNING is only a couple seconds, but there's a chance that something could jam, the switches could fail, or something I have no knowledge of could go wrong. Question becomes, do I now need an intermediate "In Motion" state for the six or so cases where this happens?
In the end, I decided no, because there was no other transition out of that state than the expected behaviors, so modeling the intermediate state didn't offer me any benefit[1]. Failure to get to OFF state within a certain time puts the system into a global error condition that required manual intervention to fix.
I don't have a real comment here :-) other than to back up your point that modeling isn't as obvious as it first appears to be.
[1] I would have created this intermediate state if this was a complex controller that was likely to have new rules added later. However, knowing it was a simple one-off, I'd just be giving myself extra work for no benefit if I did it now.
In the example given, I'd probably stick to a single intermediate state and let the language work as my implicit state machine for the internals.
Depends a lot on the boilerplate required to insert states though, my preferences owe a lot to the HFSM implementations I've used in the past.
A lot of people don't even realise they've made a modeling error. Then you invariably see code written to try and handle "unexpected errors".
We used this approach back at Heroku to power Heroku Postgres and follow the same to power our database as a service at Citus as well (https://www.citusdata.com/blog/2016/08/12/state-machines-to-...). The approach has scaled extremely well due to us following a few key principles (most importantly that we don't change the state of a running database, rather we failover to some new one with the new state).
However, now I'm at a loss on how to teach the junior programmers at my company how to recognize which patterns scream "turn me into a state machine!" Several booleans triggering certain code paths in several methods is a pretty sure sign. Are there more?
The words "event loop" probably mean you need a state machine.
If "time" is an input variable, you probably have a state machine.
https://www.microsoft.com/en-us/research/blog/p-programming-...
SDL is widely used in telecom and datacom systems to develop the control plane. Most tools are of the draw your code-type, which ends up being a unmanagable mess in direct contrast to what management thinks. But the tools will generate state machines that pass messages between eachother and to controlling interfaces based on states an inputs.
The point being made for SDL is that you can easily simulate the whole system and watch/test that the control plane will work as intended before the HW has been built.
I've been meaning to write a letter to the CS department of one UC school: What the hell are they teaching in CS nowadays? If presented with a situation where the user can create circular references, there's one UC school that produces graduates with high 3.8+ GPAs, virtually none of whom I've interviewed can give you an implementable description of how to detect circular references. As a general pattern, they also tend to say silly things, like that a null pointer member of a structure uses up no data. I can go on and on. It seems to me they are being taught by TAs who would also flub such points in an interview.
For all kinds of systems, where there are references input by users as data, one needs to be able to contend with this. Systems which crawl webpages have to contend with this. Parser-transformation systems need to detect these. Such detection could be useful in memory management. It's not just the ability to detect a circular reference. It's the ability to contend with problems of that type.
Furthermore, two of those UC system CS grads had eerily similar responses, consisting of, "Oh, is that a graph algorithm?" plus a literal handwave. Is there some pool of TAs somewhere that has that attitude towards graph algorithms?
It's the most powerful realizable automaton (although it's not even fully physically realizable because of the infinite tape), but people have studied far more powerful automata:
https://en.wikipedia.org/wiki/Turing_jump
https://en.wikipedia.org/wiki/Oracle_machine
https://en.wikipedia.org/wiki/Arithmetical_hierarchy
In these models the oracle is so called by analogy to prophetic oracles of antiquity, who were believed to obtain reliable information from an incomprehensible and supernatural source. :-)
> they go to the same dusty corner where so many other CS
> topics that are never used in practice lie already.
https://www.skorks.com/2011/09/why-developers-never-use-stat...If you think that's a head-scratcher, the fact that senior developers consistently do the exact same thing must really confuse you!
1) How would you describe the reason for using state machines over handling the state and transitions through if-statements and sprinklings of booleans? The best I can come up with is that it allows you to be explicit about which states exist, how they can be moved between, and what other code should execute when transitioning. It basically comes down to the architectural principle of 'cohesion': put related things nearby one another. This is pretty fuzzy until you've actually had concrete experience getting bitten by the lack of cohesion and attendant unmanageable complexity. To sum up, it's something you need to learn through experience—especially because another aspect of the problem is identifying situations where it really make sense rather than some simplistic heuristic about using state machines is better than not.
2) The way they're taught in school is generally about theory of automata, or they're used to diagram the behavior of some simple little system. Using them to control state transitions in applications is unlikely taught at all, and isn't really directly implied by the seemingly related things which are taught.
It's not just juniors. The only times I've encountered state machines in the wild are almost exclusively games and virtual machines/interpreters.
The reason, to me at least, is pretty clear. In both games and VMs, you mostly know the rules ahead of time. You have a clear picture of the opcodes you want to implement (add, mul, call, jump, etc.) or the game rules you need.
But for most development, especially with multiple stakeholders or customers and multiple developers working independently, the rules aren't known at the start. In fact, the majority of requirements are brought up months or years after the first line of code is even written. It's like the parable of the blind men and the elephant (https://en.wikipedia.org/wiki/Blind_men_and_an_elephant). Each person, working separately, has a different idea of what this thing is that you're creating. Communication being an incredibly difficult thing, the requirements are never fully rendered coherent by the entire team at the moment where it would benefit them most (i.e. the beginning).
As taught in school, State Machines are formalisms that fit well when everything can be formally specified. As I have learnt, State Machines in programming help to reorganize things that have evolved haphazardly.
Very often a program has only one or very few meaningful state machines, and pretty much always they are "global", i.e. there is only one of its kind in a process.
Just use global state, it has the best possible syntax for OOP :-)
But having also blogged for a while... There are no good examples that are complex enough to be realistic and yet simple enough that we can concentrate on the programming principle and not be distracted by the thing being modelled :-D
Now as to one or two state machines... This has not been my experience. I have worked on some systems that had dozens of state machines, nearly every domain model was a state machine of some kind.
This example is very reductive. In a rich and constantly changing domain like banking using a state machine to model core entities like an Account almost always ends in disaster. It simply doesn't work because businesses are complex and ever-changing. Virtually every time I've seen a 'STATE' property in a core entity, especially if it's a public property, it has evolved over time to become a horrendous thing that nobody really understands but it is now integrated throughout so many codebases that people have no choice but to continue supporting it. Ugh.
The real point here is that state machines are mathematical, highly specified constructs. They do not change well. If you are working on a protocol that can be specified precisely, sure use a state machine. If you're working on a business entity think long and hard about whether these requirements are truly fundamental and will never change. And if you really do think you have a state machine at least don't make it public.
http://www.di.unipi.it/~boerger/Papers/Methodology/BcsFacs07...
Microsoft even had a gool, AsmL, for this method. TLA's PlusCal specs look similar to some Ive seen in ASM's, too.
The idea is to capture the useful properties of state machines without being constrained to enumerable states.
I’m currently working on a program to edit these machines visually.
This seems a lot like the expression problem [1]. There are no perfect solutions. A problem can be split along multiple dimensions, but not all at once, or at least not as code saved in a text file.
Whether you split the problem first by method or by state, you will have code that's located far away from closely related code.
1. Can simultaneous actions hurt here?
2. Would a database transactions work instead?
Iff the answer is "yes" to the first and "no" to the second then consider state machines. Make sure the answer to #1 is really "yes" though. For example, things like animations consider libraries like Ember Concurrency which give you fine grain control over queuing and restarting things without the muck of a bunch of states and transitions.
In program semantics and formal verification, a state machine is a mathematical mechanism for describing an often nondeterministic discrete (software or hardware) system as a mathematical relation, →, on states, where if `s → t` (i.e., the pair <s,t> is in the relation), then a transition from state `s` to state `t` is possible. For example, both Turing machines and the lambda calculus are often naturally described as state machines. A finite state machine is just a state machine with a finite number of states.
However... A blog post with the stated aim of alerting programmers to the opportunities for refactoring a convoluted domain model into something with more structure has to start somewhere, and leave something out.
The great thing about discussions like this is that more experienced programmers such as yourself can chime in with exactly this kind of observation.
I invite you to post a link or two for others to read. I'm sure the community will appreciate it.
Now as to my request... Any particular essay or other resource about infinite state machines you'd care to suggest?
[^1]: https://pdfs.semanticscholar.org/12d9/eae1638729aeb237b5be44...
[^2]: These rules are called an operational semantics. There are other ways of giving semantics to a formal system: for instance, denotational semantics exploit recursive mathematical definitions. Each way has its pros and cons.
Not only process algebras, but even the lambda calculus is naturally expressed as a state machine, where the states represent the expression, and transitions represent possible reductions (lambda calculus is nondeterministic).
But giving your classes explicit state is certainly very valuable. I even wrote a tool that would take an ASCII-art diagram of a PN embedded in the comments of a class, and generate the state definitions and methods within the class.
``` def handle(%{state: "open", balance: balance},%Deposit{amount: amount}) do {:ok, %{state: "open", balance: (balance + amount)}} end
def handle(%{state: "closed"}, %Deposit{}) do {:error, "invalid action: account closed"} end
```
Every state/event pairing is explicitly defined as a variation of the `handle` method. There are countless ways to build a state machine like this, but the basic pattern matching primitive seems to simplify this a lot.
An extension to javascript to support this has been proposed, I'm hopeful that it gets considered seriously: https://github.com/tc39/proposal-pattern-matching
I wonder how those map to "Behavior Trees" in game development?
Actual hierarchical state machines are pretty common for driving a variety of things. Probably most commonly animation but also driving game state.
My understanding of hierarchical state machines, is that they're equivalent to Context Free Languages in terms of computational power.
State machines descriptions can lie. For instance, suppose that the implementation of a state machine grows hair that is not folded back into the specification. For instance, originally, the outputs of state transitions were just pure outputs. Now they are secretly fed back into the machine and give rise to additional states.
Or, originally, the state machine just consumed input events and changed state. Now, without it being clear in the diagrams and documentation, the machine can push back any number of events into the event stream to process again, including rearranged and edited versions of the events. This is just modeled as an "output" of certain transitions. Oops! (Why, it must be an output, because it's coded in some "output handler" function in the state machine implementation).
I think the only course where I explicitly designed programs using state machines was compilers (other than writing things to simulate state machines in my theory courses).
I did both EE and CS undergrad (we didn't have Computer Engineering at the time). In EE we started talking about FSMs very early on, in quite a bit of depth. In CS though, we didn't really talk about them until the Computability course in 3rd or 4th year, and even then it was in the very theoretical Finite Automata sense; applying FSMs to software design wasn't really a thing that was ever covered.
From the EE material, I started loosely applying those concepts to software design, but it wasn't until my first job in industry where I was lucky enough to be exposed to a system that was very deliberately designed as a system of FSMs.
We based the design of ours off of a pretty famous paper, whose name is entirely escaping me at the moment. Damn.
http://www.wisdom.weizmann.ac.il/~harel/SCANNED.PAPERS/Visua...
I'm curious to know what famous paper it is so that I can go and read it!
I emailed the mentor who first introduced me to it to see if he remembers what it was called. Watch this space!
> Another in the series "Show HN what is it that people
> actually learn in their first two years of undegrad CS"
This is my entire technical blogging output from 2004-2018. Combinatorial logic, surreal numbers, function-oriented programming, everything.Thankfully I enjoyed screwing around with game programming, and picked up Matt Buckland's Programming Game AI by Example[1]. I've used essentially the same FSM design described there over and over in my career.
There's CS and there are coding jobs. And sometimes they don't overlap...
So there's learning about state machines in that context and then there's learning about state machines by actually building them in complex pieces of software, or replacing spaghetti code with FSMs. That's when I personally realized how valuable they are.
That is something I never learned in school - and something I learned throughout a career of experimenting, making mistakes, reading from books like http://gameprogrammingpatterns.com, learning from peers, and reading articles like this.
Finite state machines as used to accomplish practical computing tasks other than grammar recognition were something I didn't see at all in undergrad CS (with the very slight exception of networking where we did see a state diagram for TCP).
(Also, I did my CS undergrad at UC Berkeley and I don't recall ever studying state machines. All the useful engineering bits and design patterns I picked up after getting my first job.)
I first started to really learn about finite state machines (FSMs) during compiler class. The parser in a compiler for example is a FSM. Tools like Bison generates FSMs based on state rules. And in general as programmers we write code to parse stuff all the time. So how can FSMs be unknown? I'm a bit baffled.
It was amazing the amount of features we could push out with great stability and scalability using this middleware. We build huge systems that just ran like clockwork and was easy to explain and reason about.
Sad part of this is that the middleware is not commercially available without buying they vendors domain specific products.
To demonstrate that this is so, I suggest that we can write a processor that converts all lets to consts where possible. I also demonstrate that this is so by asking, "What bug will const catch that our tests will not catch?"
_Immutable Data_, on the other hand, is marvellous. Immutability has nonlocal effects, and it is not something that can be trivially verified.
Anybody here have some thoughts/experience with this point of view?
I agree with your colleague somewhat. If you have a system where every domain object is inextricably linked to every other domain object, then you're going to have a state explosion trying to capture the states and transitions.
My gut reaction looking at a system like that is to start decomposing it, looking for accidental coupling that doesn't need to be there.
I guess domain-specific transitions like undo and cohesion mean similar things to state machines: requirements that don't cleanly fit into conventional state machine models.
Just because the State is a big horrid Machine is no reason to "love" it!