SlideShare uma empresa Scribd logo
1 de 48
6. Debugging
Birds-eye view
© Oscar Nierstrasz
ST — Introduction
1.2
It can be easier to talk to objects than to read
classes — The system is alive. Talk to it.
The debugger can be your best friend. Don’t be afraid of it.
It can be easier to talk to objects than to read
classes — The system is alive. Talk to it.
The debugger can be your best friend. Don’t be afraid of it.
© Oscar Nierstrasz
ST — Debugging
6.3
Roadmap
> Common syntactic errors
> Common semantic errors
> Encapsulation errors
> Class/instance errors
> Debugging patterns
Selected material based on Klimas, et al., Smalltalk with Style.
Selected material courtesy Stéphane Ducasse.
© Oscar Nierstrasz
ST — Debugging
6.4
Roadmap
> Common syntactic errors
> Common semantic errors
> Encapsulation errors
> Class/instance errors
> Debugging patterns
© Oscar Nierstrasz
ST — Debugging
6.5
Does not understand self
> The error message “does not understand self” usually
means that you have forgotten the period at the end of a
statement
SnakesAndLaddersTest>>testExample
self assert: eg currentPlayer = jack.
loadedDie roll: 1.
eg playOneMove
self assert: jack position = 6.
self assert: eg currentPlayer = jill.
Klimas, et al., Smalltalk with Style
© Oscar Nierstrasz
ST — Debugging
6.6
Use parentheses in expressions with
multiple keyword messages
> Do not forget to use parentheses when sending multiple
keyword messages in one expression
self assert: players includes: aPlayer.
self assert: (players includes: aPlayer).
Klimas, et al., Smalltalk with Style
© Oscar Nierstrasz
ST — Debugging
6.7
True vs true
> true is the boolean value, True its class.
Book>>initialize
inLibrary := true
Book>>initialize
inLibrary := True
© Oscar Nierstrasz
ST — Debugging
6.8
nil is not a Boolean
> nil is not an acceptable receiver for ifTrue:
© Oscar Nierstrasz
ST — Debugging
6.9
whileTrue
> The receiver of whileTrue: and whileTrue must be
a block
[x<y] whileTrue: [x := x + 3]
(x<y) whileTrue: [x := x + 3]
© Oscar Nierstrasz
ST — Debugging
6.10
Commenting comments
> Be careful when commenting out code that contains
comments
— You may activate some other code that was commented out!
MyClass>>doit
self doStuff.
"
self doMoreStuff.
"self suicide."
self finishUp.
"
MyClass>>doit
self doStuff.
self doMoreStuff.
"self suicide."
self finishUp.
© Oscar Nierstrasz
ST — Debugging
6.11
Forgetting to return the result
> In a method self is returned by default.
— Do not forget ^ to return something else!
BoardSquare>>isLastSquare
position = board lastPosition
Returns self (a BoardSquare), not a Boolean!
© Oscar Nierstrasz
ST — Debugging
6.12
Interesting Return Value
When do you explicitly return a value at the end
of a method?
> Return a value only when you intend for the sender to
use the value.
— Return self explicitly only if the client is expected to use it!
BoardSquare>>destination
^ self
Even though self is returned
by default we make explicit
that this is the value returned.
© Oscar Nierstrasz
ST — Debugging
6.13
Method arguments are read-only
> Do not try to assign a value to a method argument.
— Arguments are read only!
MyClass>>setName: aString
aString := aString, 'Device'.
name := aString
Won’t compile!
© Oscar Nierstrasz
ST — Debugging
6.14
self and super are read-only
> Do not try to modify self or super
© Oscar Nierstrasz
ST — Debugging
6.15
Roadmap
> Common syntactic errors
> Common semantic errors
> Encapsulation errors
> Class/instance errors
> Debugging patterns
© Oscar Nierstrasz
ST — Debugging
6.16
Do not override basic methods
> Never redefine basic-methods
— ==, basicNew, basicNew:, basicAt:, basicAt:Put: ...
> Never redefine the method class
© Oscar Nierstrasz
ST — Debugging
6.17
hash and =
> Redefine hash whenever you redefine =
— Ensure that if a = b then a hash = b hash
— Otherwise Sets and Dictionaries may behave incorrectly!
Book>>=aBook
^ (self title = aBook title)
and: [self author = aBook author]
Book>>hash
^self title hash bitXor: self author hash
© Oscar Nierstrasz
ST — Debugging
6.18
add: returns the argument
> add: returns the argument and not the receiver
— Use yourself to get the collection back.
OrderedCollection new add: 5; add: 6
OrderedCollection new add: 5; add: 6; yourself
an OrderedCollection(5 6)
6
[:range | range copy do: [:aNumber | aNumber isPrime
ifFalse: [ range remove: aNumber ]]. range
] value: ((2 to: 20) asOrderedCollection)
First copy the collection
an OrderedCollection(2 3 5 7 11 13 17 19)
© Oscar Nierstrasz
ST — Debugging
6.19
Don’t iterate over a collection and modify it
> Never iterate over a collection which the iteration
somehow modifies.
Take care, since the iteration can involve various methods and
modifications which may not be obvious!
[:range | range do: [:aNumber | aNumber isPrime
ifFalse: [ range remove: aNumber ]]. range
] value: ((2 to: 20) asOrderedCollection)
an OrderedCollection(2 3 5 7 9 11 13 15 17 19)
© Oscar Nierstrasz
ST — Debugging
6.20
Roadmap
> Common syntactic errors
> Common semantic errors
> Encapsulation errors
> Class/instance errors
> Debugging patterns
© Oscar Nierstrasz
ST — Debugging
6.21
Use of Accessors: Protect your Clients
> The literature says:
— “Access instance
variables using
methods”
– I.e., getters and
setters
SnakesAndLadders>>initialize
…
self squares: OrderedCollection new.
…
SnakesAndLadders>>squares
^ squares
> However, accessor methods should be private by default.
— Put them in the private protocol
> A client could use a public accessor to modify our state
— If we change the representation of squares, client code could
break!
— Instead provide dedicated methods to modify private state
© Oscar Nierstrasz
ST — Debugging
6.22
Copy a collection if you do not want it
modified
> Answer a copy of a collection if you do not want it
modified
— Law of Demeter: never modify a returned collection!
SnakesAndLadders>>squares
^ squares
NastyClient>>break: aSnakesAndLadders
aSnakesAndLadders squares removeFirst
SnakesAndLadders>>squares
^ squares copy
Klimas, et al., Smalltalk with Style
© Oscar Nierstrasz
ST — Debugging
6.23
Collection Accessor method
How do you provide access to an instance
variable that holds a collection?
> Provide methods that are implemented with delegation
to the collection.
— To name the methods, (possibly) add the name of the collection
to the collection messages
SnakesAndLadders>>at: position
^ squares at: position
SnakesAndLadders>>currentPlayer
^ players at: turn
© Oscar Nierstrasz
ST — Debugging
6.24
Enumeration Method
How do you provide safe, general access to
collection elements?
> Implement a method that executes a Block for each
element of the collection
— Name the method by concatenating the name of the collection
and Do:
SnakesAndLadders>>squaresDo: aBlock
squares do: aBlock
SnakesAndLadders>>playersDo: aBlock
players do: aBlock
© Oscar Nierstrasz
ST — Debugging
6.25
Boolean Property Setting Method
How do you set a boolean property?
> Create two methods beginning with “be”.
— One has the property name, the other the negation.
— Add “toggle” if the client doesn’t want to know about the current
state.
switch beOn
switch on: true
© Oscar Nierstrasz
ST — Debugging
6.26
Roadmap
> Common syntactic errors
> Common semantic errors
> Encapsulation errors
> Class/instance errors
> Debugging patterns
© Oscar Nierstrasz
ST — Debugging
6.27
(Re-)Defining classes
> Redefining a class:
— Before creating a class, check if it already exists. This is (sigh) a
weakness of the system
— VisualWorks 7.0 has namespaces so less likely to redefine a
class
Pharo checks this for critical classes.
© Oscar Nierstrasz
ST — Debugging
6.28
Class methods cannot access instance
variables
> Do not try to access instance variables to initialize them
in a class method.
— It is impossible!
— A class method can only access class instance variables and
classVariables.
– Define and invoke an initialize method on instances.
– Or define a Constructor Parameter Method
GamePlayer class>>named: aName
^ self new setName: aName
SnakesAndLadders>>initialize
…
die := Die new.
squares := …
© Oscar Nierstrasz
ST — Debugging
6.29
Do not reference class names
> Do not explicitly reference the class name to create new instances
of the receiver
— This will break subclassing
— Reference self instead
Object subclass: #VeebleFetzer
instanceVariableNames: 'name'
…
VeebleFetzer>>name: aName
name := aName
VeebleFetzer class>>named: aName
^ VeebleFetzer new name: aName
VeebleFetzer named: 'mine'
a VeebleFetzer
VeebleFetzer subclass: #FeebleVetzer
instanceVariableNames: ''
…
FeebleVetzer named: 'mineToo'
a VeebleFetzer
Klimas, et al., Smalltalk with Style
© Oscar Nierstrasz
ST — Debugging
6.30
Returning the class instead of an instance
Returns the class
MyClass (self) and
not the new instance!
MyClass>>new
^ super new initialize
MyClass>>new
super new initialize
Looping initialization
© Oscar Nierstrasz
ST — Debugging
6.31
This example loops!
Behavior>>new
^ self basicNew initialize
Packet class>> new
^self new initialize
In Pharo, new objects are initialized by default!
© Oscar Nierstrasz
ST — Debugging
6.32
Super new initialize
> super new initialize is usually redundant
— In Pharo, this is done automatically (in Behavior)
— Your objects will be initialized twice!
Object subclass: #MyClass
…
MyClass>>initialize
Transcript show: self class name;
show: ' initialized'; cr.
MyClass class>>new
^ super new initialize
© Oscar Nierstrasz
ST — Debugging
6.33
Super initialize
> Don’t forget to initialize any inherited state!
MyClass>>initialize
super initialize.
…
Establish super invariants before
establishing own invariant (as in Java)
© Oscar Nierstrasz
ST — Debugging
6.34
Roadmap
> Common syntactic errors
> Common semantic errors
> Encapsulation errors
> Class/instance errors
> Debugging patterns
© Oscar Nierstrasz
ST — Debugging
6.35
Debug printing
> Basic printing
— You can use the Transcript to display progress
> Optional printing
— Use a global or a class to control printing information
Transcript cr; show: ‘The total= ’, self total printString.
Debug
ifTrue: [Transcript show: self total printString]
Debug > 4
ifTrue: [Transcript show: self total printString]
Debug print: [Transcript show: self total printString]
© Oscar Nierstrasz
ST — Debugging
6.36
Tests are your friends!
> Resist the temptation to write debugging print methods
— Write a test instead!
> Resist the temptation to evaluate ad hoc expressions in
a Workspace
— Write a test instead!
— Tests are reusable
– You will have to spend the effort debugging anyway
– Amortize the investment by coding your debugging effort as tests
© Oscar Nierstrasz
ST — Debugging
6.37
The Inspector is your friend!
> You can inspect anything
— Inspect any expression
— View the printString state
— Interact with any object
— Inspect instance variables
— Navigate through the system
© Oscar Nierstrasz
ST — Debugging
6.38
Use the Inspector to make ad hoc changes
> You can use the Inspector as an ad hoc interface to
modify the state of a running system
— Use this sparingly!
If we change the name
of a GamePlayer, this
will be reflected in the
running system.
© Oscar Nierstrasz
ST — Debugging
6.39
Modify a running system
> You can change the code on the fly while you are
running the system
— Keep the Inspector open
— Keep the Debugger open
> You do not have to:
— Close the application and any views (inspectors, debuggers)
— Implement your changes
— Compile
— Restart
> Just keep everything running while you are
changing things
Well, sometimes you have to …
© Oscar Nierstrasz
ST — Debugging
6.40
Breakpoints
> Send the message self halt to start the debugger at
an arbitrary location
SnakesAndLadders>>playOneMove
| result |
self assert: self invariant.
self halt.
^ self isOver
…
© Oscar Nierstrasz
ST — Debugging
6.41
Debugging
Step over or into
methods to
track the state
© Oscar Nierstrasz
ST — Debugging
6.42
The Debugger is your friend!
Everything is an
object!
> You can:
— Inspect any entity
— Evaluate any code
— Modify code on the fly
Don’t forget:
— Keep the Debugger
open!
© Oscar Nierstrasz
ST — Debugging
6.43
Dangling self halt
> When you have finished debugging, don’t forget to
remove any self halt in the code!
— Running all the tests should catch this!
© Oscar Nierstrasz
ST — Debugging
6.44
The Browser is your friend!
Learn to tinker with the system
> Example:
— How can we browse all methods that send to super?
> We follow a browsing path:
1. “browse”
2. Object>>browse
3. Object>>systemNavigation
4. SystemNavigation
5. SystemNavigation>>browseMethodsWithSourceString:
> First solution:
SystemNavigation default
browseMethodsWithSourceString: 'super'
A bit slow, and
contains many
false negatives
© Oscar Nierstrasz
ST — Debugging
6.45
The Message Name Finder is your friend!
> We continue browsing:
1. SystemNavigation>>browseMethodsWith*
2. SystemNavigation>>browseAllSelect:
> Query the Message Name Finder for “super”
— Yields CompiledMethod>>sendsToSuper
> Better solution:
SystemNavigation default
browseAllSelect: [:method | method sendsToSuper ]
Fast, and accurate!
© Oscar Nierstrasz
ST — Debugging
6.46
What you should know!
When should you explicitly return self?
Why shouldn’t you redefine methods named basic*?
Why are blocks not full closures?
How do you provide access to instance variables that
are collections, without breaking encapsulation?
What is one of the most important uses of super?
How does programming with Smalltalk differ from
programming in a conventional static language?
© Oscar Nierstrasz
ST — Debugging
6.47
Can you answer these questions?
What will happen if you redefine the method class?
When should you define accessors for instance
variables?
How can explicit references to class names make your
application fragile?
Where is the method halt defined?
© Oscar Nierstrasz
ST — Introduction
1.48
Attribution-ShareAlike 3.0 Unported
You are free:
to Share — to copy, distribute and transmit the work
to Remix — to adapt the work
Under the following conditions:
Attribution. You must attribute the work in the manner specified by the author or
licensor (but not in any way that suggests that they endorse you or your use of the
work).
Share Alike. If you alter, transform, or build upon this work, you may distribute the
resulting work only under the same, similar or a compatible license.
For any reuse or distribution, you must make clear to others the license terms of this work.
The best way to do this is with a link to this web page.
Any of the above conditions can be waived if you get permission from the copyright holder.
Nothing in this license impairs or restricts the author's moral rights.
License
http://creativecommons.org/licenses/by-sa/3.0/

