Reputation: 196499
I have to edit some code that has a proposedDate (as a DateTime object called minDate) and an array of blackout dates. Given a proposed Date, it tries to see if this is valid (NOT a blackout dates). If it is a blackout date, then keep checking the next day until you find a date that is not a valid checkout date. The existing code looks like this
if ( blackoutDates.Contains(minDate))
{
minDate = minDate.AddDays(1);
dateOffset = dateOffset + 1;
if ( blackoutDates.Contains(minDate))
{
minDate = minDate.AddDays(1);
dateOffset = dateOffset + 1;
if (blackoutDates.Contains(minDate))
{
minDate = minDate.AddDays(1);
dateOffset = dateOffset + 1;
}
}
}
Clearly there is a repeated pattern here and I am trying to figure out the best way to clean up this code and make it elegant.
Upvotes: 0
Views: 93
Reputation: 7136
No need for recursion. You can do this in a loop.
while(blackoutDates.Contains(minData)){
minData = minData.AddDays(1);
++dataOffset;
}
I don't know what language is this, but check if there is already a standard API for doing what you need first.
Upvotes: 4
Reputation: 59111
I wouldn't make it recursive. I would make it a while
loop:
while(blackoutDates.Contains(minDate))
{
minDate = minDate.AddDays(1);
dateOffset = dateOffset + 1;
}
Recursion can express loops, but looping constructs are usually clearer when used in the context they are designed for. They also make it a bit simpler to reach data that is outside the scope of the loop than recursion does (specifically local variables).
Upvotes: 1