SlideShare a Scribd company logo
1 of 36
Iterator
– A powerful but underappreciated pattern
Nitin Bhide
Chief Software Engineer
Geometric Ltd.

nitin.bhide@geometricglobal.com
Iterator – A Definition

WHAT IS AN ITERATOR ? WHAT PROBLEM DOES IT
SOLVE ?

Confidential
Iterator - Definition

In object-oriented computer programming, an
iterator is an object that enables a programmer to
traverse a container(or collection).
• http://en.wikipedia.org/wiki/Iterator

In object-oriented programming, the iterator
pattern is a design pattern in which an iterator is
used to traverse a container and access the
container's elements.
• http://en.wikipedia.org/wiki/Iterator_pattern
Confidential
Some More Info about Iterators
• Defined GoF book, as “Iterator Pattern”.
• It is a Structural Pattern

• The essence of the Iterator Pattern is to
"Provide a way to access the elements of an aggregate
object sequentially without exposing its underlying
representation.“
• The iterator pattern decouples algorithms from
containers.

Confidential
Benefits of “decoupling of algorithms and collections”
• Common ‘interface’ can be defined to access the elements of
collection.

• Algorithms can be written using this common iterator interface
• Allows us to change the ‘internal’ implementation of collection
with no change in the algorithms implementation
• Allows us to add new algorithms which work all existing
collection types.
• For example, C++ Standard Template Library provides a set of
algorithms which work on multiple collections types by using a
common ‘iterator’ interface
Confidential
Typical operations in an Iterator Interface
• CurrentElement()
• referencing one particular element in the object collection

• Next()
• modifying itself so it points to the next element

• Reset() – Optional
• Reset the current element to start element

• HasNext() or IsEnd() – Optional
• Detect if there is no element left in the collection.

Confidential
Looping with Iterator (pseudo code)

Simple for loop
• for(int i=0; i<10; ++i)
{
curval = i;
}

