Best practices for organizing a big hairy state machine?? #4783
-
I just migrated a big state machine from v4 to v5. It's part of the @localfirst/auth library and implements a connection protocol for authenticating communication between peers in a local-first setting. There's a class wrapping the state machine that gives it network access and a public API. This class was already an ugly beast before the migration, but at least before I had the state machine config in one file and the implementation in another. Now I've inlined the config in order to get the strong-typing benefits of the new I've spent a few hours now cleaning it up to try to turn it into something that won't cause my fellow developers to reconsider their career choices, but there doesn't seem to be any way around the fact that I now have 649 lines of code in my constructor alone. 🤡 You can take a look here, but you might need a stiff drink first. Here's a redacted summary of the ugly facts: const machine = setup({
types: {
context: {} as ConnectionContext,
events: {} as ConnectionMessage,
},
actions: {
//... 307 lines of code
},
guards: {
// ... 45 lines of code
}).createMachine({
//... 239 lines of code
}) So ... what's my question. I guess I'm wondering
Thanks!! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
This is normal! Sure, the code seems like a lot, but when you visualize it (currently requires a pro subscription): https://github.stately.ai/local-first-web/auth/blob/d2d9b3c9209f869f8c009b528c92d3fc88a38663/packages/auth/src/connection/Connection.ts#L105-L703 - it actually becomes easily understandable. I got the gist of the state machine in under 30 seconds, just looking at the diagram: |
Beta Was this translation helpful? Give feedback.
-
see also: follow-up/rephrasing in #4812 |
Beta Was this translation helpful? Give feedback.
This is normal! Sure, the code seems like a lot, but when you visualize it (currently requires a pro subscription): https://github.stately.ai/local-first-web/auth/blob/d2d9b3c9209f869f8c009b528c92d3fc88a38663/packages/auth/src/connection/Connection.ts#L105-L703 - it actually becomes easily understandable. I got the gist of the state machine in under 30 seconds, just looking at the diagram: