Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

    init -> success -> red
    init -> failure -> cleanup

    red -> success -> red_yellow
    red -> failure -> cleanup

    red_yellow -> success -> green
    red_yellow -> failure -> cleanup

    green -> success -> yellow
    green -> failure -> cleanup

    yellow -> success -> red
    yellow -> failure -> cleanup

    cleanup -> done -> finish
init/red/etc are states.

success/failure/etc are events.

Each state is a function. The function red() for example, waits for 20 seconds, then returns success (assuming nothing went wrong).

To start the state machine, initializes state to "init", and enter a loop, in the loop you call the function for the current state (which makes that state actually happen and do whatever it does), and that function returns its event for whatever happen when it was run, and you then call a second function, which updates state based on the event which just occurred. Keep doing that, until you hit state "finish", then you're done.



Got it, thanks. But it seemed from your original post that you tend to write state machines a lot more than the usual engineer does, would that be correct? Would you use this in a crud rest API for example?


When writing code, the amount of structure depends on the amount of code.

More and more complex code requires more structure.

Structure takes time and effort, so we write the minimum amount of structure which is appropriate for the code (where code often grows over time, and then by that growth becomes unmanagable, and then we need more structure, which may require a rewrite to move from the existing structure to a new, fuller structure).

So with methods for organizing code, we go something like, in order of less to more structure,

. lines of code . functions . libraries . OO libraries . classes

A state machine is a form of structure, separate from how we organize code, and moderately high cost. I don't often use one, because most of the code I write doesn't need to be particularly rigorous - but for example I did write a mailing list, and that really is used, so it really did have to be correct, so I wrote out the state machine and implemented based on the state machine.

State machines also help with testing. You can keep track of which states you have tested and which events from each state you have tested.

I've never written a REST API in my life, so I can't tell you if I would use a state machine for that :-)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: