11 ms·
JavaScript state machines and statecharts
- westurner 3y agoState machine: https://en.wikipedia.org/wiki/Finite-state_machine https://en.wikipedia.org/wiki/Finite-state_machine https://docs.viewflow.io/bpmn/index.html https://docs.viewflow.io/bpmn/index.html : > Unlike Finite state machine based workflow, BPMN allows parallel task execution, and suitable to model real person collaboration patterns. BPMN: Business Process Model and Notation: https://en.wikipedia.org/wiki/Business_Process_Model_and_Notation https://en.wikipedia.org/wiki/Business_Process_Model_and_Not... On the difference between the map and the territory. > - Can TLA+ find side-channels (which bypass all software memory protection features other than encryption-in-RAM)? From https://news.ycombinator.com/item?id=31617335 https://news.ycombinator.com/item?id=31617335 : >> Can there still be side channel attacks in formally verified systems? Can e.g. TLA+ help with that at all? From https://news.ycombinator.com/item?id=33563857 https://news.ycombinator.com/item?id=33563857 : > - TLA+ Model checker https://en.wikipedia.org/wiki/TLA%2B#Model_checker https://en.wikipedia.org/wiki/TLA%2B#Model_checker : >> The TLC model checker builds a finite state model of TLA+ specifications for checking invariance properties
- komali2 3y agoI recently had a conversation about joining a startup with a really interesting, but complicated, product mostly actualized in a complex JavaScript spa (react). They wanted a more senior engineer to join so as to help untangle some of the complications and lead the juniors (that built the thing already? Unclear) out of some kind of rats nest they'd been coded into. I never saw the code so I'm not exactly sure what this meant. Anyway the founder asked me to look into this xstate platform before our call and asked a lot of questions about my understanding of state machines. The founder had this idea that if the team built out a bunch of state charts using this product and like, diagrammed their entire app, that was their ticket out of whatever sticky situation they were in. I was pretty skeptical at the time and remain so now. This seems like an interesting analysis method, and implementing SPAs in a state machine way (each component being a state machine) is alright I guess, but, especially for a startup, building out these charts feels like a waste of time. To me it seems like fielding early customer feedback and driving features is more important. My guess is that the engineers had a pretty good idea what was going on but were struggling to explain it in a way the founder understood, or maybe were slowing down on feature implementation, I don't really know, but I'm always so skeptical of slapping more tools and plugins and diagrams onto the stack of things the engineering team has to worry about. I'm curious if anyone has been on a team in a situation as I've vaguely described here and found state charts useful in getting them out of a hole?
- robopsychology 3y agoIf you follow a proper state machine design then it should be exportable as a diagram, I’d assume. I worked in a team that modeled with state machines and it was useful but I was the most junior member at 7 years experience
- eyelidlessness 3y agoProducing visual charts is kind of just a neat side effect of state machines. The real benefit is formalizing a process’s possible state flows in a generally consistent and traceable way. You don’t actually need any tool to do this, disciplined convention can accomplish the same (but a tool is a great forcing function to be sure you’re actually doing it, and a well defined static type system can be useful too).
- hutzlibu 3y agoI agree to your main point, but I think you are underestimating the usefullness of visual charts in giving easy overview for people not invested into the code, to see what is going on.
- migf 3y agoI have actually just started a process like this in a personal react project. The project uses password auth and websockets, and I was starting to get bugs around refreshing things that I couldn't easily fix. I had implemented this originally using a singleton pattern for an AuthService and a MessageBus for the websockets. I created those at app start and put them in a React Context. Converting things to xstate is working great, but it's nearly a rewrite. The approach I had stashed state in a couple different places and had a bunch of callbacks passed around. Now all that state is just in the state machine's context, and what were methods turn into pure functions. One thing that's a little non obvious is that if you have async operations (ie waiting for a new token) you probably want a state for waiting for that, where you invoke the async method followed by transitions on success and failure. The docs reflect this, but it's not narratively obvious. Anyway, liking it so far. Changing to a state machine is going to hurt if your code already sucks.
- aarpmcgee 3y agoAll I know is, the parts of my app that I implemented with state machines are by far the most stable, least buggy. fwiw, if xstate feels like too much for whatever reason, https://thisrobot.life https://thisrobot.life has seemed like a decent alternative to me.
- hashbig 3y agoSame here, state machines are fantastic to extend state driven UIs without worrying about breaking existing behavior. If you find XState too verbose consider using a DSL that compiles down to JS like Lucy: https://lucylang.org https://lucylang.org
- simlevesque 3y agoIt seems like both of your links are projects from the same person, he must be passionated about state machines.
- MatthewPhillips 3y agoI am, thank you. : - )
- aarpmcgee 3y agoThanks for all your valuable contributions to this space! I have been curious if development on Lucy is continuing? I might like to port some of my existing machines over if the project is still active.
- _heimdall 3y agoCan confirm.
- astrange 3y agohttp://www.colm.net/open-source/ragel/ http://www.colm.net/open-source/ragel/ is good if you're more on the C side. hmm… seaside… C side… has this been used for anything yet?
- rektide 3y agoWhat's the quote about "those who do not do X end up with an unintensional half built reimplementation of X"? My personal recent example is a wizard in a web app built as a single major component, with some subcomponents, that goes forward and backwards through 3 different major flows depending on use case. It's been somewhat tamed over time, but we still find cases where an error on step X gets us into an unrecoverable state, sometimes with actual longstanding data impact or where closing & reopening the modal doesnt get the user back on course. With a state machine, I feel, things would be far more predictable. Having some actual Computer Science in your coding can be a huge boon.
- mathgladiator 3y agoGreenspun's tenth rule? > Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp. https://en.wikipedia.org/wiki/Greenspun%27s_tenth_rule https://en.wikipedia.org/wiki/Greenspun%27s_tenth_rule
- tshaddox 3y agoI think you’re looking for this: https://en.wikipedia.org/wiki/Greenspun%27s_tenth_rule https://en.wikipedia.org/wiki/Greenspun%27s_tenth_rule > Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp.
- qdot76367 3y agoI use xstate in a major project, having moved from python's transitions library to this when the project became web focused. XState is fantastic once you get used to it, but the ramp-up is similar to a fairly complex framework. Onboarding new engineers to it can be quite a chore, especially if they're not used to thinking about different execution paradigms. That said, the ability to autogenerate visualizations of the state graph is super near, and there's so many nice utilities inside of it that make life easy once you get going.
- ramesh31 3y ago>Onboarding new engineers to it can be quite a chore, especially if they're not used to thinking about different execution paradigms. Sadly this is what I've run into as well. Having built a serious application from the ground up with XState at the core of the architecture, it's the closest thing to code nirvana I've ever reached. But getting buy-in across the org was an impossible task due to the overhead and boilerplate.
- h0l0cube 3y agoI’m wondering how this would work alongside the History API for web apps. SPAs have complicated flows, but is often good practice to use URLs for routing in case the user hits refresh, restarts the browser, shares the link etc. As long as XState can be coaxed to keep the history sane, this could be a way to make web apps less buggy, with excellent visual documentation of the expected app behaviour to boot
- z3t4 3y agoYes, you can make your web app stateless by moving the state to the query string.
- h0l0cube 3y agoYes, and also the fragment. But what I’m referring to is that the state machine needs to manage burning the stack (e.g., clicking a ‘Done’ button on wizard would take you back several pages). When the user hits back they should be able to naturally affect the state machine and also to eventually leave the page to its referrer if they go back far enough
- tlrobinson 3y agoState charts are great for the right use cases. I used XState to help build a graphical editor (think Figma) with fairly complex interactions involving mouse and keyboard events, etc. I’m curious if others have found it worthwhile for more typical web apps too. My instinct is it’s usually overkill.
- dgb23 3y agoI never used a library for this kind of thing. But simple Mealy Machines come up somewhat regularly in my UI code.
- jdougan 3y agoImplementing State Machines in Smalltalk, Trevor P. Hopkins, Technical Report UMCS-93-3-1, March 1993 [PDF] http://trevor-hopkins.com/downloads/UMCS-93-3-1.pdf http://trevor-hopkins.com/downloads/UMCS-93-3-1.pdf
- tuzemec 3y agoI've stumbled upon this post about building simple state machines [1] a while ago. I was working on a small game and it helped a lot with the "enemy' behavior. [1] - https://kentcdodds.com/blog/implementing-a-simple-state-machine-library-in-javascript https://kentcdodds.com/blog/implementing-a-simple-state-mach...
- fabianlindfors 3y agoOne quality about state machines that I find overlooked is debuggability. Limiting state updates to transitions makes it so easy to debug weird edge cases and race conditions. This upside is perhaps more relevant on the backend though where state is more long-lived, which is why I've been experimenting with a project for building backends with state machines: https://github.com/fabianlindfors/restate https://github.com/fabianlindfors/restate.
- revskill 3y agoThis is the State Design GoF pattern.
- layer8 3y agoYou mean the State GoF design pattern.
- narag 3y agoI've only used a state machine in code once. Guess what I was writing. BUT. Once a state diagram saved my team a whole lot of pain. We were translating a piece of regulation to code. There were a bunch of people directly talking to us that had a little idea (in that case, worse than no idea) of what the persistence of the real system was. The diagram made wonders: I was able to ask "is this situation the same as this? no? why?" and actually make myself understood when I said "that won't work" instead of getting in a loop. Best of all: non-technical people got really well what the diagram meant and, after a while playing with it, they liked it. Big fan.
- kkirsche 3y agoThis looks amazing. Does anyone know a good resource for creating database-backed state machines? Eg states are defined in the database
- fabianlindfors 3y agoProbably not exactly what you are thinking of but my project Restate is all about building backends using state machines by saving them and their transitions to the database: https://github.com/fabianlindfors/restate https://github.com/fabianlindfors/restate
- kkirsche 3y agoThank you for sharing! Any resource to understand how others have solved or approached this problem is valuable.
- carlbarrdahl 3y agoWould be interesting to see how good LLMs are at generating code for this. As I see it, state machines are a json serializable representation of logic. We also have json schema for representations of valid inputs. GraphQL or similar as representations for fetching data. And of course jsx for rendering views. Put all these as a Venn diagram, what are the overlaps? Can we use these constraints as a way to generate robust and consistent apps?
- psnehanshu 3y agoDoes anyone know of a beginner friendly guide to State machines? I would love to try it out.
- eatonphil 3y agoSince this thread mostly only seems to get into why state machines are great, I wanted to see what else there is on the other side. You rarely see state machines in application development (backend or frontend). And if I saw it there I'd think someone was making overcomplicating things. https://workflowengine.io/blog/why-developers-never-use-state-machines/ https://workflowengine.io/blog/why-developers-never-use-stat... On the other hand, programming in state machines makes more sense when you're dealing with network protocols like TCP or distributed systems like Raft (both the implementation of Raft and the clients of Raft are modelled as state machines). It's hard for me to explain why state machines feel like overkill/overengineering in application development but feel natural in network and distributed systems programming.
- giraffe_lady 3y agoI have seen state machines quite frequently in production code, but rarely formally defined state machines. For example something I've seen a few times is a db table with the fields "account confirmed bool" "account_deleted bool" and "account_suspended bool." There's a state machine in that app somewhere, even if they wouldn't describe it that way. I think developers having better awareness of when they're drifting into this approach and intentionally choosing it or not would be a much better situation.
- baudaux 3y agoI like state machines for modelling system/software. It could be great if it can also use the plantuml format.