0

I'm a bit OCD about my code and wondered how other people structure the following sample control flow. I haven't found anything that passes my "pretty" code test.

var records = repo.GetRecords(batch:10);

while(records.Any())
{
    var processed = ProcessRecords(records);        
    repo.DeleteRecords(processed);      
    records = repo.GetRecords(batch:10);
}

Thanks

NATO24
  • 928
  • 1
  • 7
  • 15

2 Answers2

1
while (true)
{
    var records = repo.GetRecords(batch:10);

    if (!records.Any())
        break;

    var processed = ProcessRecords(records);        
    repo.DeleteRecords(processed);      
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • I normally do it the way you mentioned but I even add a delay before breaking. Would that be a bad idea? – Vaibhav Desai Apr 12 '13 at 18:23
  • @VaibhavDesai What do you mean you add a delay before breaking? – John Kugelman Apr 12 '13 at 18:24
  • Just a sleep for say 10 seconds to avoid checking again and again if there is nothing to process. I guess this would be an app specific thing. – Vaibhav Desai Apr 12 '13 at 18:31
  • 1
    This method feels like a kludge. For loops are typically used when you have a known beginning and ending. – Chuck Conway Apr 12 '13 at 18:32
  • 1
    how is this any cleaner, neater or whatever than the original? I see a `for (;;)` I'll just be wondering wtf? – Filip Apr 12 '13 at 18:37
  • @ChuckConway `for (;;)` is the way I write infinite loops. It's equivalent to `while (true)`. The difference is just a matter of style. Six of one, half a dozen of the other. – John Kugelman Apr 12 '13 at 18:39
1

Similar to @John Kugleman's above, but using while rather than for.

while (true)
{
    var records = repo.GetRecords(batch:10);

    if (!records.Any()) break;

    var processed = ProcessRecords(records);        
    repo.DeleteRecords(processed);      
}

You can also find questions like this:

Split List into Sublists with LINQ

That ask how to "chunkify" a sequence of items. That technique might or might not apply to your situation.

Assuming a Chunk extension method (similar to @TickleMeElmo's answer or Split from @JaredPar's answer), your code might look like this:

foreach (var chunk in repo.GetRecords().Chunk(10))
{
  var processed = ProcessRecords(chunk);
  repo.DeleteRecords(processed);
}

This idiom might not work that well if you already have some sort of "chunkification" built into to your repository.

Community
  • 1
  • 1
wageoghe
  • 27,390
  • 13
  • 88
  • 116