TIL thinking in States
POSTED ON:
TAGS: states programming
This is a great reminder of how to approach a problem.
"Sorry, we're super-duper, mega-out of milk."
To a programmer, that's an odd statement. You're either out of milk or you're not.
- has milk
- does not have milk
There's no "super duper" state. There's no 'So out of milk there's chaos'.
Using a example from a e-commerce platform:
If the user paid, then ship it. If it's shipped, then the whole order is complete.
This function smells funny:
function isComplete() {
return isPaid() && hasShipped();
}
Why? That whole function is encompassing two states.
When we think in state machines:
State machine rules:
img source
You can ONLY move to each state after completion of the prior one.
An order can only be in one of three distinct states:
- In progress: Can add or remove items. Can't ship.
- Paid: Can't add or remove items. Can be shipped.
- Shipped: Done. No more changes accepted.
The order if finalized when hasShipped()
has occured.
So that function should be:
function isComplete() {
return hasShipped();
}
Related TILs
Tagged: states