Thursday 11 July 2013

Some Thoughts on Iterator.Remove

In my last article I mentioned that Java's Itearator<>T> features a remove method that is missing in .Net's IEnumerator<T>. Such difference is a bit surprising, and at first thought it seemed to me that it made Java Iterators more powerful that .Net Enumerators. Well, after giving it a second thought, it strikes me that such remove method should not be there.

Why am I saying this? Well, first I would recommend reading this good discussion, even when it's not much related to what I'm going to discuss below. So, in principle the idea looks good, as removing while iterating is problematic, why not add such functionality to the class that already takes care of the iteration? This class has deep knowledge of the class being iterated, enough knowledge to allow it to take the necessary measures so that a removal operation does not break the iteration. So far so good, so what's the problem?

  • First of all, now the Iterator interface has 2 capabilities (responsibilities), iterating and removing while iterating, when probably some classes just need the first one, iterating. So, I would prefer 2 interfaces here, something like Iterator (that just iterates) and something like RemoveEnabledIterator.
  • You could say that if you're not happy with current Iterator, you can just create your own ReadOnlyIterator/Iterable interface and use it rather than Iterator/Iterable in those classes that don't allow the removal. There's a huge problem here, that Iterator is a fundamental class in the Java language, as Iterable-Iterator form the basis for the enhanced for loop (for : ). This means that with the current design, if you want to be able to iterate one collection with (for : ) it has to implement Iterable, so you'll have to define an Iterator, and you'll be forced to implement a remove method in it. OK, some people will say that you're not forced, as the documentation states that the remove method is an optional operation. Problem is that this "optional" thing seems a bit messy to me, it just means that you can implement it or throw an UnsupportedOperationException, which entails that consumers of an Iterator can not assume that your Iterator supports remove and they'll expect to see it cleary explained in your documentation. This question provides some good information.

So, all in all, I reckon I'm quite more happy with .Net's IEnumerable-IEnumerator pair.

No comments:

Post a Comment