简体   繁体   中英

Improvement of State Machine implemented in scala

I am working on an implementation of a state machine in scala.

The original version is written in python, therefore I have a lot of if /else clauses in the code.

The state machine itself, has more values than the state. And the state itself depends on those values.

The states of the object will be stored in a database every time when the state changes.

To update the state, the state machine has an update method, to do the transitions.

The code example is very basic, my question is regarding the nesting of my if statement in the pattern matching approach. Is there a cleaner way in scala to achieve this? I used an immutable way of implementing it.

trait State
case object Initial extends State
case object State1 extends State
case object State2 extends State        

case class StateMachine (
                              id: Int,
                              currentState: State = Initial,
                              previousState: Option[State] = None,
                              value1: Int = 0,
                              value2: Int = 0,
                              value3: Int = 0
                            ) {



    def update(val1: Int, val2: Int, val3: Int): StateMachine = {

    val newStateMachine: StateMachine = (val1, val2) match {

      case (1, 1 ) => {

        val tempVal3 = val1 + val2

        if (val3 != 0 && val3 <= 100) {
          this.copy(currentState = State1, value1 = val1, value2 = val2, value3 = val3)
        } else if (val3 > 100) {
          this.copy(currentState = State2,value1 = val1, value2 = val2, value3 = val3 - tempVal3)
        }
        else {
          this.copy(value3 = tempVal3)
        }
      }

      case (2, _) if (val3 != 0 && val3 <= 100) => {
        if (val3 != 0 && val3 <= 50) {
          this.copy(currentState = State1, value1 = val1, value2 = val2, value3 = val3)
        }
        else {
          this.copy(value3 = 0)
        }
      }

      case _ => this
    }

    newStateMachine
  }
}

Programming a full feldged State Machine is a hard task and from what I read in your question, there is already a Scala Framework does exactly what you want

Akka Finite State Machine ( FSM )

I strongly advice to check it.

Naturally what you will read there snippets about a Hello World, if you want to see how a full fledged solution should look like, I wrote blogs Akka FSM Implementation Example , Model Driven Finite State Machine about it you can find the implementation details there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM