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

Servlets - filter, listeners, wrapper, internationalization
Servlets -  filter, listeners, wrapper, internationalizationServlets -  filter, listeners, wrapper, internationalization
Servlets - filter, listeners, wrapper, internationalizationsusant sahu
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design PatternSanae BEKKAR
 
Singleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation PatternSingleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation PatternSeerat Malik
 
Understanding LINQ in C#
Understanding LINQ in C# Understanding LINQ in C#
Understanding LINQ in C# MD. Shohag Mia
 
Angular 6 Form Validation with Material
Angular 6 Form Validation with MaterialAngular 6 Form Validation with Material
Angular 6 Form Validation with MaterialMalika Munaweera
 
Py.test
Py.testPy.test
Py.testsoasme
 
Java Collections
Java CollectionsJava Collections
Java Collectionsparag
 
QA Fes 2016. Алексей Виноградов. Page Objects: лучше проще, да лучшe
QA Fes 2016. Алексей Виноградов. Page Objects: лучше проще, да лучшeQA Fes 2016. Алексей Виноградов. Page Objects: лучше проще, да лучшe
QA Fes 2016. Алексей Виноградов. Page Objects: лучше проще, да лучшeQAFest
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesWebStackAcademy
 
Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)Sameer Rathoud
 
Event Sourcing with Kotlin, who needs frameworks!
Event Sourcing with Kotlin, who needs frameworks!Event Sourcing with Kotlin, who needs frameworks!
Event Sourcing with Kotlin, who needs frameworks!Nico Krijnen
 
Visitor Pattern
Visitor PatternVisitor Pattern
Visitor PatternIder Zheng
 

What's hot (20)

Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
 
Visitor design patterns
Visitor design patternsVisitor design patterns
Visitor design patterns
 
Servlets - filter, listeners, wrapper, internationalization
Servlets -  filter, listeners, wrapper, internationalizationServlets -  filter, listeners, wrapper, internationalization
Servlets - filter, listeners, wrapper, internationalization
 
Iterator
IteratorIterator
Iterator
 
Design patterns
Design patternsDesign patterns
Design patterns
 
07 java collection
07 java collection07 java collection
07 java collection
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
 
Singleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation PatternSingleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation Pattern
 
Understanding LINQ in C#
Understanding LINQ in C# Understanding LINQ in C#
Understanding LINQ in C#
 
Angular 6 Form Validation with Material
Angular 6 Form Validation with MaterialAngular 6 Form Validation with Material
Angular 6 Form Validation with Material
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
Py.test
Py.testPy.test
Py.test
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
QA Fes 2016. Алексей Виноградов. Page Objects: лучше проще, да лучшe
QA Fes 2016. Алексей Виноградов. Page Objects: лучше проще, да лучшeQA Fes 2016. Алексей Виноградов. Page Objects: лучше проще, да лучшe
QA Fes 2016. Алексей Виноградов. Page Objects: лучше проще, да лучшe
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 
Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Event Sourcing with Kotlin, who needs frameworks!
Event Sourcing with Kotlin, who needs frameworks!Event Sourcing with Kotlin, who needs frameworks!
Event Sourcing with Kotlin, who needs frameworks!
 
Visitor Pattern
Visitor PatternVisitor Pattern
Visitor Pattern
 

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
 
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
 
LINQ Inside
LINQ InsideLINQ Inside
LINQ Insidejeffz
 

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
 
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
 
LINQ Inside
LINQ InsideLINQ Inside
LINQ Inside
 

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

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 

Recently uploaded (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.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.