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

Sql injections - with example
Sql injections - with exampleSql injections - with example
Sql injections - with examplePrateek Chauhan
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in javaCPD INDIA
 
Advanced SQL injection to operating system full control (whitepaper)
Advanced SQL injection to operating system full control (whitepaper)Advanced SQL injection to operating system full control (whitepaper)
Advanced SQL injection to operating system full control (whitepaper)Bernardo Damele A. G.
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List Hitesh-Java
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread poolsmaksym220889
 
Sql injection - security testing
Sql injection - security testingSql injection - security testing
Sql injection - security testingNapendra Singh
 
Sql injection in cybersecurity
Sql injection in cybersecuritySql injection in cybersecurity
Sql injection in cybersecuritySanad Bhowmik
 
Age calculator
Age calculatorAge calculator
Age calculatornajim017
 
Java - Interfaces & Packages
Java - Interfaces & PackagesJava - Interfaces & Packages
Java - Interfaces & PackagesArindam Ghosh
 
Java design patterns
Java design patternsJava design patterns
Java design patternsShawn Brito
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptmanish kumar
 
Design Patterns - 01 Introduction and Decorator Pattern
Design Patterns - 01 Introduction and Decorator PatternDesign Patterns - 01 Introduction and Decorator Pattern
Design Patterns - 01 Introduction and Decorator Patterneprafulla
 
소프트웨어 아키텍처 문서화
소프트웨어 아키텍처 문서화소프트웨어 아키텍처 문서화
소프트웨어 아키텍처 문서화영기 김
 

What's hot (20)

GORM
GORMGORM
GORM
 
Sql injections - with example
Sql injections - with exampleSql injections - with example
Sql injections - with example
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Advanced SQL injection to operating system full control (whitepaper)
Advanced SQL injection to operating system full control (whitepaper)Advanced SQL injection to operating system full control (whitepaper)
Advanced SQL injection to operating system full control (whitepaper)
 
Chapter2 Encapsulation (Java)
Chapter2 Encapsulation (Java)Chapter2 Encapsulation (Java)
Chapter2 Encapsulation (Java)
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
 
Template pattern
Template patternTemplate pattern
Template pattern
 
Sql injection - security testing
Sql injection - security testingSql injection - security testing
Sql injection - security testing
 
Sql injection in cybersecurity
Sql injection in cybersecuritySql injection in cybersecurity
Sql injection in cybersecurity
 
Proxy pattern
Proxy patternProxy pattern
Proxy pattern
 
Age calculator
Age calculatorAge calculator
Age calculator
 
Java - Interfaces & Packages
Java - Interfaces & PackagesJava - Interfaces & Packages
Java - Interfaces & Packages
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
 
Design Patterns - 01 Introduction and Decorator Pattern
Design Patterns - 01 Introduction and Decorator PatternDesign Patterns - 01 Introduction and Decorator Pattern
Design Patterns - 01 Introduction and Decorator Pattern
 
Sql injection
Sql injectionSql injection
Sql injection
 
Jpa
JpaJpa
Jpa
 
소프트웨어 아키텍처 문서화
소프트웨어 아키텍처 문서화소프트웨어 아키텍처 문서화
소프트웨어 아키텍처 문서화
 

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
 
java framwork for HIBERNATE FRAMEWORK.pptx
java framwork for HIBERNATE FRAMEWORK.pptxjava framwork for HIBERNATE FRAMEWORK.pptx
java framwork for HIBERNATE FRAMEWORK.pptxramanujsaini2001
 
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
 

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
 
java framwork for HIBERNATE FRAMEWORK.pptx
java framwork for HIBERNATE FRAMEWORK.pptxjava framwork for HIBERNATE FRAMEWORK.pptx
java framwork for HIBERNATE FRAMEWORK.pptx
 
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
 

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

Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...caitlingebhard1
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxMarkSteadman7
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringWSO2
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....rightmanforbloodline
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuidePixlogix Infotech
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAnitaRaj43
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
How to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfHow to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfdanishmna97
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 

Recently uploaded (20)

Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptx
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software Engineering
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
How to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfHow to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 

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.