SlideShare a Scribd company logo
1 of 25
Stéphane Ducasse 1
Stéphane Ducasse
stephane.ducasse@inria.fr
http://stephane.ducasse.free.fr/
Basic Objects,
Conditionals and Loops
S.Ducasse 2
Conditionals and Loops
Booleans
Basic Loops
Overview of the Collection hierarchy— more than 80
classes: (Bag,Array, OrderedCollection,
SortedCollection, Set, Dictionary...)
Loops and Iteration abstractions
Common object behavior
S.Ducasse 3
Booleans
S.Ducasse 4
Boolean Objects
• false and true are objects described by classes
Boolean,True and False
• Uniform, but optimized and inlined (macro
expansion at compile time)
• Logical Comparisons &, |, xor:, not
• aBooleanExpr comparison anotherBooleanExpr
• (1 isZero) & false
S.Ducasse 5
Boolean Hierarchy
• Please open your browser and analyse it
• How to implement in OO true and false without
conditional? Booleean
not
ifTrue:
False
not
ifTrue:
True
not
ifTrue:
S.Ducasse 6
Boolean Lazy Logical Operators
• Lazy Logical operators
aBooleanExpr and: andBlock
• andBlock will only be valued if aBooleanExpression is
true
• aBooleanExpression or: orBlock
• orBlock will only be valued if aBooleanExpression is false
false and: [1 error: 'crazy']
PrIt-> false and not an error
S.Ducasse 7
Conditional are Messages to Boolean
Objects
• aBoolean ifTrue: aTrueBlock ifFalse: aFalseBlock
• aBoolean ifFalse: aFalseBlock ifTrue: aTrueBlock
• aBoolean ifTrue: aTrueBlock
• aBoolean ifFalse: aFalseBlock
• Hint:Take care — true is the boolean value and
True is the class of true, its unique instance!
S.Ducasse 8
Why Block Use in Conditional
• Why do conditional expressions use blocks?
• Because, when a message is sent, the receiver
and the arguments of the message are always
evaluated. Blocks are necessary to avoid
evaluating both branches.
S.Ducasse 14
Collections
A lot but key abstraction
Key iterators
S.Ducasse 15
Collections
• Some criteria to identify them
– Access: indexed, sequential or key-based.
– Size: fixed or dynamic.
– Element type: any or well-defined type.
– Order: defined, defineable or none.
– Duplicates: possible or not
S.Ducasse 16
Essential Collection
Sequenceable ordered
ArrayedCollection fixed size + key = integer
Array any kind of elements
CharacterArray elements = character
String
IntegerArray
Interval arithmetique progression
LinkedList dynamic chaining of the element
OrderedCollection size dynamic + arrival order
SortedCollection explicit order
Bag possible duplicate + no order
Set no duplicate + no order
IdentitySet identification based on identity
Dictionary element = associations + key based
IdentityDictionary key based on identity
S.Ducasse 17
Essential Collections:AnotherView
Keyed
Adds Allowed
Sorted
UniqueKey
Duplicates Allowed
Bag Set
Sorted
Ordered
Array
String
Identity Dictionary
Integer Key
Dictionary
Collection
Collection
y
y
y
y
y
yn
n
n
n
n
n
S.Ducasse 18
Some Collection Methods
• Will be defined, redefined, optimized or forbidden in the
subclasses
• Accessing: size, capacity, at: anInteger, at: anInteger put: anElement
• Testing: isEmpty, includes: anElement, contains: aBlock, occurencesOf:
anElement
• Adding: add: anElement, addAll: aCollection
• Removing: remove: anElement, remove:anElement ifAbsent: aBlock,
removeAll: aCollection
• Enumerating (See generic enumerating): do: aBlock, collect: aBlock, select:
aBlock, reject: aBlock, detect:, detect: aBlock ifNone: aNoneBlock, inject:
avalue into: aBinaryBlock
• Converting: asBag, asSet, asOrderedCollection, asSortedCollection,
asArray, asSortedCollection: aBlock
• Creation: with: anElement, with:with:, with:with:with:, with:with:with:with:,
with:All: aCollection
S.Ducasse 19
Sequenceable Specific (Array)
|arr|
arr := #(calvin hates suzie).
arr at: 2 put: loves.
arr
PrIt-> #( calvin loves suzie)
•Accessing: first, last, atAllPut: anElement, atAll:
anIndexCollection: put: anElement
•Searching (*: + ifAbsent:): indexOf: anElement, indexOf:
anElement ifAbsent: aBlock
•Changing: replaceAll: anElement with: anotherElement
•Copying: copyFrom: first to: last, copyWith: anElement,
copyWithout: anElement
S.Ducasse 20
KeyedCollection Specific (Dictionary)
|dict|
dict := Dictionary new.
dict at: 'toto' put: 3.
dict at: 'titi' ifAbsent: [4]. -> 4
dict at: 'titi' put: 5.
dict removeKey: 'toto'.
dict keys -> Set ('titi')
•Accessing: at: aKey, at: aKey ifAbsent: aBlock, at: aKey
ifAbsentPut: aBlock, at: aKey put: aValue, keys, values,
associations
•Removing: removeKey: aKey, removeKey: aKey ifAbsent: aBlock
•Testing: includeKey: aKey
•Enumerating: keysAndValuesDo: aBlock, associationsDo: aBlock,
keysDo: aBlock
S.Ducasse 28
Common Shared Behavior
S.Ducasse 29
Common Shared Behavior
• Object is the root of the inheritance tree
• Defines the common and minimal behavior for
all the objects in the system.
• Comparison of objects: ==, ~~, =, =~, isNil,
notNil
S.Ducasse 30
Identity vs. Equality
• = anObject returns true if the structures are equivalent (the same
hash number)
• (Array with: 1 with: 2) = (Array with:1 with:2) PrIt-> true
• == anObject returns true if the receiver and the argument point to
the same object. == should never be overridden.
Object>>= anObject
^ self == anObject
~= is: not =
~~ is: not ==
(Array with: 1 with: 2 ) == (Array with: 1 with:2) PrIt-> false
(Array with: 1 with: 2 ) = (Array with: 1 with:2) PrIt-> true
• Take care when redefining = . One should override hash too!
S.Ducasse 31
Common Behavior: Printing
• Print and store objects: printString, printOn: aStream.
printString calls printOn: aStream
(123 1 2 3) printString
-> ' (123 1 2 3)'
Date today printString
-> 'October 5, 1997'
S.Ducasse 32
Storing
• storeString, storeOn: aStream.
• storeString calls storeOn: aStream
Date today storeString
-> '(Date readFromString: ''10/5/1997'')'
OrderedCollection new add: 4 ; add: 3 ; storeString
-> '((OrderedCollection new) add: 4; add: 3; yourself)’
• You need the compiler, so for a deployment image this is
not convenient
S.Ducasse 33
readFromString: recreating Objects
• Create instances from stored objects: class methods
readFrom: aStream, readFromString: aString
• Object readFromString: '((OrderedCollection new)
add: 4; yourself)'
• -> OrderedCollection (4)
S.Ducasse 34
Notifying the Programmer
• error: aString,
• doesNotUnderstand: aMessage,
• halt, halt: aString,
• To invoke the debugger
• Input defaultState shiftPressed ifTrue:[self halt]
• shouldNotImplement
• Sign of bad design: subclassing
• subclassResponsibility
• Abstract method
S.Ducasse 35
Copying inVW
• Copying of objects: shallowCopy, copy
• shallowCopy : the copy shares instance variables
with the receiver.
• default implementation of copy is shallowCopy
a a copy
S.Ducasse 36
Copying inVW
Object>>copy
^ self shallowCopy postCopy
Object>>postCopy
^ self
•postCopy is a hook method
•copy is a template method
S.Ducasse 37
Summary
timesRepeat:, to:do:,
Array, OrderedCollection, Dictionary, Set
do:, select:, collect:

