Understanding State Machines in Almadar
State machines are at the heart of Almadar. In this post, we explore why we chose state machines as the foundation for application behavior.
Why State Machines?
Traditional web applications often suffer from unpredictable behavior. A button might do different things depending on hidden state, race conditions, or implicit assumptions buried in code.
State machines solve this by making every possible state explicit and every transition intentional.
Anatomy of an Almadar State Machine
Every trait in Almadar contains a state machine:
{
"name": "Toggleable",
"stateMachine": {
"initial": "off",
"states": ["off", "on"],
"transitions": [
{
"from": "off",
"event": "TOGGLE",
"to": "on",
"effects": [
["render-ui", "main", { "pattern": "toggle", "props": { "active": true }}]
]
},
{
"from": "on",
"event": "TOGGLE",
"to": "off",
"effects": [
["render-ui", "main", { "pattern": "toggle", "props": { "active": false }}]
]
}
]
}
}
Key Concepts
States
States represent the possible conditions of your entity. Each state is explicit and named.
Events
Events trigger transitions. They can come from user actions, system events, or other orbitals.
Transitions
Transitions define how your entity moves from one state to another. Each transition can have:
- Guards: Conditions that must be met
- Effects: Actions to perform (update fields, render UI, emit events)
Effects
Effects are the side-effects of a transition. Almadar supports:
set- Update an entity fieldincrement/decrement- Modify numbersrender-ui- Render a UI patternemit- Publish events to other orbitalspersist- Save to databasenavigate- Change routes
Benefits
- Predictability: You always know what state your app is in
- Testability: Test every transition independently
- Security: Guards prevent unauthorized state changes
- Debugging: State history makes bugs reproducible
Next Steps
Ready to build with state machines? Check out our Getting Started guide.
