El Mac
El Mac

Reputation: 3418

Save data in state-machine

what is the best way to save data in a state-machine-like application?

How the application works:

There are multiple states, like Loging, MainMenu, Registration, etc. There is a loop that working until the state reaches Exit.

while(currentState != States.Exit)
{
   switch (currentState)
   { 
      case Login:
            // Do everything needed for the login, including showing the Login-Window.
            LoginProcess();
         break;
      case MainMenu:
            MainMenuProcess();
         break;
      // Etc...
   }
}

The problem:

I want to save data in between these processes. For example I want to have a User Object after the login containing everything that has to do with the user. There are many variables I could have to save and they are not always initialized (i.e. the User can only exist after login).

How it's done until now:

Right now there are just "public" members that can be null if the respective process has not started. They are defined in the class of the State-Machine loop. This can get messy easily.

Expectations:

I would like to have a way to do this data-saving in a clean way. Maybe even extract it from the state-machine or something similar. Maybe there is a way to restrict processes to access members they should not change?

Thanks in advance.

Upvotes: 3

Views: 999

Answers (2)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149618

Instead having every possible field for each process in the state machine, I would create small POCO objects which are in charge of passing information to each step of the state machine.

For example:

public class LoginProcessInfo
{
    private readonly string username;
    private readonly string password;

    public LoginProcessInfo(string username, string password)
    {
        this.username = username;
        this.password = password;
    }
}

Now, with each iteration of the state, pass the relevant arguments to the method. You could either create a new one each time, or pool the created object if you're simply re-using them:

while(currentState != States.Exit)
{
   switch (currentState)
   { 
      case Login:
            LoginProcess(new LoginProcessInfo(username, password));
         break;
      case MainMenu:
            MainMenuProcess();
         break;
   }
}

Upvotes: 1

3dd
3dd

Reputation: 2540

You could persist it to a database, or serialize your model into a JSON object, this object could be saved, then loaded up later and deserialized into your domain model.

You can also consider sagas, there are frameworks that support the notion of this and might help solve the problem. http://www.cs.cornell.edu/andru/cs711/2002fa/reading/sagas.pdf

Upvotes: 1

Related Questions