Ch.6: Design Patterns: State Machines That Stay Correct
Outline
Transcript
0:00 State groups an object's behavior by its current stage. Our bug is an export that says cancelled and still awards itself a completion badge. We'll enforce the rules that stop that. It's cancelled and congratulating itself. We'll build one state machine with a small table and State objects: the same stages and allowed changes. Then we'll try a cancellation change that keeps prepared text. Imagine a caller cancelling an export. Our job has two flags, initially false. In this Python code, self means this job.
0:30 Cancel sets cancelled to true; finish sets completed to true. Yep. Call cancel, then finish, and both flags become true. The job is reporting two outcomes that our rules say should exclude each other. Finish ignores the earlier cancellation. These are explicit calls to one object in memory, with no background worker. Do those calls have to happen at the same time? No. Cancel first, finish afterward is enough. The corrected job should reject finish and remain cancelled. Its buffer, where temporary data goes, is empty; None means no output in Python.
1:03 Our full corrected sequence starts the job, cancels it, then attempts finish. That final call reports an invalid transition, meaning a change we don't allow. The result stays cancelled. Let's make those allowed changes visible before choosing how to implement them. First, the diagram gives that corrected job four states, its possible stages. Queued can start or cancel. Running can cancel or finish. Each arrow is one permitted transition. And cancelled and completed have no arrows leaving them. For this job, neither can be started again, cancelled again or finished again.
1:36 An enum names the four choices. Here the job stores cancelled. We now record one stage. Does that fix cancellation, or can finish still overwrite it? Take the unguarded finish method. It simply assigns completed, regardless of the value already there. It's a mistake to assume naming the stages enforces that diagram. Oh, right. We record a single stage, but finish still puts it in the wrong one. Yeah. Naming the stage and checking the next change are separate jobs. Where should that check live? We can put the allowed pairs in a table and consult it before changing anything.
2:11 Refactoring Guru's State guide and the other sources are linked in the description. Let's try the table first. Now the transition table records those four allowed changes. Each key pairs the current stage with an operation. Its value is the next stage. Follow the two running rows. Cancel leads to cancelled; finish leads to completed. But there isn't a row for cancelled and finish. There's our missing check. The method asks the table for that pair. What comes back when that route isn't there? None. The next lines raise an error, sending the rejection back to whoever called the method.
2:45 Raising the error ends this call before it can change the job's data. Compare the before and after cards: cancelled, empty buffer, no output. We haven't changed any of them, so there's nothing to undo for this call. What goes into the buffer on an allowed start? The job prepares header and row, two strings in its buffer. Finish then joins those strings into two output lines and empties the buffer. Running cancellation discards those prepared strings without producing output. Try finish afterward, and the lookup rejects it before either field can change.
3:16 A reviewer could ask, 'The four-row table already works. What do these extra classes buy us?' For this job, I'd ask that too. The table already enforces these rules. Consider a new request: keep prepared text on running cancellation. We'll trace the original State version first. Now the job holds a state object instead of an enum value. Here it's Running. The job holding that reference is called the context. I'm not sure where cancellation happens yet. Can you follow the call through Running and back to the job?
3:47 Read how the job handles cancel. Here self.state points to Running, its current state object. And the final self inside the parentheses, is that the job again? Yes, that argument is the same export job. That's delegation: handing the operation to another object, along with the job it needs. Then what does Running do with that job? Its cancel method clears the buffer, then returns a new Cancelled object. The job gets that returned object and stores it in its state field. We can see the assignment in the outer cancel method.
4:18 The job replaces its state reference only after Running returns. Ah, the export job hasn't changed class. It's the same object with the same fields, now pointing at Cancelled instead of Running. Exactly. The picture removes that old connection. It doesn't claim the Running object was destroyed. What stops the new state from accepting finish? Cancelled uses a default finish method on a parent class called State. That method raises the rejection instead of returning another state. Next, Cancelled inherits finish: it uses its parent's method.
4:51 Does a rejected finish still replace the job's state? No. State's finish method raises before it can return, so the job never reaches its new-state assignment. Good. The buffer and output stay unchanged too. We wrote those defaults; the pattern doesn't choose them for us. The export has finished, with its text ready. Now call start on it. What should happen to its state and output? Start is rejected, so the job stays completed and keeps its text. We test every stage and operation in that grid. And we're checking the fields afterward, rather than just catching the error?
5:26 Right. An error isn't enough if the text disappeared. The tests check that rejection leaves those fields unchanged. I'd keep those checks with either design. Let's apply that request. Consider a running job whose cancellation should keep prepared text. Queued cancellation should still produce none. Where does the change go? In the table version's cancel branch, we check whether the current stage is running before joining the prepared strings. Then we clear the buffer as before. Because queued hasn't prepared anything to keep?
5:56 Yes. In the State version, we change Running's cancel method: keep those strings as output, clear the buffer, and return Cancelled. That method already belongs to the running stage. Queued's cancel method stays as it was. Will running cancellation keep the prepared lines without allowing finish afterward? Yes. Both changed implementations end cancelled, retaining header and row as output. The buffer is empty. A later finish call still rejects, leaving that text intact. I like having the running rule beside Running's other operations.
6:26 The table needs that stage check inside its operation method. Yeah, I like that placement. For this small job, though, I think I'd still keep the table. One method changed in each design. I mean, there isn't much behavior to split up. For instance, Running's finish method joins the strings, clears that buffer and returns Completed. The changed cancel method does that work too, but returns Cancelled. Right. We'd still review those returned states if a route changes. The original cancelled export stays cancelled; the changed one can retain prepared text and still reject finish.
7:01 Those rules come from the code, not the pattern's name. Take the completed job from earlier. Its output is intact. Can cancel change it? The call is rejected. Its text survives, and the stage remains completed. Thanks for listening to Learning Podcasts.