I have created a class to keep track of some internal states. You can see it as a very simple implementation of a state machine
class State extends Backbone.Model
defaults:
step: 'start'
initialize: ->
@stepDefs = [
name : 'start'
,
name : STAGE_1
precondition: _.bind @_condition_1, @
,
name : STAGE_2
precondition: _.bind @_condition_2, @
,
name : 'end'
]
@steps = (step.name for step in @stepDefs)
_condition_1: ->
# test something
_condition_2: ->
# test something else
gotoNextStep: (fromStepName) ->
idx = @steps.indexOf(fromStepName)
if idx < @steps.length
step = @stepDefs[idx + 1]
if not step.precondition
return step.name
else
if step.precondition()
return step.name
return fromStepName # stay as the current status
else
return 'end'
I am not entirely happy with this code because I want this class to only hold the step definitions and the current state (step
). I think I should create another class to provide the implementation of function _condition_1
and _condition_2
. However if I break the class State
into two (One for purely keeping the state and the other for controlling state progression), I think it may introduce a circular dependency because:
State holder needs to reference the
condition_1
andcondition_2
function from the newly split-out state computation classthe state computation class needs to have a reference to an instance of the State holder class in order to update it to a new state.
Did I overthink the situation? Is the above class structure already OK?
_condition_1
andcondition_2
are removed because they contain business logic that are irrelevant to my question regarding class structure. \$\endgroup\$