Mais conteúdo relacionado

Destaque (20)

Double Dispatch
Double DispatchDouble Dispatch
Double Dispatch
 
Stoop 414-smalltalk elementsofdesign
Stoop 414-smalltalk elementsofdesignStoop 414-smalltalk elementsofdesign
Stoop 414-smalltalk elementsofdesign
 
Stoop 415-design points
Stoop 415-design pointsStoop 415-design points
Stoop 415-design points
 
Stoop 423-some designpatterns
Stoop 423-some designpatternsStoop 423-some designpatterns
Stoop 423-some designpatterns
 
Stoop 413-abstract classes
Stoop 413-abstract classesStoop 413-abstract classes
Stoop 413-abstract classes
 
Stoop ed-class forreuse
Stoop ed-class forreuseStoop ed-class forreuse
Stoop ed-class forreuse
 
12 virtualmachine
12 virtualmachine12 virtualmachine
12 virtualmachine
 
01 intro
01 intro01 intro
01 intro
 
11 bytecode
11 bytecode11 bytecode
11 bytecode
 
15 - Streams
15 - Streams15 - Streams
15 - Streams
 
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)
 
14 - Exceptions
14 - Exceptions14 - Exceptions
14 - Exceptions
 
Stoop 436-strategy
Stoop 436-strategyStoop 436-strategy
Stoop 436-strategy
 
