Tuesday, March 31, 2009
Wednesday, July 2, 2008
Externalize Business Logic from Status/Transition handling of Business Entities
- Separate Business Logic from State-Transition handling logic
- Simply Read/Write access to the State Machine via a State-Transition Matrix model.
- Easy access of exception on undefined state-transitions.
- Directed application to Event-Driven approach.
State Machine will basically provide the state/transition handling services (load/reset state machine, get next status, set new status) to the Business Service layer which have no any knowledge about the logic of maintaining statuses for its entities.
State Machine Implementation
This idea is acquired from the mathematical modal called Deterministic Finite Automation on which Most of the commonly used compilers (Lexical Analyzer) are designed.
A state machine consists of
- a set of states S
- a set of transition T
- a state s0 that is distinguished as the initial state
- a set of states F distinguish as final states
- and for each transition t1, t2 leaving state s as t1 ≠ t2
can easily be represented as a 2-dimentional matrix (2-dimentional array) in which one axis represents all possible state and the others for all possible transition, and returning resulting next state.
The following figure illustrates a sample state machine that follows above properties;
Here, how it represents above state machine in a 2-dimentional array.
int[][] stateMachine = new int[4][3];
stateMachine [STATUS_INIT][event_create] = STATUS_NEW;
stateMachine [STATUS_NEW][event_open] = STATUS_ACTIVE;
stateMachine [STATUS_ACTIVE][event_close] = STATUS_CLOSE;
stateMachine [STATUS_NEW][ event_close] = STATUS_CLOSE;
Using above state machine model, status handling services for the business service layer can be easily implemented as following.
begin
//read from configuration or database and fill the stateMachine matrix
end;
nextStatus(event:Int, currentStatus:Int) : Int
begin
return stateMachine[currentStatus][event];
end;
I found this is simple way of expressing state machine for any business model and would lead to a centralized state management mechanism.