posted 22 years ago
Interesting Post.
In my opinion, performance wise the normal counter is fast. No doubts. However, when it comes to writing reusable/extensible code, Iterator comes into picture, and afterall thats what is OO development is all about.
consider this,
At first look, this class looks perfectly fine and also looks well encapsulated(?). It doesn't expose its private varible( as its private). Clients of this class don't know the name of the private variable(videos), as a result if the variable name is changed clients won't be affected. so, it seems like its well encapsulated. However, if we take a closer look at the code, we realize that we are returning a Vector in the getVideos() function, which goes to say that our collection is implemented as a Vector. Clients of this class know that the collection is implemented as vector and write their code such that they expect a return value of type vector. Now if the writer of this class decides to change the collection from a Vector to something else(ex: stack,queue, array ..anything for that matter), then he should be able to do so without affecting his clients(Thats what is encapsulationg afterall). However, we see that if he changes his collection type then he needs to change the return type of the getVideos(), which means his clients will be affected.
(Well, it is surely possible to return a vector even when the collection is implemented as an array/stack/queue , etc..but that is not the best way to code afterall. Why would anyone implement something as a stack/queue and convert it to vector just for returning)
Therefore, we see that we need a way in which we should have the liberty to change the type of collection we use, but at the same time make sure our clients are not affected. Well, this is where Iterators come into picture.
If we return an iterator instead of a Vector(as in the code above) then (i) our clients don't know what type of collection we are using to store our videos, which is good , because thats what is real encapsulation. (ii) we are at liberty to change our type of collection without affecting our clients code, because all collections support the interator interface.
so, in short, its not style, but a good programming practice to return an iterator, if you want your code to be extensible.
Performance..well, it surely will go down a little bit. But then everything comes with a price, and this price is sure worth the benefit it gives.
Rex