More Related Content

What's hot

Switching from java to groovy
Switching from java to groovySwitching from java to groovy
Switching from java to groovyPaul Woods
 
SPL - The Undiscovered Library - PHPBarcelona 2015
SPL - The Undiscovered Library - PHPBarcelona 2015SPL - The Undiscovered Library - PHPBarcelona 2015
SPL - The Undiscovered Library - PHPBarcelona 2015Mark Baker
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2RajKumar Rampelli
 
New SPL Features in PHP 5.3
New SPL Features in PHP 5.3New SPL Features in PHP 5.3
New SPL Features in PHP 5.3Matthew Turland
 
Talk about ReactiveMongo at MSUG May
Talk about ReactiveMongo at MSUG MayTalk about ReactiveMongo at MSUG May
Talk about ReactiveMongo at MSUG MayAndrey Neverov
 
Working with Groovy Collections
Working with Groovy CollectionsWorking with Groovy Collections
Working with Groovy CollectionsTed Vinke
 
Invertible-syntax 入門
Invertible-syntax 入門Invertible-syntax 入門
Invertible-syntax 入門Hiromi Ishii
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)Night Sailer
 
Solr & Lucene @ Etsy by Gregg Donovan
Solr & Lucene @ Etsy by Gregg DonovanSolr & Lucene @ Etsy by Gregg Donovan
Solr & Lucene @ Etsy by Gregg DonovanGregg Donovan
 
