3

I have a Sensor state machine for which I've written Cycle() methods:

 /// <summary> /// Cycle sets the machine to follow a path from one it's current state to the next. The /// behavior of the sensor is to revert to it's default state should an invalid state be /// encountered. /// </summary> /// <returns></returns> public IState Cycle() { if(_currentState.Next.IsNullOrEmpty()) { _currentState = DefaultState.Set(); } else { _currentState = _currentState.Cycle(); } return _currentState; } public IEnumerator<IState> Cycle(Func<bool> HasWork) { while(HasWork()) { yield return Cycle(); } } 

Implementation:

 [TestMethod] public void SensorExperiment_CycleWhileFunc() { float offset = .5f; IState previousState = State.Empty; IStimulus temp = new PassiveStimulus(68f) { Offset = offset }; ISensor thermostat = new Sensor(65f, 75f, temp); int cycles = 0; // using this func to tell the machine when to turn off Func<bool> hasWork = () => { previousState = thermostat.CurrentState; // run 10 cycles6 return cycles++ < 10; }; var iterator = thermostat.Cycle(hasWork); while(iterator.MoveNext()) { Console.WriteLine("Previous State: {0}\tCurrent State: {1}", previousState.Name, iterator.Current.Name); } } 

I have read Eric Lippert's answer to an inquiry using the IEnumerator as a StateMachine. Is my implementation abusing or leveraging the use of an IEnumerator? I see my implementation as a way to provide automation of a sequence of states.

6
  • 3
    Consider that the way the state machine is generated may change in the future. Commented Jun 10, 2012 at 17:12
  • @Oded: not sure I follow. Sensor is a specialization of an abstract Machine and method are defined by appropriate interfaces. Commented Jun 10, 2012 at 17:15
  • OK. When you use yield in your code, a state machine is generated by the compiler. How this state machine works is something that may change in future versions and may break your code if it relies on how it works. Commented Jun 10, 2012 at 17:17
  • @Oded It seems to me that this code doesn't rely on any implementation details of yield. I think it's safe. Commented Jun 10, 2012 at 17:18
  • 1
    @IAbstract - Well... possibly. One hopes the MS team implementing it would test well enough to cover most bases. But people do get creative ;) Commented Jun 10, 2012 at 17:22

1 Answer 1

2

I don't think using it like this is really an abuse, after all, you treat the result most as a collection.

On the other hand, I don't see any reason why you should use iterator here. If you rewrote your code to something like the following, it should work the same.

while (hasWork()) Console.WriteLine("Previous State: {0}\tCurrent State: {1}", previousState.Name, thermostat.Cycle().Name); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.