10 - OOP - Inheritance (a)
10 - OOP - Inheritance (a)10 - OOP - Inheritance (a)
10 - OOP - Inheritance (a)
 
Stoop ed-lod
Stoop ed-lodStoop ed-lod
Stoop ed-lod
 
Stoop 434-composite
Stoop 434-compositeStoop 434-composite
Stoop 434-composite
 
Stoop 400 o-metaclassonly
Stoop 400 o-metaclassonlyStoop 400 o-metaclassonly
Stoop 400 o-metaclassonly
 
8 - OOP - Smalltalk Model
8 - OOP - Smalltalk Model8 - OOP - Smalltalk Model
8 - OOP - Smalltalk Model
 
Stoop ed-dual interface
Stoop ed-dual interfaceStoop ed-dual interface
Stoop ed-dual interface
 
09 metaclasses
09 metaclasses09 metaclasses
09 metaclasses
 

Semelhante a 06 debugging

Rails' Next Top Model
Rails' Next Top ModelRails' Next Top Model
Rails' Next Top Model
Adam Keys
 
Java 2 chapter 10 - basic oop in java
Java 2   chapter 10 - basic oop in javaJava 2   chapter 10 - basic oop in java
Java 2 chapter 10 - basic oop in java
let's go to study
 
Scalable CSS You and Your Back-End Coders Can Love - @CSSConf Asia 2014
Scalable CSS You and Your Back-End Coders Can Love - @CSSConf Asia 2014Scalable CSS You and Your Back-End Coders Can Love - @CSSConf Asia 2014
Scalable CSS You and Your Back-End Coders Can Love - @CSSConf Asia 2014
Christian Lilley
 
Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...
Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...
Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...
Lucidworks
 