MySQLConf2009: Taking ActiveRecord to the Next Level
MySQLConf2009: Taking ActiveRecord to the Next LevelMySQLConf2009: Taking ActiveRecord to the Next Level
MySQLConf2009: Taking ActiveRecord to the Next LevelBlythe Dunham
 
RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기Suyeol Jeon
 

What's hot (20)

16 ruby hashes
16 ruby hashes16 ruby hashes
16 ruby hashes
 
ScalaBlitz
ScalaBlitzScalaBlitz
ScalaBlitz
 
Switching from java to groovy
Switching from java to groovySwitching from java to groovy
Switching from java to groovy
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
SPL - The Undiscovered Library - PHPBarcelona 2015
SPL - The Undiscovered Library - PHPBarcelona 2015SPL - The Undiscovered Library - PHPBarcelona 2015
SPL - The Undiscovered Library - PHPBarcelona 2015
 
Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2
 
New SPL Features in PHP 5.3
New SPL Features in PHP 5.3New SPL Features in PHP 5.3
New SPL Features in PHP 5.3
 
Talk about ReactiveMongo at MSUG May
Talk about ReactiveMongo at MSUG MayTalk about ReactiveMongo at MSUG May
Talk about ReactiveMongo at MSUG May
 
Scala Parallel Collections
Scala Parallel CollectionsScala Parallel Collections
Scala Parallel Collections
 
Working with Groovy Collections
Working with Groovy CollectionsWorking with Groovy Collections
Working with Groovy Collections
 
Invertible-syntax 入門
Invertible-syntax 入門Invertible-syntax 入門
Invertible-syntax 入門
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 
Array1
Array1Array1
Array1
 
Solr & Lucene @ Etsy by Gregg Donovan
Solr & Lucene @ Etsy by Gregg DonovanSolr & Lucene @ Etsy by Gregg Donovan
Solr & Lucene @ Etsy by Gregg Donovan
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
Functional es6
Functional es6Functional es6
Functional es6
 
MySQLConf2009: Taking ActiveRecord to the Next Level
MySQLConf2009: Taking ActiveRecord to the Next LevelMySQLConf2009: Taking ActiveRecord to the Next Level
MySQLConf2009: Taking ActiveRecord to the Next Level
 
Lodash js
Lodash jsLodash js
Lodash js
 
RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기
 

Viewers also liked (20)

14 - Exceptions
14 - Exceptions14 - Exceptions
14 - Exceptions
 
9 - OOP - Smalltalk Classes (b)
9 - OOP - Smalltalk Classes (b)9 - OOP - Smalltalk Classes (b)
9 - OOP - Smalltalk Classes (b)
 
