[fpc-pascal] Changing iterator usage pattern in FCL-STL
Graeme Geldenhuys
mailinglists at geldenhuys.co.uk
Mon Nov 9 10:47:55 CET 2015
On 2015-11-08 18:38, leledumbo wrote:
> It := SomeContainer.Iterator;
> while not It.EOF do begin
> ...
> It.Next;
> end;
Not to be a stickler, but that is not an ideal interface either (in my
eyes). Not everything is a "file", so EOF (End-of-File) was really not a
good choice. eg: Iterating characters in a String, Objects in a
ObjectList etc... none relate to a "file".
Years ago I implemented a stand-alone unit containing various iterators
for my most used container types. It is Interface based, and the
Iterator design is based on Java's Iterator design - where the current
pointer is between elements. This makes it easy to use without any
confusion. So the above code can be written as:
Itr := gIteratorFactory.GetIterator(SomeContainer);
while Itr.HasNext do
begin
itm := Itr.Next;
// do something with itm
end;
No "file" related methods, no need for extra checks for the first or
last element, no need to manually free the iterator in the end. Also,
all Iterators have the same interface, no matter the container.
See the "Iterator Pattern" article I wrote for more details and actual code.
http://geldenhuys.co.uk/articles/
Regards,
- Graeme -
--
fpGUI Toolkit - a cross-platform GUI toolkit using Free Pascal
http://fpgui.sourceforge.net/
My public PGP key: http://tinyurl.com/graeme-pgp
More information about the fpc-pascal
mailing list