refactoring for finite state machine