Saturday, February 22, 2014

Iterators in C

Recently I have found myself implementing an Arraylist data structure in C. As I did this I contemplated how I might implement various standard OO mechanisms in C in support of this Arraylist. The most obvious mechanism to support for this data structure is the classic Iterator pattern. So I thought I talk about how iterators work in general and how they might work in C.

Iterators in supply an interface for traversing a Aggregate data structure, that is something that encapsulates 1 or more elements, in a way that decouples them from the client code. Most iterators provide a mechanism for at least four central operations, reset(), next(), isDone(), and getItem(). These functions allow for resetting the traversal to the beginning of the Collection, moving the iterator to the next element in the Collection, check to see if there are any more elements after the current element, and getting the element at the current location of iteration, respectively.

Iterators are very powerful as they provide a way to define different types of traversal over the same Collection, ways to store traversals for later, as well as many other neat tricks.

Usually when implementing an iterator in a standard OO language, you have the given Collection create some Iterator object that conforms to some Abstract Iterator interface (Or actual Interface rather than Abstract class in languages Java). In C we are not afford such luxuries as Objects.
What we could do is define the struct and members in a header file somewhere. We would set all of their values to be Function pointers. Any collection that wishes to provide an Iterator can create a struct of this type and set the pointers in it to point to static functions that are implemented internal to the Collection.

There are quite a few issues with this method however, for one it explicitly violates the intention of a static member by allowing references to them to leave the scope in which they were defined. But this is kind of how C works, Wild West Style.

I haven't finished all the implementation yet, so I can't speak to how practical this would be (I am sure that Google can tell me, but sometimes it is useful just to contemplate something.). It is an interesting task forcing OO concepts into non-OO languages.

No comments:

Post a Comment