Stoop ed-class forreuse
Stoop ed-class forreuseStoop ed-class forreuse
Stoop ed-class forreuse
 
Stoop 305-reflective programming5
Stoop 305-reflective programming5Stoop 305-reflective programming5
Stoop 305-reflective programming5
 
Stoop 423-smalltalk idioms
Stoop 423-smalltalk idiomsStoop 423-smalltalk idioms
Stoop 423-smalltalk idioms
 
Stoop 301-internal objectstructureinvw
Stoop 301-internal objectstructureinvwStoop 301-internal objectstructureinvw
Stoop 301-internal objectstructureinvw
 
Stoop 437-proxy
Stoop 437-proxyStoop 437-proxy
Stoop 437-proxy
 
Stoop 450-s unit
Stoop 450-s unitStoop 450-s unit
Stoop 450-s unit
 
Double Dispatch
Double DispatchDouble Dispatch
Double Dispatch
 
Stoop 422-naming idioms
Stoop 422-naming idiomsStoop 422-naming idioms
Stoop 422-naming idioms
 
Debugging VisualWorks
Debugging VisualWorksDebugging VisualWorks
Debugging VisualWorks
 
Stoop 400-metaclass only
Stoop 400-metaclass onlyStoop 400-metaclass only
Stoop 400-metaclass only
 
Stoop ed-inheritance composition
Stoop ed-inheritance compositionStoop ed-inheritance composition
Stoop ed-inheritance composition
 
5 - OOP - Smalltalk in a Nutshell (c)
5 - OOP - Smalltalk in a Nutshell (c)5 - OOP - Smalltalk in a Nutshell (c)
5 - OOP - Smalltalk in a Nutshell (c)
 
08 refactoring
08 refactoring08 refactoring
08 refactoring
 
Stoop ed-subtyping subclassing
Stoop ed-subtyping subclassingStoop ed-subtyping subclassing
Stoop ed-subtyping subclassing
 
Stoop ed-lod
Stoop ed-lodStoop ed-lod
Stoop ed-lod
 
Stoop 413-abstract classes
Stoop 413-abstract classesStoop 413-abstract classes
Stoop 413-abstract classes
 
06 debugging
06 debugging06 debugging
06 debugging
 
05 seaside
05 seaside05 seaside
05 seaside
 

Similar to 12 - Conditions and Loops

Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structuresagorolabs
 
OclApunteNavegacion.ppt
OclApunteNavegacion.pptOclApunteNavegacion.ppt
OclApunteNavegacion.pptClaudiaNaveda2
 
0-Slot18-19-20-ContiguousStorage.pdf
0-Slot18-19-20-ContiguousStorage.pdf0-Slot18-19-20-ContiguousStorage.pdf
0-Slot18-19-20-ContiguousStorage.pdfssusere19c741
 
Introduction to Ruby Programming Language
Introduction to Ruby Programming LanguageIntroduction to Ruby Programming Language
Introduction to Ruby Programming LanguageNicolò Calcavecchia
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.pptYonas D. Ebren
 
Mathemetics module
Mathemetics moduleMathemetics module
Mathemetics modulemanikanta361
 
Java OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionJava OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionOUM SAOKOSAL
 
Code Like Pythonista
Code Like PythonistaCode Like Pythonista
Code Like PythonistaChiyoung Song
 
Hashing In Data Structure Download PPT i
Hashing In Data Structure Download PPT iHashing In Data Structure Download PPT i
Hashing In Data Structure Download PPT icajiwol341
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonUC San Diego
 
Iniciando com jquery
Iniciando com jqueryIniciando com jquery
Iniciando com jqueryDanilo Sousa
 
.NET Fest 2018. Дмитрий Иванов. Иммутабельные структуры данных в .NET: зачем ...
.NET Fest 2018. Дмитрий Иванов. Иммутабельные структуры данных в .NET: зачем ....NET Fest 2018. Дмитрий Иванов. Иммутабельные структуры данных в .NET: зачем ...
.NET Fest 2018. Дмитрий Иванов. Иммутабельные структуры данных в .NET: зачем ...NETFest
 
