I've came across recently with a dirty if-else code, so I've looked for a refactor options and found recommendation on state-machine
as an elegant replacement for dirty if-else
code.
But something is hard me to grasp: It looks that as client I have the responsibility to move the machine from one state to the other. Now, if there are 2 transitions options (depend on the result of work done in the current state) Do I need to use if-else also? If so, what the main benefit from that pattern? From my point of view the machine may do the transition automatically from the starting state
Before asking I've read the below, and it only strengthens my opinion:
Auto advancing state machine with Stateless
How to encapsulate .NET Stateless state machine
Statemachine that transitions to target state and fires transitions and states between?
In my example, I've an MarketPriceEvent
which needs to be stored in Redis. Before stored it has to pass through validation path. The validation path states are:
- Basic Validation
- Comparison
- Another comparison
- Storing
- Error auditing
The problem is that I've many decisions to make. For example: only if BasicValidation
passed successfully I'd like to to move to Comparison
. Now if Comparison
succeeded i'd like to move to Storing
, otherwise move to ErrorAuditing
.
So if we're going into code:
_machine.Configure(State.Validate).PermitIf(Trigger.Validated, State.Compare1, () => isValid);
_machine.Configure(State.Compare1).OnEntry(CompareWithResource1).
PermitIf(Trigger.Compared, State.Store, () => isValid)
.PermitIf(Trigger.Compared, State.Compare2, () => !isValid);
And in my client/wrapper code I'll write:
//Stay at Validate state
var marketPriceProcessingMachine = new MarketPriceProcessingMachine();
if (marketPriceProcessingMachine.Permitted(Trigger.Validated))
marketPriceProcessingMachine.Fire(Trigger.Validated);
//else
// ...
In short, If I need to use if-else
, What the benefit did I get from such State machine concept? If it's deterministic why it doesn't self move to the next state? If I'm wrong, What's the wrong?