Sunday, January 29, 2006
Know why and proper examples
"Know why" is difficult to achieve. One of the reasons is that books, papers and trainers often provide toy examples, from which the reader / student can easily learn how, but not why. They then move to other subjects, because many people just don't care enough to learn the why part.
Consider the concept of iterator in C# 2.0. It's bad enough that they used the wrong name: "iterator" is a widely known concept in C++, and it's even a pattern in the GoF book, and what we usually mean by iterator is much closer to what is called an enumerator in C# than by iterator. Still, their concept is quite cool. However, they completely waste it in almost every example I've seen. They invariably start by repeating the "C# Version 2.0 Specification": Generally, enumerators are difficult to implement, but the task is significantly simplified with iterators. Then they provide a trivial example (a stack iterator, or a constant list iterator), where writing the enumerator would have been trivial as well.
The true power of C# iterators can't be seen on toy problems. You have to step up a little, like defining a Tree class and (e.g.) a depth-first iterator. Here you'll see a significant difference in complexity between an enumerator and an iterator, and you'll understand why. The enumerator has to keep all the navigation state within its own data members, and therefore has to make that state explicit. The iterator does not need any explicit navigation state. It's all implicit in the stack. The iterator can even be made recursive, as you need to navigate a tree (you need a little bit of creativity for this: try it out!). Indeed, writing a depth-first tree iterator in C++ is not trivial, but it's extremely simple with the yield return paradigm of iterators in C#.
Try out this simple exercise, and you'll know why :-).



