by vatsachak · 3mo ago · 0 comments
That's why in crates where I need to make sure certain functions are called in order, I use a Ticket<T>, where one function returns a Ticket<Func1Done> with the output and the other has to consume it as an input.
The typestate pattern is a specialization of making only valid states representable
As a separate point, I think this is an excellent example of making invalid states unrepresentable.
Types are not the only way to encode such invariants. tests (and to a smaller extend lints and agent hooks) are other such mechanisms.
On this beat, I think people really under-appreciate the value of tests that check the structure of code to verify some general property, instead of checking the behavior of particular code paths.
At work, we have an internal system where we use a specific type to pass certain information around. It is extremely easy to construct an (empty) instance of that type wherever it is needed, but that is almost always wrong, you actually have to do the work and figure out how to get a real instance from somewhere. To make matters worse, whether the instance is empty or not doesn't matter in development, but matters a lot in production.
Because agents are lazy, they tend to construct empty instances whenever they feel like it, and there was no immediate feedback mechanism that could tell them it was wrong. It's not something you can easily encode in a type for example. I therefore build one (imperfectly, based on ruff lints), but it solved the problem entirely.
If you were to design Ikea furniture, you'd make pieces that only fit in to the total configuration the correct way.
Types provide that same phenomenon in programming imo. At the end of the day we are shoveling and playing with bytes so we need to provide handles to these processes which make sure that we can't fit a "square peg into a round hole"
pub trait ValidState {}
struct StateMachine<'a, T>
where
T: ValidState
{untyped: &'a mut UntypedStateMachine,
_marker: PhantomData<T>
}
fn reserve_right<'a>(state: StateMachine<'a, Begin>) -> StateMachine<'a, Reserved>
fn query<'a>(state: StateMachine<'a, Reserved>) -> StateMachine<'a, Queried>
fn record<'a>(state: StateMachine<'a, Queried>) -> StateMachine<'a, Recorded>
> Typestate improves code faultlessness and testability, but comes at the cost of more boilerplate code and can degrade readability.
I have noticed this in my own code. `Ticket` with an internal variable tracking the state makes using it simpler. I just have to store one object in my struct `struct MyData { ticket: Ticket }` and call `ticket` methods in the correct order.
Typestate `Ticket<T>` is not as simple. I have to wrap it in my own enum: `enum TicketState { Ticket1(Ticket<Func1Done>), Ticket2(Ticket<Func2Done>), }` to store in my struct: `struct MyData { ticket: TicketState }`. Then every time I call `ticket` methods, I must extract the correct variant value first. That degrades readability and creates extra run-time cost.
It's really not that cumbersome, it's like two extra lines of code...
The ticket approach is a neat way to handle this, but I’ve always felt that functions needing to be called in a specific order is usually a bad code smell.
I’m sure there are times it’s unavoidable or maybe even the cleanest approach, but I don’t think I’ve encountered one in my career. When are you finding you need to do this?
Can you give an example where a different design eliminates the need for the ticket pattern?
All I’m saying is that having a set of functions that must be called in a specific order is often a code smell. Forcing them to be called in the right order improves the ergonomics, but doesn’t eliminate the smell.
If there is no shared information in the ticket other than the fact that the earlier method was called, then you’re almost certainly modifying global hidden state. If you can avoid that, all the better.
If you do need to package data along with the ticket, you can just use regular structs. Which is usually better from a naming perspective anyway.
let gpu : GPU = GPU::initialize(…);
let ctx : Context = gpu.create_context(…);
The ticket pattern is just plain old structs but with a (usually unnecessary) layer of generics. let t1 : Ticket<GPU> = GPU::initialize();
let t2 : Ticket<Context> = GPU::create_context(t1);Personally, I think the main legitimate use of the ticket pattern is when dealing with hardware. In which case your global hidden state is actually the physical world and can't be eliminated.
Otherwise, I think you have a good point.
Forcing it to be done correctly through the type system is a neat trick, but better is to design it so the trick wasn’t needed in the first place.
Maybe I misunderstood something.
func1(foo_0) -> bar0
func2(foo_1, foo_2) -> bar1
func3(foo_3, foo_3) -> bar2
And you wanted to make sure that func2 and func3 can only be called after func1 has been called.
A wrapper on the output of func1 here would be awkward because then you return Wrapper<Func1Done>(bar0). But func2 does not even need a bar0 and neither does func3.
So the solution is to return (bar0, Wrapper<Func1Done>) from func1 where
struct Wrapper<T>(//cheating ())
Also, many other functions can depend on the ticket from func_1. So making the ticket separate and generic on the process is the right (imo) solution here.
On the other hand, doesnt seprating args and typestate defeat the purpose? Since they can now be constructed separately.
async fn write_buffer(buf: &mut [u8]) -> Ticket<BufferWritten>
//Best that it it's own function for readability
async fn complex_counter_logic(ctr: Arc<AtomicUsize>, ticket: Ticket<BufferWritten>) -> Ticket<ComplexCounterLogic>
//One could also place all the data in a giant struct and move that across all functions but that eventually leads to struct bloat unless we use an explicit state machine, in which case type state is better