9collection in c#
9collection in c#9collection in c#
9collection in c#Sireesh K
 
Session 14 - Object Class
Session 14 - Object ClassSession 14 - Object Class
Session 14 - Object ClassPawanMM
 

Similar to 12 - Conditions and Loops (20)

Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
OclApunteNavegacion.ppt
OclApunteNavegacion.pptOclApunteNavegacion.ppt
OclApunteNavegacion.ppt
 
0-Slot18-19-20-ContiguousStorage.pdf
0-Slot18-19-20-ContiguousStorage.pdf0-Slot18-19-20-ContiguousStorage.pdf
0-Slot18-19-20-ContiguousStorage.pdf
 
Introduction to Ruby Programming Language
Introduction to Ruby Programming LanguageIntroduction to Ruby Programming Language
Introduction to Ruby Programming Language
 
Javasession7
Javasession7Javasession7
Javasession7
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
 
Mathemetics module
Mathemetics moduleMathemetics module
Mathemetics module
 
Java 103
Java 103Java 103
Java 103
 
Java OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionJava OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - Collection
 
Code Like Pythonista
Code Like PythonistaCode Like Pythonista
Code Like Pythonista
 
Data Mining Lecture_3.pptx
Data Mining Lecture_3.pptxData Mining Lecture_3.pptx
Data Mining Lecture_3.pptx
 
Icom4015 lecture14-f16
Icom4015 lecture14-f16Icom4015 lecture14-f16
Icom4015 lecture14-f16
 
Hashing In Data Structure Download PPT i
Hashing In Data Structure Download PPT iHashing In Data Structure Download PPT i
Hashing In Data Structure Download PPT i
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Java tutorial part 4
Java tutorial part 4Java tutorial part 4
Java tutorial part 4
 
Recursion
RecursionRecursion
Recursion
 
Iniciando com jquery
Iniciando com jqueryIniciando com jquery
Iniciando com jquery
 
.NET Fest 2018. Дмитрий Иванов. Иммутабельные структуры данных в .NET: зачем ...
.NET Fest 2018. Дмитрий Иванов. Иммутабельные структуры данных в .NET: зачем ....NET Fest 2018. Дмитрий Иванов. Иммутабельные структуры данных в .NET: зачем ...
.NET Fest 2018. Дмитрий Иванов. Иммутабельные структуры данных в .NET: зачем ...
 
9collection in c#
9collection in c#9collection in c#
9collection in c#
 
Session 14 - Object Class
Session 14 - Object ClassSession 14 - Object Class
Session 14 - Object Class
 

More from The World of Smalltalk (20)

05 seaside canvas
05 seaside canvas05 seaside canvas
05 seaside canvas
 
99 questions
99 questions99 questions
99 questions
 
13 traits
13 traits13 traits
13 traits
 
12 virtualmachine
12 virtualmachine12 virtualmachine
12 virtualmachine
 
11 bytecode
11 bytecode11 bytecode
11 bytecode
 
10 reflection
10 reflection10 reflection
10 reflection
 
09 metaclasses
09 metaclasses09 metaclasses
09 metaclasses
 
07 bestpractice
07 bestpractice07 bestpractice
07 bestpractice
 
04 idioms
04 idioms04 idioms
04 idioms
 
03 standardclasses
03 standardclasses03 standardclasses
03 standardclasses
 
02 basics
02 basics02 basics
02 basics
 
01 intro
01 intro01 intro
01 intro
 
Stoop sed-smells
Stoop sed-smellsStoop sed-smells
Stoop sed-smells
 
Stoop sed-sharing ornot
Stoop sed-sharing ornotStoop sed-sharing ornot
Stoop sed-sharing ornot
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
Stoop metaclasses
Stoop metaclassesStoop metaclasses
Stoop metaclasses
 
Stoop ed-unit ofreuse
Stoop ed-unit ofreuseStoop ed-unit ofreuse
Stoop ed-unit ofreuse
 