For loop with Iterator
• for(iterator it=iterator();
it.IsEnd()==false;
it.Next()
{
curval = it.Current();
}
Confidential
In various programming languages

ITERATOR IMPLEMENTATIONS

Confidential
Iterator Implementations – Concepts and Limitations
• Iterator as an ‘object’ allows iterator to have its own state
(i.e. its own member variables) different than the state of
collection
• Allows multiple iterator objects corresponding to same
collection
• If collection changes while ‘iteration’ is in progress, all
existing iterators can become invalid.

• Implementation of Iterator and the collection on which it
operates are usually ‘tightly coupled’
Confidential
Examples of Iterator implementations

C++

C#

• STL Containers implement their iterators
• STL algorithms are defined in terms iterators

• IEnumerable<T> and Ienumerator<T>
iterfaces define the iterators

Java

• SDK defines iterator interface
• and collections implement their iterators

SQL

• Cursor is an iterator

Confidential
EXAMPLES OF POWER OF THE ITERATORS

Confidential
LINQ – Language INtegrated Query
• Language Integrated Query (LINQ, pronounced "link") is a
Microsoft .NET Framework component that adds native
data querying capabilities to .NET languages.
• From MSDN Documentation:
In Visual Studio you can write LINQ queries in Visual Basic or C#
with SQL Server databases, XML documents, ADO.NET
Datasets, and any collection of objects that supports IEnumerable
or the generic IEnumerable<T> interface.

Essentially Power of LINQ is because of
Power of Iterators
Confidential
Reason behind Iterators Power
Simple for loop with if check

For loop with iterator

For(i=0; i<100; i++)
{
if( I % 3 == 0)
{
print I;
}
}

For(it.Reset(); it.HasNext();
it.MoveNext())
{
print it.Current;
}

For loop is has 3 responsibilities
1. Looping
2. Filtering
3. Printing the results

For loop has only two responsibilities
1. Looping
2. Printing the results

Iterators MoveNext function is
overloaded such that it returns only
numbers divisible by 3.

Responsibility of Filtering is moved to
Iterator.
Confidential
Simple For loop with LINQ
with if check

With LINQ

for(i=0; i<100; i++)
{
if( i % 3 == 0)
{
print i;
}
}

var nums = from n in
Enumerable.Range(1, 100).w
here(n % 3 == 0)
for(var i in nums)
{
print i;
}

Confidential
LINQ Providers
• LINQ to SQL/ADO.Net
• LINQ to XML
• LINQ to Amazon
• LINQ to Active Directory
• LINQ to CRM
• LINQ To Geo - Language
Integrated Query for Geospatial
Data
• LINQ to Excel
• LINQ to Flickr
• LINQ to Google
• LINQ to Indexes (LINQ and i40)
• LINQ to JSON
• LINQ to IMAP

• LINQ to NHibernate
• LINQ to LDAP
• LINQ to Lucene
• LINQ to MySQL, Oracle and
PostgreSql (DbLinq)
• LINQ to NCover
• LINQ to Opf3
• LINQ to RDF Files
• LINQ to Sharepoint
• LINQ to SimpleDB
• LINQ to Streams
• LINQ to WebQueries
• LINQ to WMI

From Links to LINQ page :
http://blogs.msdn.com/b/charlie/archive/2008/02/28/link-to-everything-a-list-of-linqproviders.aspx
Confidential
Reasons behind Power of Iterators

Iterators can act as ‘filters’ or ‘views’
• where instead of returning all elements of a
collection it can ‘filter’ the elements and return a
‘partial’ list.
• The filtering happens as ‘needed’ and an
intermediate ‘collection’ of filtered results can be
avoided.
• Different implementations of iterator can provided
different filtering criteria.
• Hence algorithms written with ‘iterators’ can work
on original collection or filtered collections. .
Confidential
Reasons behind Power of Iterators

Iterators can be polymorphic
• Hence same function can return different
results by passing different iterator to it.
• For example, in our previous example of
printing numbers divisible by 3, can be easily
changed to printing all ‘primes’ by replacing
the iterator. There is no need to change the
print function.
Confidential
Reasons behind Power of Iterators

Iterators can be combined to provide more flexibility
• For example, combine two existing iterators into a new iterator
such that it ‘chains’ the child iterators
• For example, ‘<itertools>’ module of python provides many ways
of combining iterators
• Following one liner in python efficiently returns ‘dot product’ of
two mathematical vectors
sum(imap(operator.mul, vector1, vector2)).
imap() function takes multiple iterators and calls ‘mul’ (multiply
function) with current values of those iterators.

Confidential
Reasons behind Power of Iterators

Iterators can work with ‘collection like’ objects.

• For example, we can write an iterator which
return one word at a time from an input
stream (or a text file)
• Best example is how LINQ works with
Databases or XML with exactly same
interface.
Confidential
Few More Examples of Powerful Iterators

Suppose we want to extract ‘unique words’ from
a text file.
• Since iterator can have its own state, we can write an
iterator that remembers the words it already ‘seen’ and
• if the word is already ‘seen’ ignore that word and reads the
next word from the istream.
• Such an iterator will return just the ‘unique’ words in the
istream.
• Now if you have function which takes a word iterator as
parameter and prints the words, then just by passing the
‘unqiue word iterator, we can print the unique words in the
text file.
Confidential
Laser Cutting Tool path Generation
• For one of my project, problem was to generate the
toolpath for laser cutting of sheet metal parts

• Toolpath generation had different strategies based on
various parameters and part selection logic etc etc.
• Naïve implementation, will require
• writing complicated for loops different strategies
• Parameters passed as function parameters
• Combining strategies is nearly impossible.
• Lot of duplication of boiler plate code.
• New strategy will require changes in the existing code.
Confidential
Laser Cutting Tool path Generation - Solution
• We defined a base class ToolPathIterator
• Every new toolpath creation strategy is implemented as ‘drived
class’ of this iterator.
• We also implemented iterators which derived from this base
class And also used some existing Toolpathiterators internally to
combine the strategies.

• A Factory method instantiated the necessary toolpath
iterator based on name of the strategy.
• Only Factory method depends on all concrete iterator
implementations.
• Everywhere else ToolPathIterator base class was used.
• Add a new strategy required
• (a) adding new derived class from ToolpathIterator
• (b) change in Factory Method.
Confidential
Why I don’t see many custom iterators ?

WHY ITERATORS ARE UNDERAPPRECIATED ?

Confidential
•Most probably because Iterator is a
‘really simple concept’
•and
•people have difficulty in believing
that such simple concept can have
so much power.
Confidential
Why iterators are underappreciated ?

• Difficulty in thinking traversal/iteration as ‘separate
object/responsibility’
• Difficulty in thinking ‘iterator’ as interface with multiple
possible implementations
• Writing an iterator requires defining a new class.
• This may require additional coding while writing for loop may
look simpler/quicker.

Confidential
Difficulty in ‘thinking’ traversal/iteration as ‘separate object’

• Developers are used to thinking in loops which work on
‘indices’.
• For them ‘i++’ is conceptually easier that ‘it.next()’
• I see many examples of iterating over C++ vector use indexing
operation (e.g. vec[i]) rather than using vec.begin();

• Hence creating separate class/object to keep track of
current element and moving to next element is somehow
difficult ‘leap’.
• However once you make that ‘leap’ your subsequent design may
change significantly from the past design

Confidential
‘iterator’ as interface with multiple possible implementations

• Since ‘iterator’ is a separate class/object, we can create
‘iterator’ interfaces (or base classes).

• If we write function using the ‘iterator’ interface, then we
can pass different implementations of iterators and get
different behavior.
• Different traversal algorithms (e.g. pre order, post order
traversals in trees)
• Filtering

• All this flexibility is possible, if you start thinking in terms
of ‘iterator interface and its implementations’ or a
hierarchy of iterators.
Confidential
Writing an iterator requires defining a new class
• In languages like Java, C++, writing an iterator means
adding a new class in the system.
• It required additional code than simple for loop
• Developer has to take care in defining iterator interface (e.g.
iterators that will work with STL containers).
• Developers treated it as ‘additional burden/cost’ . They could
not visualize the benefits and hence decided that separate
iterator class is probably not worth the efforts.

• However, this is changing with co-routines
implementations
• ‘yield return’ and similar keywords being introduced in the
languages like C#, Python.
Confidential
Yield Return in C#
• A Trivial Example : Writing an iterator which returns numbers divisible by
three
• Defining the Iterator using Yield Return.
IEnumberable<int> DivisibleByThree()
{
for(int i=0; i< 100; i++)
{
if(i % 3 == 0)
{
yield return i;
}
}
}

• Using the Iterator with foreach
foreach(var j=DivisibleByThree())
{
print j;
}
Confidential
TIPS FOR MAKING EFFECTIVE USE OF ITERATORS

Confidential
Use Iterators instead of ‘indexing’ in loops
• In general, loops with iterators are more efficient than
index based loops
• For example, getting element at ‘i’th Index is equivalent
to
*(Startpos + i*sizeof(element))
While getting next element from the current element is
equivalent to
*(cur_elem_pos++)
• Hence usually ‘iterators’ based loops are slightly faster.

Confidential
Never directly return a member ‘collection’ from a class
Don’t

DO

Class XYZ
{
private List<int> intlist= new List<int>();

Class XYZ
{
private List<int> intlist= new List<int>();

List<int> IntList
{
get {
return intlist;
}
}
}

IEnumberable<int> IntList
{
get {
return intlist;
}
}
}

Confidential
Loop+If : see if you can use an iterator

• If you see similar loop + if condition or similar contents of
loop at multiple places
• See if you can extract the similarities into an Iterator
• Sometime you have to create a ‘base iterator’ and override
‘MoveNext()’ implementations
• If you are using C#/Python, see if you can use ‘yield’

Confidential
Never directly return a member ‘collection’ from a class.
• It violates ‘encapsulations’
• Also all the users of your class are now ‘explicitly’ depend
on the collection (e.g List).
• Tomorrow if you want to change the List to HashSet(),
every where your class is used will potentially need to
change.
• For C#
• Define an IEnumerable as ‘get’ property. It will allow you to
change the internal collection type with almost no impact on the
external interface.

• For Java/C++
• Define an iterator for your class.
Confidential
Summary

As Developer
change your
thinking to

• Think traversal/iterator as ‘separate
class/object/responsibility’
• Think ‘iterator’ as interface with
multiple possible implementations
• Different traversal strategies/algorithms
can be implemented as different iterator
implementations.

Once you do
that, you will
find many
more uses of
Iterator

• That can simplify your code
• Make it less bug prone and more stable.
• Make it easier to enhance and maintain

Confidential
END OF PRESENTATION
The material contained in this deck represents proprietary, confidential information pertaining to products, technologies & processes from Geometric. All information
in this document is to be treated in confidence. The names and trademarks used in this document are the sole property of the respective companies and are governed/
protected by the relevant trademark and copyright laws.

© Geometric Limited | info@geometricglobal.com

|

www.geometricglobal.com

|

Confidential

More Related Content

What's hot (20)

2. python basic syntax
2. python   basic syntax2. python   basic syntax
2. python basic syntax
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
 
L11 array list
L11 array listL11 array list
L11 array list
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
Python decorators
Python decoratorsPython decorators
Python decorators
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Unit Testing with Python
Unit Testing with PythonUnit Testing with Python
Unit Testing with Python
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
 
Command line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorialCommand line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorial
 
Standard template library
Standard template libraryStandard template library
Standard template library
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method Pattern
 
Python 2 vs. Python 3
Python 2 vs. Python 3Python 2 vs. Python 3
Python 2 vs. Python 3
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 

Viewers also liked

Hashing and Hash Tables
Hashing and Hash TablesHashing and Hash Tables
Hashing and Hash Tablesadil raja
 
Universal Declarative Services
Universal Declarative ServicesUniversal Declarative Services
Universal Declarative Servicesschemouil
 
Polymorphism and Software Reuse
Polymorphism and Software ReusePolymorphism and Software Reuse
Polymorphism and Software Reuseadil raja
 
XKE - Programming Paradigms & Constructs
XKE - Programming Paradigms & ConstructsXKE - Programming Paradigms & Constructs
XKE - Programming Paradigms & ConstructsNicolas Demengel
 
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...cprogrammings
 
The Physical Layer
The Physical LayerThe Physical Layer
The Physical Layeradil raja
 
The Data Link Layer
The Data Link LayerThe Data Link Layer
The Data Link Layeradil raja
 
Classes And Methods
Classes And MethodsClasses And Methods
Classes And Methodsadil raja
 
12 couplingand cohesion-student
12 couplingand cohesion-student12 couplingand cohesion-student
12 couplingand cohesion-studentrandhirlpu
 
Data structure and algorithms in c++
Data structure and algorithms in c++Data structure and algorithms in c++
Data structure and algorithms in c++Karmjeet Chahal
 
C++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismC++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismJussi Pohjolainen
 
The Network Layer
The Network LayerThe Network Layer
The Network Layeradil raja
 

Viewers also liked (20)

Hashing and Hash Tables
Hashing and Hash TablesHashing and Hash Tables
Hashing and Hash Tables
 
Universal Declarative Services
Universal Declarative ServicesUniversal Declarative Services
Universal Declarative Services
 
Polymorphism and Software Reuse
Polymorphism and Software ReusePolymorphism and Software Reuse
Polymorphism and Software Reuse
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
C++ Inheritance
C++ InheritanceC++ Inheritance
C++ Inheritance
 
XKE - Programming Paradigms & Constructs
XKE - Programming Paradigms & ConstructsXKE - Programming Paradigms & Constructs
XKE - Programming Paradigms & Constructs
 
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
 
04 design concepts_n_principles
04 design concepts_n_principles04 design concepts_n_principles
04 design concepts_n_principles
 
Association agggregation and composition
Association agggregation and compositionAssociation agggregation and composition
Association agggregation and composition
 
The Physical Layer
The Physical LayerThe Physical Layer
The Physical Layer
 
The Data Link Layer
The Data Link LayerThe Data Link Layer
The Data Link Layer
 
Syntax part 6
Syntax part 6Syntax part 6
Syntax part 6
 
Classes And Methods
Classes And MethodsClasses And Methods
Classes And Methods
 
12 couplingand cohesion-student
12 couplingand cohesion-student12 couplingand cohesion-student
12 couplingand cohesion-student
 
Data structure and algorithms in c++
Data structure and algorithms in c++Data structure and algorithms in c++
Data structure and algorithms in c++
 
WSO2 Complex Event Processor
WSO2 Complex Event ProcessorWSO2 Complex Event Processor
WSO2 Complex Event Processor
 
C++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismC++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphism
 
Cohesion and coherence
Cohesion and coherenceCohesion and coherence
Cohesion and coherence
 
Cohesion & Coupling
Cohesion & Coupling Cohesion & Coupling
Cohesion & Coupling
 
The Network Layer
The Network LayerThe Network Layer
The Network Layer
 

Similar to Iterator - a powerful but underappreciated design pattern

New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNico Ludwig
 
Object Oriented Programming with COBOL
Object Oriented Programming with COBOLObject Oriented Programming with COBOL
Object Oriented Programming with COBOLMicro Focus
 
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptxStatic abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptxMarco Parenzan
 
JSR 335 / java 8 - update reference
JSR 335 / java 8 - update referenceJSR 335 / java 8 - update reference
JSR 335 / java 8 - update referencesandeepji_choudhary
 
NHDay Introduction to LINQ2NH
NHDay Introduction to LINQ2NHNHDay Introduction to LINQ2NH
NHDay Introduction to LINQ2NHGian Maria Ricci
 
PresentationPatterns_v2
PresentationPatterns_v2PresentationPatterns_v2
PresentationPatterns_v2Maksym Tolstik
 
Understanding LINQ in C#
Understanding LINQ in C# Understanding LINQ in C#
Understanding LINQ in C# MD. Shohag Mia
 
Hot to build continuously processing for 24/7 real-time data streaming platform?
Hot to build continuously processing for 24/7 real-time data streaming platform?Hot to build continuously processing for 24/7 real-time data streaming platform?
Hot to build continuously processing for 24/7 real-time data streaming platform?GetInData
 
C# 3.0 and LINQ Tech Talk
C# 3.0 and LINQ Tech TalkC# 3.0 and LINQ Tech Talk
C# 3.0 and LINQ Tech TalkMichael Heydt
 
Complete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itComplete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itlokeshpappaka10
 
Lucene for Solr Developers
Lucene for Solr DevelopersLucene for Solr Developers
Lucene for Solr DevelopersErik Hatcher
 
Lucene for Solr Developers
Lucene for Solr DevelopersLucene for Solr Developers
Lucene for Solr DevelopersErik Hatcher
 
OpenSAF Symposium_Python Bindings_9.21.11
OpenSAF Symposium_Python Bindings_9.21.11OpenSAF Symposium_Python Bindings_9.21.11
OpenSAF Symposium_Python Bindings_9.21.11OpenSAF Foundation
 
Introducing object oriented programming (oop)
Introducing object oriented programming (oop)Introducing object oriented programming (oop)
Introducing object oriented programming (oop)Hemlathadhevi Annadhurai
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project LambdaRahman USTA
 
The Meteor Framework
The Meteor FrameworkThe Meteor Framework
The Meteor FrameworkDamien Magoni
 
Design patterns
Design patternsDesign patterns
Design patternsAlok Guha
 

Similar to Iterator - a powerful but underappreciated design pattern (20)

New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iv
 
Object Oriented Programming with COBOL
Object Oriented Programming with COBOLObject Oriented Programming with COBOL
Object Oriented Programming with COBOL
 
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptxStatic abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
 
JSR 335 / java 8 - update reference
JSR 335 / java 8 - update referenceJSR 335 / java 8 - update reference
JSR 335 / java 8 - update reference
 
NHDay Introduction to LINQ2NH
NHDay Introduction to LINQ2NHNHDay Introduction to LINQ2NH
NHDay Introduction to LINQ2NH
 
PresentationPatterns_v2
PresentationPatterns_v2PresentationPatterns_v2
PresentationPatterns_v2
 
Android meetup
Android meetupAndroid meetup
Android meetup
 
Understanding LINQ in C#
Understanding LINQ in C# Understanding LINQ in C#
Understanding LINQ in C#
 
Linq
LinqLinq
Linq
 
Hot to build continuously processing for 24/7 real-time data streaming platform?
Hot to build continuously processing for 24/7 real-time data streaming platform?Hot to build continuously processing for 24/7 real-time data streaming platform?
Hot to build continuously processing for 24/7 real-time data streaming platform?
 
C# 3.0 and LINQ Tech Talk
C# 3.0 and LINQ Tech TalkC# 3.0 and LINQ Tech Talk
C# 3.0 and LINQ Tech Talk
 
Complete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itComplete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept it
 
Lucene for Solr Developers
Lucene for Solr DevelopersLucene for Solr Developers
Lucene for Solr Developers
 
Lucene for Solr Developers
Lucene for Solr DevelopersLucene for Solr Developers
Lucene for Solr Developers
 
OpenSAF Symposium_Python Bindings_9.21.11
OpenSAF Symposium_Python Bindings_9.21.11OpenSAF Symposium_Python Bindings_9.21.11
OpenSAF Symposium_Python Bindings_9.21.11
 
10-DesignPatterns.ppt
10-DesignPatterns.ppt10-DesignPatterns.ppt
10-DesignPatterns.ppt
 
Introducing object oriented programming (oop)
Introducing object oriented programming (oop)Introducing object oriented programming (oop)
Introducing object oriented programming (oop)
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
The Meteor Framework
The Meteor FrameworkThe Meteor Framework
The Meteor Framework
 
Design patterns
Design patternsDesign patterns
Design patterns
 

More from Nitin Bhide

2nd Techathon in Geometric - 27/28 Feb 2015
2nd Techathon in Geometric - 27/28 Feb 20152nd Techathon in Geometric - 27/28 Feb 2015
2nd Techathon in Geometric - 27/28 Feb 2015Nitin Bhide
 
Do/Doing/Done Is NOT Kanban
Do/Doing/Done Is NOT KanbanDo/Doing/Done Is NOT Kanban
Do/Doing/Done Is NOT KanbanNitin Bhide
 
Object Oriented Containers - Applying SOLID Principles to Docker/Container De...
Object Oriented Containers - Applying SOLID Principles to Docker/Container De...Object Oriented Containers - Applying SOLID Principles to Docker/Container De...
Object Oriented Containers - Applying SOLID Principles to Docker/Container De...Nitin Bhide
 
Daily Habits Of Highly Agile Developers
Daily Habits Of Highly Agile DevelopersDaily Habits Of Highly Agile Developers
Daily Habits Of Highly Agile DevelopersNitin Bhide
 
DevOps - Understanding Core Concepts
DevOps - Understanding Core ConceptsDevOps - Understanding Core Concepts
DevOps - Understanding Core ConceptsNitin Bhide
 
Collected Wisdom
Collected WisdomCollected Wisdom
Collected WisdomNitin Bhide
 
DevOps - Understanding Core Concepts (Old)
DevOps - Understanding Core Concepts (Old)DevOps - Understanding Core Concepts (Old)
DevOps - Understanding Core Concepts (Old)Nitin Bhide
 
Fundamental Principles of Software Development
Fundamental Principles of Software Development Fundamental Principles of Software Development
Fundamental Principles of Software Development Nitin Bhide
 
Agile Mindset and Its Implications - My Understanding
Agile Mindset and Its Implications - My UnderstandingAgile Mindset and Its Implications - My Understanding
Agile Mindset and Its Implications - My UnderstandingNitin Bhide
 
GUI patterns : My understanding
GUI patterns : My understandingGUI patterns : My understanding
GUI patterns : My understandingNitin Bhide
 
Code Review Checklist
Code Review ChecklistCode Review Checklist
Code Review ChecklistNitin Bhide
 
Common Sense Software Development
Common Sense Software DevelopmentCommon Sense Software Development
Common Sense Software DevelopmentNitin Bhide
 

More from Nitin Bhide (13)

2nd Techathon in Geometric - 27/28 Feb 2015
2nd Techathon in Geometric - 27/28 Feb 20152nd Techathon in Geometric - 27/28 Feb 2015
2nd Techathon in Geometric - 27/28 Feb 2015
 
Do/Doing/Done Is NOT Kanban
Do/Doing/Done Is NOT KanbanDo/Doing/Done Is NOT Kanban
Do/Doing/Done Is NOT Kanban
 
Object Oriented Containers - Applying SOLID Principles to Docker/Container De...
Object Oriented Containers - Applying SOLID Principles to Docker/Container De...Object Oriented Containers - Applying SOLID Principles to Docker/Container De...
Object Oriented Containers - Applying SOLID Principles to Docker/Container De...
 
Daily Habits Of Highly Agile Developers
Daily Habits Of Highly Agile DevelopersDaily Habits Of Highly Agile Developers
Daily Habits Of Highly Agile Developers
 
DevOps - Understanding Core Concepts
DevOps - Understanding Core ConceptsDevOps - Understanding Core Concepts
DevOps - Understanding Core Concepts
 
Collected Wisdom
Collected WisdomCollected Wisdom
Collected Wisdom
 
DevOps - Understanding Core Concepts (Old)
DevOps - Understanding Core Concepts (Old)DevOps - Understanding Core Concepts (Old)
DevOps - Understanding Core Concepts (Old)
 
Fundamental Principles of Software Development
Fundamental Principles of Software Development Fundamental Principles of Software Development
Fundamental Principles of Software Development
 
Agile Mindset and Its Implications - My Understanding
Agile Mindset and Its Implications - My UnderstandingAgile Mindset and Its Implications - My Understanding
Agile Mindset and Its Implications - My Understanding
 
GUI patterns : My understanding
GUI patterns : My understandingGUI patterns : My understanding
GUI patterns : My understanding
 
Code Review Checklist
Code Review ChecklistCode Review Checklist
Code Review Checklist
 
CSS Basics
CSS BasicsCSS Basics
CSS Basics
 
Common Sense Software Development
Common Sense Software DevelopmentCommon Sense Software Development
Common Sense Software Development
 

Recently uploaded

#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 

Recently uploaded (20)

#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 

Iterator - a powerful but underappreciated design pattern

  • 1. Iterator – A powerful but underappreciated pattern Nitin Bhide Chief Software Engineer Geometric Ltd. nitin.bhide@geometricglobal.com
  • 2. Iterator – A Definition WHAT IS AN ITERATOR ? WHAT PROBLEM DOES IT SOLVE ? Confidential
  • 3. Iterator - Definition In object-oriented computer programming, an iterator is an object that enables a programmer to traverse a container(or collection). • http://en.wikipedia.org/wiki/Iterator In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements. • http://en.wikipedia.org/wiki/Iterator_pattern Confidential
  • 4. Some More Info about Iterators • Defined GoF book, as “Iterator Pattern”. • It is a Structural Pattern • The essence of the Iterator Pattern is to "Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.“ • The iterator pattern decouples algorithms from containers. Confidential
  • 5. Benefits of “decoupling of algorithms and collections” • Common ‘interface’ can be defined to access the elements of collection. • Algorithms can be written using this common iterator interface • Allows us to change the ‘internal’ implementation of collection with no change in the algorithms implementation • Allows us to add new algorithms which work all existing collection types. • For example, C++ Standard Template Library provides a set of algorithms which work on multiple collections types by using a common ‘iterator’ interface Confidential
  • 6. Typical operations in an Iterator Interface • CurrentElement() • referencing one particular element in the object collection • Next() • modifying itself so it points to the next element • Reset() – Optional • Reset the current element to start element • HasNext() or IsEnd() – Optional • Detect if there is no element left in the collection. Confidential
  • 7. Looping with Iterator (pseudo code) Simple for loop • for(int i=0; i<10; ++i) { curval = i; } For loop with Iterator • for(iterator it=iterator(); it.IsEnd()==false; it.Next() { curval = it.Current(); } Confidential
  • 8. In various programming languages ITERATOR IMPLEMENTATIONS Confidential
  • 9. Iterator Implementations – Concepts and Limitations • Iterator as an ‘object’ allows iterator to have its own state (i.e. its own member variables) different than the state of collection • Allows multiple iterator objects corresponding to same collection • If collection changes while ‘iteration’ is in progress, all existing iterators can become invalid. • Implementation of Iterator and the collection on which it operates are usually ‘tightly coupled’ Confidential
  • 10. Examples of Iterator implementations C++ C# • STL Containers implement their iterators • STL algorithms are defined in terms iterators • IEnumerable<T> and Ienumerator<T> iterfaces define the iterators Java • SDK defines iterator interface • and collections implement their iterators SQL • Cursor is an iterator Confidential
  • 11. EXAMPLES OF POWER OF THE ITERATORS Confidential
  • 12. LINQ – Language INtegrated Query • Language Integrated Query (LINQ, pronounced "link") is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages. • From MSDN Documentation: In Visual Studio you can write LINQ queries in Visual Basic or C# with SQL Server databases, XML documents, ADO.NET Datasets, and any collection of objects that supports IEnumerable or the generic IEnumerable<T> interface. Essentially Power of LINQ is because of Power of Iterators Confidential
  • 13. Reason behind Iterators Power Simple for loop with if check For loop with iterator For(i=0; i<100; i++) { if( I % 3 == 0) { print I; } } For(it.Reset(); it.HasNext(); it.MoveNext()) { print it.Current; } For loop is has 3 responsibilities 1. Looping 2. Filtering 3. Printing the results For loop has only two responsibilities 1. Looping 2. Printing the results Iterators MoveNext function is overloaded such that it returns only numbers divisible by 3. Responsibility of Filtering is moved to Iterator. Confidential
  • 14. Simple For loop with LINQ with if check With LINQ for(i=0; i<100; i++) { if( i % 3 == 0) { print i; } } var nums = from n in Enumerable.Range(1, 100).w here(n % 3 == 0) for(var i in nums) { print i; } Confidential
  • 15. LINQ Providers • LINQ to SQL/ADO.Net • LINQ to XML • LINQ to Amazon • LINQ to Active Directory • LINQ to CRM • LINQ To Geo - Language Integrated Query for Geospatial Data • LINQ to Excel • LINQ to Flickr • LINQ to Google • LINQ to Indexes (LINQ and i40) • LINQ to JSON • LINQ to IMAP • LINQ to NHibernate • LINQ to LDAP • LINQ to Lucene • LINQ to MySQL, Oracle and PostgreSql (DbLinq) • LINQ to NCover • LINQ to Opf3 • LINQ to RDF Files • LINQ to Sharepoint • LINQ to SimpleDB • LINQ to Streams • LINQ to WebQueries • LINQ to WMI From Links to LINQ page : http://blogs.msdn.com/b/charlie/archive/2008/02/28/link-to-everything-a-list-of-linqproviders.aspx Confidential
  • 16. Reasons behind Power of Iterators Iterators can act as ‘filters’ or ‘views’ • where instead of returning all elements of a collection it can ‘filter’ the elements and return a ‘partial’ list. • The filtering happens as ‘needed’ and an intermediate ‘collection’ of filtered results can be avoided. • Different implementations of iterator can provided different filtering criteria. • Hence algorithms written with ‘iterators’ can work on original collection or filtered collections. . Confidential
  • 17. Reasons behind Power of Iterators Iterators can be polymorphic • Hence same function can return different results by passing different iterator to it. • For example, in our previous example of printing numbers divisible by 3, can be easily changed to printing all ‘primes’ by replacing the iterator. There is no need to change the print function. Confidential
  • 18. Reasons behind Power of Iterators Iterators can be combined to provide more flexibility • For example, combine two existing iterators into a new iterator such that it ‘chains’ the child iterators • For example, ‘<itertools>’ module of python provides many ways of combining iterators • Following one liner in python efficiently returns ‘dot product’ of two mathematical vectors sum(imap(operator.mul, vector1, vector2)). imap() function takes multiple iterators and calls ‘mul’ (multiply function) with current values of those iterators. Confidential
  • 19. Reasons behind Power of Iterators Iterators can work with ‘collection like’ objects. • For example, we can write an iterator which return one word at a time from an input stream (or a text file) • Best example is how LINQ works with Databases or XML with exactly same interface. Confidential
  • 20. Few More Examples of Powerful Iterators Suppose we want to extract ‘unique words’ from a text file. • Since iterator can have its own state, we can write an iterator that remembers the words it already ‘seen’ and • if the word is already ‘seen’ ignore that word and reads the next word from the istream. • Such an iterator will return just the ‘unique’ words in the istream. • Now if you have function which takes a word iterator as parameter and prints the words, then just by passing the ‘unqiue word iterator, we can print the unique words in the text file. Confidential
  • 21. Laser Cutting Tool path Generation • For one of my project, problem was to generate the toolpath for laser cutting of sheet metal parts • Toolpath generation had different strategies based on various parameters and part selection logic etc etc. • Naïve implementation, will require • writing complicated for loops different strategies • Parameters passed as function parameters • Combining strategies is nearly impossible. • Lot of duplication of boiler plate code. • New strategy will require changes in the existing code. Confidential
  • 22. Laser Cutting Tool path Generation - Solution • We defined a base class ToolPathIterator • Every new toolpath creation strategy is implemented as ‘drived class’ of this iterator. • We also implemented iterators which derived from this base class And also used some existing Toolpathiterators internally to combine the strategies. • A Factory method instantiated the necessary toolpath iterator based on name of the strategy. • Only Factory method depends on all concrete iterator implementations. • Everywhere else ToolPathIterator base class was used. • Add a new strategy required • (a) adding new derived class from ToolpathIterator • (b) change in Factory Method. Confidential
  • 23. Why I don’t see many custom iterators ? WHY ITERATORS ARE UNDERAPPRECIATED ? Confidential
  • 24. •Most probably because Iterator is a ‘really simple concept’ •and •people have difficulty in believing that such simple concept can have so much power. Confidential
  • 25. Why iterators are underappreciated ? • Difficulty in thinking traversal/iteration as ‘separate object/responsibility’ • Difficulty in thinking ‘iterator’ as interface with multiple possible implementations • Writing an iterator requires defining a new class. • This may require additional coding while writing for loop may look simpler/quicker. Confidential
  • 26. Difficulty in ‘thinking’ traversal/iteration as ‘separate object’ • Developers are used to thinking in loops which work on ‘indices’. • For them ‘i++’ is conceptually easier that ‘it.next()’ • I see many examples of iterating over C++ vector use indexing operation (e.g. vec[i]) rather than using vec.begin(); • Hence creating separate class/object to keep track of current element and moving to next element is somehow difficult ‘leap’. • However once you make that ‘leap’ your subsequent design may change significantly from the past design Confidential
  • 27. ‘iterator’ as interface with multiple possible implementations • Since ‘iterator’ is a separate class/object, we can create ‘iterator’ interfaces (or base classes). • If we write function using the ‘iterator’ interface, then we can pass different implementations of iterators and get different behavior. • Different traversal algorithms (e.g. pre order, post order traversals in trees) • Filtering • All this flexibility is possible, if you start thinking in terms of ‘iterator interface and its implementations’ or a hierarchy of iterators. Confidential
  • 28. Writing an iterator requires defining a new class • In languages like Java, C++, writing an iterator means adding a new class in the system. • It required additional code than simple for loop • Developer has to take care in defining iterator interface (e.g. iterators that will work with STL containers). • Developers treated it as ‘additional burden/cost’ . They could not visualize the benefits and hence decided that separate iterator class is probably not worth the efforts. • However, this is changing with co-routines implementations • ‘yield return’ and similar keywords being introduced in the languages like C#, Python. Confidential
  • 29. Yield Return in C# • A Trivial Example : Writing an iterator which returns numbers divisible by three • Defining the Iterator using Yield Return. IEnumberable<int> DivisibleByThree() { for(int i=0; i< 100; i++) { if(i % 3 == 0) { yield return i; } } } • Using the Iterator with foreach foreach(var j=DivisibleByThree()) { print j; } Confidential
  • 30. TIPS FOR MAKING EFFECTIVE USE OF ITERATORS Confidential
  • 31. Use Iterators instead of ‘indexing’ in loops • In general, loops with iterators are more efficient than index based loops • For example, getting element at ‘i’th Index is equivalent to *(Startpos + i*sizeof(element)) While getting next element from the current element is equivalent to *(cur_elem_pos++) • Hence usually ‘iterators’ based loops are slightly faster. Confidential
  • 32. Never directly return a member ‘collection’ from a class Don’t DO Class XYZ { private List<int> intlist= new List<int>(); Class XYZ { private List<int> intlist= new List<int>(); List<int> IntList { get { return intlist; } } } IEnumberable<int> IntList { get { return intlist; } } } Confidential
  • 33. Loop+If : see if you can use an iterator • If you see similar loop + if condition or similar contents of loop at multiple places • See if you can extract the similarities into an Iterator • Sometime you have to create a ‘base iterator’ and override ‘MoveNext()’ implementations • If you are using C#/Python, see if you can use ‘yield’ Confidential
  • 34. Never directly return a member ‘collection’ from a class. • It violates ‘encapsulations’ • Also all the users of your class are now ‘explicitly’ depend on the collection (e.g List). • Tomorrow if you want to change the List to HashSet(), every where your class is used will potentially need to change. • For C# • Define an IEnumerable as ‘get’ property. It will allow you to change the internal collection type with almost no impact on the external interface. • For Java/C++ • Define an iterator for your class. Confidential
  • 35. Summary As Developer change your thinking to • Think traversal/iterator as ‘separate class/object/responsibility’ • Think ‘iterator’ as interface with multiple possible implementations • Different traversal strategies/algorithms can be implemented as different iterator implementations. Once you do that, you will find many more uses of Iterator • That can simplify your code • Make it less bug prone and more stable. • Make it easier to enhance and maintain Confidential
  • 36. END OF PRESENTATION The material contained in this deck represents proprietary, confidential information pertaining to products, technologies & processes from Geometric. All information in this document is to be treated in confidence. The names and trademarks used in this document are the sole property of the respective companies and are governed/ protected by the relevant trademark and copyright laws. © Geometric Limited | info@geometricglobal.com | www.geometricglobal.com | Confidential

Editor's Notes

  1. Since iterators can have state, suppose we write an iterator that remembers the words it already ‘seen’ and if the word is already ‘seen’ reads the next word from the istream. Such an iterator will return just the ‘unique’ words in the istream.