State-Based Programming

State based programming is the use of “states” to control the flow of your program. For example, in the case of an elevator, it could be moving up, moving down, stopping, closing the doors, and opening the doors. Each of these are considered a state, and what happens next is determined by the elevator’s current state.

For instance, if the elevator has just closed its doors, what are the possibilities that can happen next? It can either move up, or move down. You wouldn’t expect the elevator to stop after closing its doors. Similarly, when an elevator stops, you expect the next action to be the doors opening.

To apply this in programming, you can store its “state” in an enumerator.

public enum ElevatorState {

Now, you can simply check for the current state and dictate what will happen next, based on that state.

public class Elevator
    ElevatorState currentState;
    public Elevator(){
        currentState = ElevatorState.CLOSED;

    public void changeState(){

        if(currentState == ElevatorState.OPEN){
            currentState = ElevatorState.CLOSED;

        if(currentState == ElevatorState.CLOSED 
           && upButtonIsPressed()){
            currentState = ElevatorState.MOVING_UP;
        if(currentState == ElevatorState.CLOSED 
           && downButtonIsPressed()){
            currentState = ElevatorState.MOVING_DOWN;

        if((currentState == ElevatorState.MOVING_UP
           || currentState == ElevatorState.MOVING_DOWN)
           && reachedDestination()){
            currentState = ElevatorState.STOP;

        if(currentState == ElevatorState.STOP){
            currentState = ElevatorState.OPEN;

Of course, this is a very simple example. You would need an event handler for when you would call changeState(), or it wouldn’t work properly. But the idea is still there. You start with a state, and continuously change states over and over again. All logic/functionality depends on what your system’s current state is in.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s