Smalltalk In A Nutshell
Smalltalk In A NutshellSmalltalk In A Nutshell
Smalltalk In A Nutshell
scg
 

Semelhante a 06 debugging (20)

03 standardclasses
03 standardclasses03 standardclasses
03 standardclasses
 
8 - OOP - Syntax & Messages
8 - OOP - Syntax & Messages8 - OOP - Syntax & Messages
8 - OOP - Syntax & Messages
 
10 reflection
10 reflection10 reflection
10 reflection
 
Rails' Next Top Model
Rails' Next Top ModelRails' Next Top Model
Rails' Next Top Model
 
02 basics
02 basics02 basics
02 basics
 
Day 2
Day 2Day 2
Day 2
 
Java 2 chapter 10 - basic oop in java
Java 2   chapter 10 - basic oop in javaJava 2   chapter 10 - basic oop in java
Java 2 chapter 10 - basic oop in java
 
Runtime Tools
Runtime ToolsRuntime Tools
Runtime Tools
 
mod_rewrite
mod_rewritemod_rewrite
mod_rewrite
 
Debugging VisualWorks
Debugging VisualWorksDebugging VisualWorks
Debugging VisualWorks
 
Scalable CSS You and Your Back-End Coders Can Love - @CSSConf Asia 2014
Scalable CSS You and Your Back-End Coders Can Love - @CSSConf Asia 2014Scalable CSS You and Your Back-End Coders Can Love - @CSSConf Asia 2014
Scalable CSS You and Your Back-End Coders Can Love - @CSSConf Asia 2014
 
