The Iterable Stream

Sometimes I find myself reusing certain paradigms in code in different projects. Many of these paradigms are the standard design patterns. There is one paradigm I’m using in a project right now that I’ve noticed I’ve used in other projects before. I call this pattern the Iterable Stream.

The Pattern

Say you have a data file or even just a stream that contains multiple records. A common example of this would be a character-delimited file which has records separated by newlines.

Python makes this embarrassingly easy with its ability to iterate over the lines of a file:

In cases such as that described above, when using C#, I often expose the iterable records through a property:

This encapsulates the dirty work of producing records from the stream and allows you to do this:

Though not as fancy as Python, using C#’s yield return syntax lets you easily make a stream iterable.

An Alternative

Alternatively, instead of exposing the iterable records through a property on SomeRecordSet, you could make SomeRecordSet itself implement IEnumerable<DataRecord>. Admittedly, this is a little more complicated, but not too much:

Then you can just iterate over the records in the object, like this:

Conclusion

We’ve been using file streams here, but it should be clear that this pattern could be used for most any stream. Making use of C#’s yield return syntax or implementing the IEnumerable<T> interface can make a data stream iterable and hide the ugly details of doing so.