Stoop ed-some principles
Stoop ed-some principlesStoop ed-some principles
Stoop ed-some principles
 
Stoop ed-frameworks
Stoop ed-frameworksStoop ed-frameworks
Stoop ed-frameworks
 

Recently uploaded

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 

Recently uploaded (20)

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 

12 - Conditions and Loops

  • 1. Stéphane Ducasse 1 Stéphane Ducasse stephane.ducasse@inria.fr http://stephane.ducasse.free.fr/ Basic Objects, Conditionals and Loops
  • 2. S.Ducasse 2 Conditionals and Loops Booleans Basic Loops Overview of the Collection hierarchy— more than 80 classes: (Bag,Array, OrderedCollection, SortedCollection, Set, Dictionary...) Loops and Iteration abstractions Common object behavior
  • 4. S.Ducasse 4 Boolean Objects • false and true are objects described by classes Boolean,True and False • Uniform, but optimized and inlined (macro expansion at compile time) • Logical Comparisons &, |, xor:, not • aBooleanExpr comparison anotherBooleanExpr • (1 isZero) & false
  • 5. S.Ducasse 5 Boolean Hierarchy • Please open your browser and analyse it • How to implement in OO true and false without conditional? Booleean not ifTrue: False not ifTrue: True not ifTrue:
  • 6. S.Ducasse 6 Boolean Lazy Logical Operators • Lazy Logical operators aBooleanExpr and: andBlock • andBlock will only be valued if aBooleanExpression is true • aBooleanExpression or: orBlock • orBlock will only be valued if aBooleanExpression is false false and: [1 error: 'crazy'] PrIt-> false and not an error
  • 7. S.Ducasse 7 Conditional are Messages to Boolean Objects • aBoolean ifTrue: aTrueBlock ifFalse: aFalseBlock • aBoolean ifFalse: aFalseBlock ifTrue: aTrueBlock • aBoolean ifTrue: aTrueBlock • aBoolean ifFalse: aFalseBlock • Hint:Take care — true is the boolean value and True is the class of true, its unique instance!
  • 8. S.Ducasse 8 Why Block Use in Conditional • Why do conditional expressions use blocks? • Because, when a message is sent, the receiver and the arguments of the message are always evaluated. Blocks are necessary to avoid evaluating both branches.
  • 9. S.Ducasse 14 Collections A lot but key abstraction Key iterators
  • 10. S.Ducasse 15 Collections • Some criteria to identify them – Access: indexed, sequential or key-based. – Size: fixed or dynamic. – Element type: any or well-defined type. – Order: defined, defineable or none. – Duplicates: possible or not
  • 11. S.Ducasse 16 Essential Collection Sequenceable ordered ArrayedCollection fixed size + key = integer Array any kind of elements CharacterArray elements = character String IntegerArray Interval arithmetique progression LinkedList dynamic chaining of the element OrderedCollection size dynamic + arrival order SortedCollection explicit order Bag possible duplicate + no order Set no duplicate + no order IdentitySet identification based on identity Dictionary element = associations + key based IdentityDictionary key based on identity
  • 12. S.Ducasse 17 Essential Collections:AnotherView Keyed Adds Allowed Sorted UniqueKey Duplicates Allowed Bag Set Sorted Ordered Array String Identity Dictionary Integer Key Dictionary Collection Collection y y y y y yn n n n n n
  • 13. S.Ducasse 18 Some Collection Methods • Will be defined, redefined, optimized or forbidden in the subclasses • Accessing: size, capacity, at: anInteger, at: anInteger put: anElement • Testing: isEmpty, includes: anElement, contains: aBlock, occurencesOf: anElement • Adding: add: anElement, addAll: aCollection • Removing: remove: anElement, remove:anElement ifAbsent: aBlock, removeAll: aCollection • Enumerating (See generic enumerating): do: aBlock, collect: aBlock, select: aBlock, reject: aBlock, detect:, detect: aBlock ifNone: aNoneBlock, inject: avalue into: aBinaryBlock • Converting: asBag, asSet, asOrderedCollection, asSortedCollection, asArray, asSortedCollection: aBlock • Creation: with: anElement, with:with:, with:with:with:, with:with:with:with:, with:All: aCollection
  • 14. S.Ducasse 19 Sequenceable Specific (Array) |arr| arr := #(calvin hates suzie). arr at: 2 put: loves. arr PrIt-> #( calvin loves suzie) •Accessing: first, last, atAllPut: anElement, atAll: anIndexCollection: put: anElement •Searching (*: + ifAbsent:): indexOf: anElement, indexOf: anElement ifAbsent: aBlock •Changing: replaceAll: anElement with: anotherElement •Copying: copyFrom: first to: last, copyWith: anElement, copyWithout: anElement
  • 15. S.Ducasse 20 KeyedCollection Specific (Dictionary) |dict| dict := Dictionary new. dict at: 'toto' put: 3. dict at: 'titi' ifAbsent: [4]. -> 4 dict at: 'titi' put: 5. dict removeKey: 'toto'. dict keys -> Set ('titi') •Accessing: at: aKey, at: aKey ifAbsent: aBlock, at: aKey ifAbsentPut: aBlock, at: aKey put: aValue, keys, values, associations •Removing: removeKey: aKey, removeKey: aKey ifAbsent: aBlock •Testing: includeKey: aKey •Enumerating: keysAndValuesDo: aBlock, associationsDo: aBlock, keysDo: aBlock
  • 17. S.Ducasse 29 Common Shared Behavior • Object is the root of the inheritance tree • Defines the common and minimal behavior for all the objects in the system. • Comparison of objects: ==, ~~, =, =~, isNil, notNil
  • 18. S.Ducasse 30 Identity vs. Equality • = anObject returns true if the structures are equivalent (the same hash number) • (Array with: 1 with: 2) = (Array with:1 with:2) PrIt-> true • == anObject returns true if the receiver and the argument point to the same object. == should never be overridden. Object>>= anObject ^ self == anObject ~= is: not = ~~ is: not == (Array with: 1 with: 2 ) == (Array with: 1 with:2) PrIt-> false (Array with: 1 with: 2 ) = (Array with: 1 with:2) PrIt-> true • Take care when redefining = . One should override hash too!
  • 19. S.Ducasse 31 Common Behavior: Printing • Print and store objects: printString, printOn: aStream. printString calls printOn: aStream (123 1 2 3) printString -> ' (123 1 2 3)' Date today printString -> 'October 5, 1997'
  • 20. S.Ducasse 32 Storing • storeString, storeOn: aStream. • storeString calls storeOn: aStream Date today storeString -> '(Date readFromString: ''10/5/1997'')' OrderedCollection new add: 4 ; add: 3 ; storeString -> '((OrderedCollection new) add: 4; add: 3; yourself)’ • You need the compiler, so for a deployment image this is not convenient
  • 21. S.Ducasse 33 readFromString: recreating Objects • Create instances from stored objects: class methods readFrom: aStream, readFromString: aString • Object readFromString: '((OrderedCollection new) add: 4; yourself)' • -> OrderedCollection (4)
  • 22. S.Ducasse 34 Notifying the Programmer • error: aString, • doesNotUnderstand: aMessage, • halt, halt: aString, • To invoke the debugger • Input defaultState shiftPressed ifTrue:[self halt] • shouldNotImplement • Sign of bad design: subclassing • subclassResponsibility • Abstract method
  • 23. S.Ducasse 35 Copying inVW • Copying of objects: shallowCopy, copy • shallowCopy : the copy shares instance variables with the receiver. • default implementation of copy is shallowCopy a a copy
  • 24. S.Ducasse 36 Copying inVW Object>>copy ^ self shallowCopy postCopy Object>>postCopy ^ self •postCopy is a hook method •copy is a template method
  • 25. S.Ducasse 37 Summary timesRepeat:, to:do:, Array, OrderedCollection, Dictionary, Set do:, select:, collect: