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

PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIShubhangi Sonawane
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxNikitaBankoti2
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 

Recently uploaded (20)

PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 

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: