How can I get rid of this goto?

24.09.2009 - 22:01 (11 months, 1 week, 2 days ago)

Filed under programming, TrivadisContent, C#

Help! It's late and I don't see a good way to get rid of this goto construct:

private void advanceTheTimeCursor(
  Func<DateTime> nextTime, 
  Action uponSuccessfulAdvancement)
{
  loop:
    var t = nextTime();
    if (t > reference) return;
    uponSuccessfulAdvancement();
    pastToPresentCursor = t;
  goto loop;
}

I kinda like it, but somebody said somewhere gotos are considered harmful...

Comments

Josh ( 25.09.2009 - 06:56 UTC )
I might be completely wrong but isn't:
loop:
//do something
goto loop;
The same as:
while(true)
{
//do something
}
If it is, then that should get rid of the goto statement...
Delirious master of here ( 25.09.2009 - 08:01 UTC )
Yes, that would help! The exit condition is still not featured prominently, though...
Josh ( 27.09.2009 - 22:52 UTC )
Then how about this:
var t = nextTime();
while(t < reference)
{
    t = nextTime();
    uponSuccessfulAdvancement();
    pastToPresentCursor = t;
}
Josh ( 28.09.2009 - 05:26 UTC )
Now that I think about it maybe this would be better:
var t = nextTime();
while(t < reference)
{
  uponSuccessfulAdvancement();
  pastToPresentCursor = t;
  t = nextTime();
}
previously t was getting updated once we knew that t < reference which could leave us in a state where t > reference. If you get the next time at the end of the while loop it should then behave as before where it will return when t > reference. hope that helps! :)
Le grandseigneur du le Site ( 28.09.2009 - 07:56 UTC )
Yes, that is the solution without goto (or while true). Using any kind of conditional loop in this scenario means stating the "modifying" statement twice once inside, once outside the loop. That's the price to pay. Since the modifying statement is quite brief (t = nextTime()), I suppose that should be the way to go. Cheers!

Post a comment