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 {
    OPEN, CLOSED, MOVING_UP, MOVING_DOWN, STOP
}

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;
            closeDoors();
        }

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

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

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

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.
 

Advertisements

Leave a Reply

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

WordPress.com Logo

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

Google+ photo

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

Twitter picture

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

Facebook photo

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

w

Connecting to %s