2

I am using Statless.StateMachine and I am facing a situation where I have one trigger with two states! Let me explain, I have an application where I need to activate some buttons when a user fills out a textbox but at the same time, those buttons will be deactivated when the user clears the textbox.

What I have done is that I have created two states Waiting and Editing. On waiting, the buttons are deactivated while on editing the buttons are activated as long as the textbox is not empty. To solve this, I wrote the following code:

_machine.Configure(State.ChoiceWaiting)
    .OnEntry(() => Setup())
    .PermitIf(Trigger.Edit, State.Editing, () => CheckEditing())
    .PermitReentryIf(Trigger.Wait, () => !CheckEditing());

_machine.Configure(State.Editing)
    .OnEntry(() => Setup2())
    .PermitIf(Trigger.Wait, State.ChoiceWaiting, () => !CheckEditing())
    .PermitIf(Trigger.Edit, State.ChoiceWaiting, () => !CheckEditing())
    .PermitReentryIf(Trigger.Edit, () => CheckEditing());

Now KeyUp event of the textbox is:

private void TextBlock_KeyUp(object sender, KeyEventArgs e)
{
    _machine.Fire(Trigger.Edit);
}

the previous code is working fine, the problem appears when pressing Backspace while the textbox is empty

System.InvalidOperationException: 'Trigger 'Edit' is valid for transition from state 'ChoiceWaiting' but a guard conditions are not met. Guard descriptions: 'Function

I know that I can solve the issue by having a condition to determine which trigger to fire on KeyUp event, but I feel that defeats the purpose of State Design Pattern as I need to control the states without the mess of if-else inside the code like KeyUp (outside StateMachine as PermitIf will do the decision on its own).

Is a correct application of the state design pattern? Or is there something I have missed?

Abdulkarim Kanaan
  • 1,703
  • 4
  • 20
  • 32
  • So basically the buttons are enabeled, if `IsNullOrWhitespace()` returns false? Or if lenght is > 0? – Christopher Apr 30 '20 at 01:06
  • @Christopher, yes IsNullOrWhiteSpace will determine whether user is editing or not – Abdulkarim Kanaan Apr 30 '20 at 01:09
  • I have solved the issue by creating a true-function and passing it to `_machine.Configure(State.Editing).PermitReentryIf`. the function determines whether to enable or disable buttons while I am in the same state and returns always true. I feel this is logical like you are requesting to stay in the state; for my case is always ok yet needs to determine to activate the buttons or not. Is there a better approach – Abdulkarim Kanaan Apr 30 '20 at 01:11

0 Answers0