Atmosphere Conference 2015: Need for Async: In pursuit of scalable internet-s...
Atmosphere Conference 2015: Need for Async: In pursuit of scalable internet-s...Atmosphere Conference 2015: Need for Async: In pursuit of scalable internet-s...
Atmosphere Conference 2015: Need for Async: In pursuit of scalable internet-s...
 
Solr Troubleshooting - TreeMap approach
Solr Troubleshooting - TreeMap approachSolr Troubleshooting - TreeMap approach
Solr Troubleshooting - TreeMap approach
 
Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...
Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...
Solr Troubleshooting - Treemap Approach: Presented by Alexandre Rafolovitch, ...
 
Script it
Script itScript it
Script it
 
9 - OOP - Smalltalk Classes (a)
9 - OOP - Smalltalk Classes (a)9 - OOP - Smalltalk Classes (a)
9 - OOP - Smalltalk Classes (a)
 
Stoop 300-block optimizationinvw
Stoop 300-block optimizationinvwStoop 300-block optimizationinvw
Stoop 300-block optimizationinvw
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
 
9 - OOP - Smalltalk Classes (b)
9 - OOP - Smalltalk Classes (b)9 - OOP - Smalltalk Classes (b)
9 - OOP - Smalltalk Classes (b)
 
Smalltalk In A Nutshell
Smalltalk In A NutshellSmalltalk In A Nutshell
Smalltalk In A Nutshell
 

Mais de The World of Smalltalk (17)

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
 
05 seaside
05 seaside05 seaside
05 seaside
 
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-subtyping subclassing
Stoop ed-subtyping subclassingStoop ed-subtyping subclassing
Stoop ed-subtyping subclassing
 
Stoop ed-some principles
Stoop ed-some principlesStoop ed-some principles
Stoop ed-some principles
 
Stoop ed-inheritance composition
Stoop ed-inheritance compositionStoop ed-inheritance composition
Stoop ed-inheritance composition
 
Stoop ed-frameworks
Stoop ed-frameworksStoop ed-frameworks
Stoop ed-frameworks
 
Stoop 450-s unit
Stoop 450-s unitStoop 450-s unit
Stoop 450-s unit
 
Stoop 440-adaptor
Stoop 440-adaptorStoop 440-adaptor
Stoop 440-adaptor
 
Stoop 439-decorator
Stoop 439-decoratorStoop 439-decorator
Stoop 439-decorator
 

