State and Side Effects
State is the collection of values a program holds at a given moment. Mutation is changing that state by reassigning a variable, adding to a list, or updating a field.
A side effect is any observable change a function makes beyond returning a value, such as mutating an argument or writing a file. A function without side effects whose output depends only on its inputs is pure.
| Concept | Meaning | Risk |
|---|---|---|
| Mutation | Modifying existing data | Hard to track state |
| Aliasing | Two names, same object | Surprise modifications |
Pitfall:b = afor a list does not copy. Mutatingbalso changesabecause they share references.
The Event-Driven World
An event-driven program inverts control: you register handlers or callbacks to run when events happen, and an event loop waits and calls them. The outside world decides the order.
Handlers communicate entirely through shared state. Because order is unpredictable, mutation bugs multiply.
| Threat | Consequence | Prevention |
|---|---|---|
| Blocking | Freezes the event loop | Keep handlers short |
| Re-entrancy | State half-updated | Protect shared state |
Pitfall: Assuming handlers run in causal order. No promise is made about which event fires first.