Given
void ProcessSchedules(IEnumerable<Schedule> schedules)
{
Contract.Requires<ArgumentException>(Contract.ForAll(schedules,x => x.Date <= DateTime.Today))
foreach( var schedule in schedules )
{
// Do something with schedule
}
}
In this scenario, schedules will be enumerated twice. (Resharper gives me the warning) An alternative I do to most scenarios is to force the collection into a list at the beginning of the method, but given the nature of code contracts, no other code should precede the precondition. What's the best way to handle this?
Here are the options that I can think of in descending order of my personal preference.
Use static checking rather than run-time checking. This way it will not have to enumerate the list at all to do the check. This option has the limitation that it is extrememly expensive. I don't have access to the static checker myself, as much as I would love to. So alternatively, you could...
Change the definition of the method to work OK in the presense of future dates so that the check is unnecessary.
Like this:
void ProcessSchedules(IEnumerable<Schedule> schedules)
{
Contract.Requires<ArgumentNullException>(schedules != null);
foreach(var schedule in schedules )
{
if (schedule.Date <= DateTime.Today)
{
// Do something with schedule
}
}
}
If that doesn't make sense for your program, then you could...
Like this:
void ProcessSchedules(List<Schedule> schedules)
{
Contract.Requires<ArgumentException>(Contract.ForAll(schedules,x => x.Date <= DateTime.Today))
foreach(var schedule in schedules )
{
// Do something with schedule
}
}
You have already said that forcing it into a list would be an option, so clearly this is a finite sequence of acceptable size. There is a high probability that the caller is using a List<Schedule>
in the first place, or that there are other places where this implementation would be useful.
If you really want to keep the IEnumerable
in your signature you could...
With your original code:
void ProcessSchedules(IEnumerable<Schedule> schedules)
{
Contract.Requires<ArgumentException>(Contract.ForAll(schedules,x => x.Date <= DateTime.Today))
foreach( var schedule in schedules )
{
// Do something with schedule
}
}
I seriously don't see a problem in enumerating the list twice, and I am not even sure why Resharper would issue a warning for this.
If generating the schedules enumeration is an expensive operation, it doesn't matter, because you shouldn't normally include the contract validation in your release code anyway.
If the schedules enumeration is reading from a database, or something like that, then the contract isn't valid anyway, because the data could change between the validation and the processing. In that case it would be more correct for the method to accept a list or some other cached copy of the data that will not mutate.