Bitten by yield return
I like the simplicity of creating enumerations with iterator blocks through yield return
. Even though I regularly do it, I was bitten by a nasty bug a few weeks ago and it was entirely my own fault.
I had been working hard on my bar management system, which includes a service to book a bar stool in advance. In my initial design, a booking had to be submitted for each day. During the first user tests, the regulars complained that it was far too complicated. They wanted to book their favorite bar stool with date intervals. The solution I came up with was a helper method that created a series of bookings between two dates.
public static IEnumerable<BarStoolBooking>SubmitSeries(BarStoolBooking bookingInfo, DateTime firstDate, DateTime lastDate) { for (DateTime date = firstDate; date <= lastDate; date = date.AddDays(1)) { bookingInfo.Date = date; yield return bookingInfo.Submit(); } } |
There’s a nasty bug in there. Can you spot it? I didn’t. I was bitten by it later on, when I wrote the presentation layer.
The presentation layer for this is simple, it prints out a header, the dates and then a footer.
var bookings = BarStoolBooking.SubmitSeries(baseBooking, DateTime.Now.Date, DateTime.Now.Date.AddDays(1)); PrintHeader(bookings.First()); foreach (var b in bookings) { Debug.WriteLine(b.Date.ToShortDateString()); } PrintFooter(bookings.First()); |
I still didn’t see the catastrophic error I had made. Can you spot it?
I found out when I saw the generated order numbers.
42 is booked for Arthur Dent (ref no 1) the following dates: 2012-05-28 2012-05-29 End of dates (ref no 4)
The header uses ref no 1. The footer uses ref no 4, but they should be the same number…
The problem is the lazy evaluation of the iterator block produced with yield return
. It will be evaluated three times, although two of them only will evaluate the first object.
- When
PrintHeader(bookings.First())
is called (just the first element) - By the
foreach
statement (entire sequence) - When
PrintHeader(bookings.First()
is called (just the first element)
On each evaluation, a new booking is submitted.
I was bitten by the lazy evaluation of yield return.
The lesson learned? Never use yield return
if there are side effects (such as submitting a booking…)