Último

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
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
heathfieldcps1
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Último (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
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
 
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...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
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
 
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
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 

06 debugging

  • 2. Birds-eye view © Oscar Nierstrasz ST — Introduction 1.2 It can be easier to talk to objects than to read classes — The system is alive. Talk to it. The debugger can be your best friend. Don’t be afraid of it. It can be easier to talk to objects than to read classes — The system is alive. Talk to it. The debugger can be your best friend. Don’t be afraid of it.
  • 3. © Oscar Nierstrasz ST — Debugging 6.3 Roadmap > Common syntactic errors > Common semantic errors > Encapsulation errors > Class/instance errors > Debugging patterns Selected material based on Klimas, et al., Smalltalk with Style. Selected material courtesy Stéphane Ducasse.
  • 4. © Oscar Nierstrasz ST — Debugging 6.4 Roadmap > Common syntactic errors > Common semantic errors > Encapsulation errors > Class/instance errors > Debugging patterns
  • 5. © Oscar Nierstrasz ST — Debugging 6.5 Does not understand self > The error message “does not understand self” usually means that you have forgotten the period at the end of a statement SnakesAndLaddersTest>>testExample self assert: eg currentPlayer = jack. loadedDie roll: 1. eg playOneMove self assert: jack position = 6. self assert: eg currentPlayer = jill. Klimas, et al., Smalltalk with Style
  • 6. © Oscar Nierstrasz ST — Debugging 6.6 Use parentheses in expressions with multiple keyword messages > Do not forget to use parentheses when sending multiple keyword messages in one expression self assert: players includes: aPlayer. self assert: (players includes: aPlayer). Klimas, et al., Smalltalk with Style
  • 7. © Oscar Nierstrasz ST — Debugging 6.7 True vs true > true is the boolean value, True its class. Book>>initialize inLibrary := true Book>>initialize inLibrary := True
  • 8. © Oscar Nierstrasz ST — Debugging 6.8 nil is not a Boolean > nil is not an acceptable receiver for ifTrue:
  • 9. © Oscar Nierstrasz ST — Debugging 6.9 whileTrue > The receiver of whileTrue: and whileTrue must be a block [x<y] whileTrue: [x := x + 3] (x<y) whileTrue: [x := x + 3]
  • 10. © Oscar Nierstrasz ST — Debugging 6.10 Commenting comments > Be careful when commenting out code that contains comments — You may activate some other code that was commented out! MyClass>>doit self doStuff. " self doMoreStuff. "self suicide." self finishUp. " MyClass>>doit self doStuff. self doMoreStuff. "self suicide." self finishUp.
  • 11. © Oscar Nierstrasz ST — Debugging 6.11 Forgetting to return the result > In a method self is returned by default. — Do not forget ^ to return something else! BoardSquare>>isLastSquare position = board lastPosition Returns self (a BoardSquare), not a Boolean!
  • 12. © Oscar Nierstrasz ST — Debugging 6.12 Interesting Return Value When do you explicitly return a value at the end of a method? > Return a value only when you intend for the sender to use the value. — Return self explicitly only if the client is expected to use it! BoardSquare>>destination ^ self Even though self is returned by default we make explicit that this is the value returned.
  • 13. © Oscar Nierstrasz ST — Debugging 6.13 Method arguments are read-only > Do not try to assign a value to a method argument. — Arguments are read only! MyClass>>setName: aString aString := aString, 'Device'. name := aString Won’t compile!
  • 14. © Oscar Nierstrasz ST — Debugging 6.14 self and super are read-only > Do not try to modify self or super
  • 15. © Oscar Nierstrasz ST — Debugging 6.15 Roadmap > Common syntactic errors > Common semantic errors > Encapsulation errors > Class/instance errors > Debugging patterns
  • 16. © Oscar Nierstrasz ST — Debugging 6.16 Do not override basic methods > Never redefine basic-methods — ==, basicNew, basicNew:, basicAt:, basicAt:Put: ... > Never redefine the method class
  • 17. © Oscar Nierstrasz ST — Debugging 6.17 hash and = > Redefine hash whenever you redefine = — Ensure that if a = b then a hash = b hash — Otherwise Sets and Dictionaries may behave incorrectly! Book>>=aBook ^ (self title = aBook title) and: [self author = aBook author] Book>>hash ^self title hash bitXor: self author hash
  • 18. © Oscar Nierstrasz ST — Debugging 6.18 add: returns the argument > add: returns the argument and not the receiver — Use yourself to get the collection back. OrderedCollection new add: 5; add: 6 OrderedCollection new add: 5; add: 6; yourself an OrderedCollection(5 6) 6
  • 19. [:range | range copy do: [:aNumber | aNumber isPrime ifFalse: [ range remove: aNumber ]]. range ] value: ((2 to: 20) asOrderedCollection) First copy the collection an OrderedCollection(2 3 5 7 11 13 17 19) © Oscar Nierstrasz ST — Debugging 6.19 Don’t iterate over a collection and modify it > Never iterate over a collection which the iteration somehow modifies. Take care, since the iteration can involve various methods and modifications which may not be obvious! [:range | range do: [:aNumber | aNumber isPrime ifFalse: [ range remove: aNumber ]]. range ] value: ((2 to: 20) asOrderedCollection) an OrderedCollection(2 3 5 7 9 11 13 15 17 19)
  • 20. © Oscar Nierstrasz ST — Debugging 6.20 Roadmap > Common syntactic errors > Common semantic errors > Encapsulation errors > Class/instance errors > Debugging patterns
  • 21. © Oscar Nierstrasz ST — Debugging 6.21 Use of Accessors: Protect your Clients > The literature says: — “Access instance variables using methods” – I.e., getters and setters SnakesAndLadders>>initialize … self squares: OrderedCollection new. … SnakesAndLadders>>squares ^ squares > However, accessor methods should be private by default. — Put them in the private protocol > A client could use a public accessor to modify our state — If we change the representation of squares, client code could break! — Instead provide dedicated methods to modify private state
  • 22. © Oscar Nierstrasz ST — Debugging 6.22 Copy a collection if you do not want it modified > Answer a copy of a collection if you do not want it modified — Law of Demeter: never modify a returned collection! SnakesAndLadders>>squares ^ squares NastyClient>>break: aSnakesAndLadders aSnakesAndLadders squares removeFirst SnakesAndLadders>>squares ^ squares copy Klimas, et al., Smalltalk with Style
  • 23. © Oscar Nierstrasz ST — Debugging 6.23 Collection Accessor method How do you provide access to an instance variable that holds a collection? > Provide methods that are implemented with delegation to the collection. — To name the methods, (possibly) add the name of the collection to the collection messages SnakesAndLadders>>at: position ^ squares at: position SnakesAndLadders>>currentPlayer ^ players at: turn
  • 24. © Oscar Nierstrasz ST — Debugging 6.24 Enumeration Method How do you provide safe, general access to collection elements? > Implement a method that executes a Block for each element of the collection — Name the method by concatenating the name of the collection and Do: SnakesAndLadders>>squaresDo: aBlock squares do: aBlock SnakesAndLadders>>playersDo: aBlock players do: aBlock
  • 25. © Oscar Nierstrasz ST — Debugging 6.25 Boolean Property Setting Method How do you set a boolean property? > Create two methods beginning with “be”. — One has the property name, the other the negation. — Add “toggle” if the client doesn’t want to know about the current state. switch beOn switch on: true
  • 26. © Oscar Nierstrasz ST — Debugging 6.26 Roadmap > Common syntactic errors > Common semantic errors > Encapsulation errors > Class/instance errors > Debugging patterns
  • 27. © Oscar Nierstrasz ST — Debugging 6.27 (Re-)Defining classes > Redefining a class: — Before creating a class, check if it already exists. This is (sigh) a weakness of the system — VisualWorks 7.0 has namespaces so less likely to redefine a class Pharo checks this for critical classes.
  • 28. © Oscar Nierstrasz ST — Debugging 6.28 Class methods cannot access instance variables > Do not try to access instance variables to initialize them in a class method. — It is impossible! — A class method can only access class instance variables and classVariables. – Define and invoke an initialize method on instances. – Or define a Constructor Parameter Method GamePlayer class>>named: aName ^ self new setName: aName SnakesAndLadders>>initialize … die := Die new. squares := …
  • 29. © Oscar Nierstrasz ST — Debugging 6.29 Do not reference class names > Do not explicitly reference the class name to create new instances of the receiver — This will break subclassing — Reference self instead Object subclass: #VeebleFetzer instanceVariableNames: 'name' … VeebleFetzer>>name: aName name := aName VeebleFetzer class>>named: aName ^ VeebleFetzer new name: aName VeebleFetzer named: 'mine' a VeebleFetzer VeebleFetzer subclass: #FeebleVetzer instanceVariableNames: '' … FeebleVetzer named: 'mineToo' a VeebleFetzer Klimas, et al., Smalltalk with Style
  • 30. © Oscar Nierstrasz ST — Debugging 6.30 Returning the class instead of an instance Returns the class MyClass (self) and not the new instance! MyClass>>new ^ super new initialize MyClass>>new super new initialize
  • 31. Looping initialization © Oscar Nierstrasz ST — Debugging 6.31 This example loops! Behavior>>new ^ self basicNew initialize Packet class>> new ^self new initialize In Pharo, new objects are initialized by default!
  • 32. © Oscar Nierstrasz ST — Debugging 6.32 Super new initialize > super new initialize is usually redundant — In Pharo, this is done automatically (in Behavior) — Your objects will be initialized twice! Object subclass: #MyClass … MyClass>>initialize Transcript show: self class name; show: ' initialized'; cr. MyClass class>>new ^ super new initialize
  • 33. © Oscar Nierstrasz ST — Debugging 6.33 Super initialize > Don’t forget to initialize any inherited state! MyClass>>initialize super initialize. … Establish super invariants before establishing own invariant (as in Java)
  • 34. © Oscar Nierstrasz ST — Debugging 6.34 Roadmap > Common syntactic errors > Common semantic errors > Encapsulation errors > Class/instance errors > Debugging patterns
  • 35. © Oscar Nierstrasz ST — Debugging 6.35 Debug printing > Basic printing — You can use the Transcript to display progress > Optional printing — Use a global or a class to control printing information Transcript cr; show: ‘The total= ’, self total printString. Debug ifTrue: [Transcript show: self total printString] Debug > 4 ifTrue: [Transcript show: self total printString] Debug print: [Transcript show: self total printString]
  • 36. © Oscar Nierstrasz ST — Debugging 6.36 Tests are your friends! > Resist the temptation to write debugging print methods — Write a test instead! > Resist the temptation to evaluate ad hoc expressions in a Workspace — Write a test instead! — Tests are reusable – You will have to spend the effort debugging anyway – Amortize the investment by coding your debugging effort as tests
  • 37. © Oscar Nierstrasz ST — Debugging 6.37 The Inspector is your friend! > You can inspect anything — Inspect any expression — View the printString state — Interact with any object — Inspect instance variables — Navigate through the system
  • 38. © Oscar Nierstrasz ST — Debugging 6.38 Use the Inspector to make ad hoc changes > You can use the Inspector as an ad hoc interface to modify the state of a running system — Use this sparingly! If we change the name of a GamePlayer, this will be reflected in the running system.
  • 39. © Oscar Nierstrasz ST — Debugging 6.39 Modify a running system > You can change the code on the fly while you are running the system — Keep the Inspector open — Keep the Debugger open > You do not have to: — Close the application and any views (inspectors, debuggers) — Implement your changes — Compile — Restart > Just keep everything running while you are changing things Well, sometimes you have to …
  • 40. © Oscar Nierstrasz ST — Debugging 6.40 Breakpoints > Send the message self halt to start the debugger at an arbitrary location SnakesAndLadders>>playOneMove | result | self assert: self invariant. self halt. ^ self isOver …
  • 41. © Oscar Nierstrasz ST — Debugging 6.41 Debugging Step over or into methods to track the state
  • 42. © Oscar Nierstrasz ST — Debugging 6.42 The Debugger is your friend! Everything is an object! > You can: — Inspect any entity — Evaluate any code — Modify code on the fly Don’t forget: — Keep the Debugger open!
  • 43. © Oscar Nierstrasz ST — Debugging 6.43 Dangling self halt > When you have finished debugging, don’t forget to remove any self halt in the code! — Running all the tests should catch this!
  • 44. © Oscar Nierstrasz ST — Debugging 6.44 The Browser is your friend! Learn to tinker with the system > Example: — How can we browse all methods that send to super? > We follow a browsing path: 1. “browse” 2. Object>>browse 3. Object>>systemNavigation 4. SystemNavigation 5. SystemNavigation>>browseMethodsWithSourceString: > First solution: SystemNavigation default browseMethodsWithSourceString: 'super' A bit slow, and contains many false negatives
  • 45. © Oscar Nierstrasz ST — Debugging 6.45 The Message Name Finder is your friend! > We continue browsing: 1. SystemNavigation>>browseMethodsWith* 2. SystemNavigation>>browseAllSelect: > Query the Message Name Finder for “super” — Yields CompiledMethod>>sendsToSuper > Better solution: SystemNavigation default browseAllSelect: [:method | method sendsToSuper ] Fast, and accurate!
  • 46. © Oscar Nierstrasz ST — Debugging 6.46 What you should know! When should you explicitly return self? Why shouldn’t you redefine methods named basic*? Why are blocks not full closures? How do you provide access to instance variables that are collections, without breaking encapsulation? What is one of the most important uses of super? How does programming with Smalltalk differ from programming in a conventional static language?
  • 47. © Oscar Nierstrasz ST — Debugging 6.47 Can you answer these questions? What will happen if you redefine the method class? When should you define accessors for instance variables? How can explicit references to class names make your application fragile? Where is the method halt defined?
  • 48. © Oscar Nierstrasz ST — Introduction 1.48 Attribution-ShareAlike 3.0 Unported You are free: to Share — to copy, distribute and transmit the work to Remix — to adapt the work Under the following conditions: Attribution. You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under the same, similar or a compatible license. For any reuse or distribution, you must make clear to others the license terms of this work. The best way to do this is with a link to this web page. Any of the above conditions can be waived if you get permission from the copyright holder. Nothing in this license impairs or restricts the author's moral rights. License http://creativecommons.org/licenses/by-sa/3.0/

Notas do Editor

  1. range := (2 to: 100) asOrderedCollection. range do: [:aNumber | aNumber isPrime ifFalse: [ range remove: aNumber ] ]. range “Gives a broken result” NB: In this example, a functional solution is even better range select: [:aNumber | aNumber isPrime ].