5 ms·
That's one of the reasons I love ADTs and pattern matching in systems code so much. For instance in rust where both self and Event are enums fn on_event(&mu
by monocasa 6y ago
That's one of the reasons I love ADTs and pattern matching in systems code so much.
For instance in rust where both self and Event are enums
fn on_event(&mut self, event: Event) {
*self = match (self, event) {
(State1(data), Event1(args)) => {
.... processing event1
State2(new_data)
}
// All other events in State1 are ignored
(State1(data), _) => State1(data),
(State2(data), Event1(args)) => {
.... processing event2
State3(new_dat)
}
..... pattern match the rest of the matrix
}
}
will do a great job highlighting missing transitions of the state machine's transition matrix.
- __jem 6y agoMy favorite rust state-machine-ism is consuming self by value when you transition. In combination with generics and From, this allows you to ensure that states are only ever entered into via the transitions you encode by implementing the trait, and because the previous state is totally consumed it makes the transitions super clear.
- monocasa 6y agoI started off by doing that, but ultimately didn't like it for my use cases. * It didn't seem to grant a lot of benefits over pattern matching (errors were pushed to compile time checks in both cases). * It had larger cognitive overhead since the allowed transitions were either all over the place in the source instead of in one match statement or weren't colocated with their structs. * It didn't seem nearly as good at attacking the combinatorial complexity you see in these matrices as pattern matching is.
- __jem 6y agoIt's definitely not a great fit if you have a ton of different state transitions, since the From impls add a lot of boiler plate. But I've found it perfect for situations where there's only a few very well defined transitions, like the Raft implementation suggested in the blog post I linked in parent reply.
- deleted 6y ago[deleted]
- pdimitar 6y agoI'd love to read a blog post detailing exactly how is this done.
- tangjurine 6y agoCould you explain a little more? That sounds really cool.
- __jem 6y agoHere's a good blog on the topic: https://hoverbear.org/blog/rust-state-machine-pattern/ https://hoverbear.org/blog/rust-state-machine-pattern/. The last implementation of Raft uses this pattern.
- tiew9Vii 6y agoNot Rust but I often find with ADT's + Pattern matching I end up with a state machine without even attempting to write a state machine. ADT's + pattern matching make it a very easy pattern to implement. If your language supports exhaustive pattern matching it's also a very easy way to leverage the compiler to find bugs in your logic.