3
\$\begingroup\$

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 and condition_2 function from the newly split-out state computation class

  • the 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?

\$\endgroup\$
3
  • \$\begingroup\$ The excerpt that you have posted is too sketchy. Please post real (or at least realistic) code for review. \$\endgroup\$ Commented Jul 15, 2016 at 7:02
  • 1
    \$\begingroup\$ Also retitle the question to describe what your code accomplishes (see How to Ask). \$\endgroup\$ Commented Jul 15, 2016 at 7:03
  • \$\begingroup\$ @200_success It is actually functional coffeescript (minus some constant value definitions). The content of functions _condition_1 and condition_2 are removed because they contain business logic that are irrelevant to my question regarding class structure. \$\endgroup\$ Commented Jul 15, 2016 at 7:13

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.