SlideShare ist ein Scribd-Unternehmen logo
1 von 62
4. Smalltalk Coding Idioms
Birds-eye view
© Oscar Nierstrasz
ST — Introduction
1.2
Distribute responsibility — in a well-designed object-
oriented system you will typically find many, small,
carefully named methods.
This promotes fluent interfaces, reuse, and maintainability.
Distribute responsibility — in a well-designed object-
oriented system you will typically find many, small,
carefully named methods.
This promotes fluent interfaces, reuse, and maintainability.
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.3
Roadmap
> Snakes and Ladders — Cascade and Yourself
> Lots of Little Methods
> Establishing class invariants
> Printing state
> Self and super
> Accessors and Query methods
> Decomposing and naming methods
Selected material based on: Kent Beck, Smalltalk Best Practice Patterns, Prentice-Hall, 1997.
Selected material courtesy Stéphane Ducasse
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.4
Roadmap
> Snakes and Ladders — Cascade and Yourself
> Lots of Little Methods
> Establishing class invariants
> Printing state
> Self and super
> Accessors and Query methods
> Decomposing and naming methods
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.5
Snakes and Ladders
See: http://en.wikipedia.org/wiki/Snakes_and_ladders
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.6
Scripting a use case
SnakesAndLadders class>>example
"self example playToEnd"
^ (self new)
add: FirstSquare new;
add: (LadderSquare forward: 4);
add: BoardSquare new;
add: BoardSquare new;
add: BoardSquare new;
add: BoardSquare new;
add: (LadderSquare forward: 2);
add: BoardSquare new;
add: BoardSquare new;
add: BoardSquare new;
add: (SnakeSquare back: 6);
add: BoardSquare new;
join: (GamePlayer named: 'Jack');
join: (GamePlayer named: 'Jill');
yourself
We need a way to:
—Construct the board
—Add some players
—Play the game
The example script
helps us to identify
responsibilities,
classes and needed
interfaces
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.7
Cascade
How do you format multiple messages to the same
receiver?
> Use a Cascade. Separate the messages with a
semicolon. Put each message on its own line and indent
one tab. Only use Cascades for messages with zero or
one argument.
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.8
Yourself
How can you use the value of a Cascade if the
last message doesn’t return the receiver of the
message?
> Append the message yourself to the Cascade.
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.9
About yourself
> The effect of a cascade is to send all messages to the
receiver of the first message in the cascade
— self new add: FirstSquare new; …
> But the value of the cascade is the value returned by the
last message sent
> To get the receiver as a result we must send the
additional message yourself
(OrderedCollection with: 1) add: 25; add: 35
(OrderedCollection with: 1) add: 25; add: 35; yourself
35
an OrderedCollection(1 25 35)
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.10
Yourself implementation
> The implementation of yourself is trivial, and occurs
just once in the system:
Object>>yourself
^ self
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.11
Do we need yourself here?
SnakesAndLadders class>>example
"self example playToEnd"
^ self new
add: FirstSquare new;
…
join: (GamePlayer named: 'Jill');
yourself
Could be. Don’t really know yet …
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.12
Roadmap
> Snakes and Ladders — Cascade and Yourself
> Lots of Little Methods
> Establishing class invariants
> Printing state
> Self and super
> Accessors and Query methods
> Decomposing and naming methods
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.13
Distributing responsibilities
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.14
Lots of Little Methods
> Once and only once
— “In a program written with good style, everything is said once
and only once.”
> Lots of little pieces
— “Good code invariably has small methods and small objects.
Only by factoring the system into many small pieces of state
and function can you hope to satisfy the ‘once and only once’
rule.”
– Kent Beck, Smalltalk Best Practice Patterns
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.15
Class responsibilities and collaborations
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.16
Class Comments
> Add a comment to each class indicating its
responsibilities
— Optionally include sample code to run an example
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.17
Inheritance in Smalltalk
> Single inheritance
> Static for the instance variables
— Instance variables are collected from the class and its direct and
indirect superclasses.
> Dynamic for the methods
— Methods are looked up at run-time depending on the dynamic
type of the receiver.
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.18
Roadmap
> Snakes and Ladders — Cascade and Yourself
> Lots of Little Methods
> Establishing class invariants
> Printing state
> Self and super
> Accessors and Query methods
> Decomposing and naming methods
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.19
Creating classes
> A class is created by sending a message to its
superclass
Object subclass: #SnakesAndLadders
instanceVariableNames: 'players squares turn die over'
classVariableNames: ''
poolDictionaries: ''
category: 'SnakesAndLadders'
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.20
Named Instance Variables
> Instance variables:
— Begin with a lowercase letter
— Must be explicitly declared: a list of instance variables
— Name should be unique in the inheritance chain
— Default value of instance variable is nil
— Private to the instance, not the class (in contrast to Java)
— Can be accessed by all the methods of the class and its subclasses
— Instance variables cannot be accessed by class methods.
— The clients must use accessors to access an instance variable.
Design Hint:
— Do not directly access instance variables
of a superclass from subclass methods.
This way classes are not strongly linked.
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.21
Problem — how to initialize objects?
Problem
> To create a new instance of a class, the message new
must be sent to the class
— But the class (an object) cannot access the instance variables
of the new object (!)
— So how can the class establish the invariant of the new object?
Solution
> Provide instance-side initialization methods in the
protocol initialize-release that can be used to create a
valid instance
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.22
Explicit Initialization
How do you initialize instance variables to their
default values?
> Implement a method initialize that sets all the
values explicitly.
—Override the class message new to invoke it on new instances
SnakesAndLadders>>initialize
super initialize.
die := Die new.
squares := OrderedCollection new.
players := OrderedCollection new.
turn := 1.
over := false.
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.23
> In Pharo, the method new calls initialize by default.
> NB: You can override new, but you should never
override basicNew!
> Every metaclass ultimately inherits from Behavior
– More on this later …
Behavior>>new
^ self basicNew initialize
Who calls initialize?
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.24
Ordered Collection
How do you code Collections whose size can’t be
determined when they are created?
> Use an OrderedCollection as your default
dynamically sized Collection.
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.25
Invariants
> If your objects have non-trivial invariants, or if they can
only be initialized incrementally, consider explicitly
implementing an invariant-checking method:
SnakesAndLadders>>invariant
"Should also check that snakes and ladders
lead to ordinary squares, and do not bounce
past the beginning or end of the board."
^ squares size > 1
and: [players size > 1]
and: [turn >= 1]
and: [turn <= players size]
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.26
Contracts
> Apply Design by Contract
— Aid debugging by checking
– Pre-conditions to public methods
– Non-trivial invariants
– Non-trivial post-conditions
BoardSquare>>nextSquare
self assert: self isLastSquare not.
^ board at: position + 1
SnakesAndLadders>>reset
die := Die new.
turn := 1.
over := false.
players do: [:each | each moveTo: self firstSquare ].
self assert: self invariant.
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.27
Constructor Method
How do you represent instance creation?
> Provide methods in the class side “instance creation”
protocol that create well-formed instances. Pass all
required parameters to them.
LadderSquare class>>forward: number
^ self new setForward: number
SnakeSquare class>>back: number
^ self new setBack: number
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.28
Constructor Parameter Method
How do you set instance variables from the
parameters to a Constructor Method?
> Code a single method that sets all the variables. Preface
its name with “set”, then the names of the variables.
SnakeSquare>>setBack: aNumber
back := aNumber.
BoardSquare>>setPosition: aNumber board: aBoard
position := aNumber.
board := aBoard
LadderSquare>>setForward: aNumber
forward := aNumber.
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.29
Roadmap
> Snakes and Ladders — Cascade and Yourself
> Lots of Little Methods
> Establishing class invariants
> Printing state
> Self and super
> Accessors and Query methods
> Decomposing and naming methods
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.30
Viewing the game state
SnakesAndLadders example inspect
In order to provide a simple way to monitor the game state and to
ease debugging, we need a textual view of the game
Not very informative
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.31
Debug Printing Method
How do you code the default printing method?
— There are two audiences:
– you (wanting a lot of information)
– your clients (wanting only external properties)
> Override printOn: to provide information about
object’s structure to the programmer
— Put printing methods in the “printing” protocol
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.32
Implementing printOn:
SnakesAndLadders>>printOn: aStream
squares do: [:each | each printOn: aStream]
BoardSquare>>printOn: aStream
aStream nextPutAll: '[', position printString, self contents, ']'
LadderSquare>>printOn: aStream
super printOn: aStream.
aStream nextPutAll: forward asString, '+>'
SnakeSquare>>printOn: aStream
aStream nextPutAll: '<-', back asString.
super printOn: aStream
GamePlayer>>printOn: aStream
aStream nextPutAll: name
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.33
Viewing the game state
SnakesAndLadders example inspect
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.34
Interacting with the game
With a bit of care, the Inspector can serve as a basic GUI
for objects we are developing
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.35
Roadmap
> Snakes and Ladders — Cascade and Yourself
> Lots of Little Methods
> Establishing class invariants
> Printing state
> Self and super
> Accessors and Query methods
> Decomposing and naming methods
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.36
Super
How can you invoke superclass behaviour?
> Invoke code in a superclass explicitly by sending a
message to super instead of self.
— The method corresponding to the message will be found in the
superclass of the class implementing the sending method.
— Always check code using super carefully. Change super to
self if doing so does not change how the code executes!
— Caveat: If subclasses are expected to call super, consider
using a Template Method instead!
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.37
Extending Super
How do you add to the implementation of a
method inherited from a superclass?
> Override the method and send a message to super in
the overriding method.
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.38
A closer look at super
> Snake and Ladder both extend the printOn: method of
their superclass
BoardSquare>>printOn: aStream
aStream nextPutAll:
'[', position printString, self contents, ']'
LadderSquare>>printOn: aStream
super printOn: aStream.
aStream nextPutAll: forward asString, '+>'
SnakeSquare>>printOn: aStream
aStream nextPutAll: '<-', back asString.
super printOn: aStream.
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.39
Normal method lookup
Two step process:
— Lookup starts in the class of the
receiver (an object)
1. If the method is defined in the
method dictionary, it is used
2. Else, the search continues in the
superclass
— If no method is found, this is an
error …
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.40
Message not understood
NB: The default implementation of
doesNotUnderstand: may be
overridden by any class.
When method lookup fails, an error message is sent
to the object and lookup starts again with this new
message.
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.41
Super
> Super modifies the usual method lookup to start in the
superclass of the class whose method sends to super
— NB: lookup does not start in the superclass of the receiver!
– Cf. C new bar on next slide
— Super is not the superclass!
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.42
Super sends
A new bar
B new bar
C new bar
D new bar
E new bar
'Abar'
'Abar & Afoo'
'Abar & Cfoo'
'Abar & Cfoo & Cfoo'
'Abar & Efoo & Cfoo'
NB: It is usually a mistake to
super-send to a different method.
D>>bar should probably do self
foo, not super foo!
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.43
Self and super
Sending to self is
always dynamic
Sending to super
is always static
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.44
Roadmap
> Snakes and Ladders — Cascade and Yourself
> Lots of Little Methods
> Establishing class invariants
> Printing state
> Self and super
> Accessors and Query methods
> Decomposing and naming methods
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.45
SnakesAndLaddersTest>>setUp
eg := self example.
loadedDie := LoadedDie new.
eg setDie: loadedDie.
jack := eg players first.
jill := eg players last.
Testing
> In order to enable deterministic test scenarios, we need
to fix the game with a loaded die!
– The loaded die will turn up the numbers we tell it to.
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.46
Getting Method
How do you provide access to an instance
variable?
> Provide a method that returns the value of the variable.
— Give it the same name as the variable.
– NB: not called “get…”
LoadedDie>>roll
self assert: roll notNil.
^ roll
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.47
Setting Method
How do you change the value of an instance
variable?
> Provide a method with the same name as the variable.
— Have it take a single parameter, the value to be set.
– NB: not called “set…”
LoadedDie>>roll: aNumber
self assert: ((1 to: 6) includes: aNumber).
roll := aNumber.
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.48
Testing the state of objects
> To enable tests, we will need to implement various
query methods
SnakesAndLaddersTest>>testStartPosition
self assert: eg lastPosition = 12.
self assert: eg isNotOver.
self assert: eg currentPlayer = jack.
self assert: eg firstSquare isFirstSquare.
self assert: eg firstSquare isLastSquare not.
self assert: eg firstSquare position = 1.
self assert: eg firstSquare isOccupied.
self assert: (eg at: eg lastPosition) isFirstSquare not.
self assert: (eg at: eg lastPosition) isLastSquare.
self assert: (eg at: eg lastPosition) position = 12.
self assert: (eg at: eg lastPosition) isOccupied not.
self assert: jack name = 'Jack'.
self assert: jill name = 'Jill'.
self assert: jack position = 1.
self assert: jill position = 1.
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.49
Query Method
How do you represent testing a property of an
object?
> Provide a method that returns a Boolean.
— Name it by prefacing the property name with a form of “be”
— is, was, will etc.
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.50
Some query methods
SnakesAndLadders>>isNotOver
^ self isOver not
BoardSquare>>isFirstSquare
^ position = 1
BoardSquare>>isLastSquare
^ position = board lastPosition
BoardSquare>>isOccupied
^ player notNil
FirstSquare>>isOccupied
^ players size > 0
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.51
A Test Scenario
SnakesAndLaddersTest>>testExample
self assert: eg currentPlayer = jack.
loadedDie roll: 1.
eg playOneMove.
self assert: jack position = 6.
…
self assert: eg currentPlayer = jack.
loadedDie roll: 2.
eg playOneMove.
self assert: jack position = 12.
self assert: eg isOver.
> To carry out a test scenario, we need to play a fixed
game instead of a random one.
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.52
Roadmap
> Snakes and Ladders — Cascade and Yourself
> Lots of Little Methods
> Establishing class invariants
> Printing state
> Self and super
> Accessors and Query methods
> Decomposing and naming methods
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.53
Composed Method
How do you divide a program into methods?
> Divide your program into methods that perform one
identifiable task.
— Keep all of the operations in a method at the same level of
abstraction.
— This will naturally result in programs with many small methods,
each a few lines long.
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.54
Method size
> Most methods will be small and self-documenting
— Few exceptions:
– Complex algorithms
– Scripts (configurations)
– Tests
SnakesAndLadders>>playOneMove
| result |
self assert: self invariant.
^ self isOver
ifTrue: ['The game is over']
ifFalse: [
result :=
(self currentPlayer moveWith: die),
self checkResult.
self upDateTurn.
result ]
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.55
Snakes and Ladders methods
• 68 methods
• only 7 are more than 6 LOC
(including comments!)
— 1 of these is the “main” method
— the other 6 are test methods
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.56
Intention Revealing Message
How do you communicate your intent when the
implementation is simple?
> Send a message to self.
— Name the message so it communicates what is to be done
rather than how it is to be done.
— Code a simple method for the message
SnakesAndLadders>>currentPlayer
^ players at: turn
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.57
Intention Revealing Selector
What do you name a method?
> Name methods after what they accomplish.
— Well-named methods can eliminate the need for most
comments
SnakesAndLadders>>upDateTurn
turn := 1 + (turnplayers size).
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.58
Some Naming Conventions
> Use imperative verbs for methods performing an action
— moveTo:, leaveCurrentSquare, playOneMove
> Prefix testing methods (i.e., that return a boolean) with
“is” or “has”
— isNil, isNotOver, isOccupied
> Prefix converting methods with “as”
— asString
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.59
Message Comment
How do you comment methods?
> Communicate important information that is not obvious
from the code in a comment at the beginning of the
method.
— Method dependencies
— To-do items
— Sample code to execute
SnakesAndLadders>>playToEnd
"SnakesAndLadders example playToEnd"
…
Hint: comments may be code smells in disguise!
— Try to refactor code and rename methods to get rid of comments!
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.60
What you should know!
What does yourself return? Why is it needed?
How is a new instance of a class initialized?
When should you implement invariants and
preconditions?
What happens when we evaluate an expression with
“print it”?
Why should a method never send super a different
message?
How is super static and self dynamic?
How do you make your code self-documenting?
© Oscar Nierstrasz
ST — Smalltalk Coding Idioms
4.61
Can you answer these questions?
When should you override new?
If instance variables are really private, why can we see
them with an inspector?
When does self = super?
When does super = self?
Which classes implement assert: ?
What does self refer to in the method
SnakesAndLadders class>>example?
© Oscar Nierstrasz
ST — Introduction
1.62
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/

Weitere ähnliche Inhalte

Was ist angesagt?

4 - OOP - Taste of Smalltalk (Tamagoshi)
4 - OOP - Taste of Smalltalk (Tamagoshi)4 - OOP - Taste of Smalltalk (Tamagoshi)
4 - OOP - Taste of Smalltalk (Tamagoshi)
The World of Smalltalk
 
4 - OOP - Taste of Smalltalk (VisualWorks)
4 - OOP - Taste of Smalltalk (VisualWorks)4 - OOP - Taste of Smalltalk (VisualWorks)
4 - OOP - Taste of Smalltalk (VisualWorks)
The World of Smalltalk
 

Was ist angesagt? (20)

4 - OOP - Taste of Smalltalk (Tamagoshi)
4 - OOP - Taste of Smalltalk (Tamagoshi)4 - OOP - Taste of Smalltalk (Tamagoshi)
4 - OOP - Taste of Smalltalk (Tamagoshi)
 
Stoop 423-smalltalk idioms
Stoop 423-smalltalk idiomsStoop 423-smalltalk idioms
Stoop 423-smalltalk idioms
 
Stoop 414-smalltalk elementsofdesign
Stoop 414-smalltalk elementsofdesignStoop 414-smalltalk elementsofdesign
Stoop 414-smalltalk elementsofdesign
 
8 - OOP - Smalltalk Syntax
8 - OOP - Smalltalk Syntax8 - OOP - Smalltalk Syntax
8 - OOP - Smalltalk Syntax
 
8 - OOP - Syntax & Messages
8 - OOP - Syntax & Messages8 - OOP - Syntax & Messages
8 - OOP - Syntax & Messages
 
06 debugging
06 debugging06 debugging
06 debugging
 
4 - OOP - Taste of Smalltalk (Squeak)
4 - OOP - Taste of Smalltalk (Squeak)4 - OOP - Taste of Smalltalk (Squeak)
4 - OOP - Taste of Smalltalk (Squeak)
 
13 traits
13 traits13 traits
13 traits
 
Stoop ed-class forreuse
Stoop ed-class forreuseStoop ed-class forreuse
Stoop ed-class forreuse
 
Stoop ed-some principles
Stoop ed-some principlesStoop ed-some principles
Stoop ed-some principles
 
Stoop sed-sharing ornot
Stoop sed-sharing ornotStoop sed-sharing ornot
Stoop sed-sharing ornot
 
9 - OOP - Smalltalk Classes (a)
9 - OOP - Smalltalk Classes (a)9 - OOP - Smalltalk Classes (a)
9 - OOP - Smalltalk Classes (a)
 
9 - OOP - Smalltalk Classes (b)
9 - OOP - Smalltalk Classes (b)9 - OOP - Smalltalk Classes (b)
9 - OOP - Smalltalk Classes (b)
 
Rails Model Basics
Rails Model BasicsRails Model Basics
Rails Model Basics
 
4 - OOP - Taste of Smalltalk (VisualWorks)
4 - OOP - Taste of Smalltalk (VisualWorks)4 - OOP - Taste of Smalltalk (VisualWorks)
4 - OOP - Taste of Smalltalk (VisualWorks)
 
Pg py-and-squid-pypgday
Pg py-and-squid-pypgdayPg py-and-squid-pypgday
Pg py-and-squid-pypgday
 
Getting Started with OpenSplice and Esper
Getting Started with OpenSplice and EsperGetting Started with OpenSplice and Esper
Getting Started with OpenSplice and Esper
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritance
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
2 - OOP
2 - OOP2 - OOP
2 - OOP
 

Andere mochten auch

Andere mochten auch (20)

1 - OOP
1 - OOP1 - OOP
1 - OOP
 
6 - OOP - LAN Example
6 - OOP - LAN Example6 - OOP - LAN Example
6 - OOP - LAN Example
 
Concurrency in Smalltalk -- Beyond Threads
Concurrency in Smalltalk -- Beyond ThreadsConcurrency in Smalltalk -- Beyond Threads
Concurrency in Smalltalk -- Beyond Threads
 
Stoop 421-design heuristics
Stoop 421-design heuristicsStoop 421-design heuristics
Stoop 421-design heuristics
 
7 - OOP - OO Concepts
7 - OOP - OO Concepts7 - OOP - OO Concepts
7 - OOP - OO Concepts
 
Stoop ed-frameworks
Stoop ed-frameworksStoop ed-frameworks
Stoop ed-frameworks
 
15 - Streams
15 - Streams15 - Streams
15 - Streams
 
Stoop 416-lsp
Stoop 416-lspStoop 416-lsp
Stoop 416-lsp
 
10 - OOP - Inheritance (a)
10 - OOP - Inheritance (a)10 - OOP - Inheritance (a)
10 - OOP - Inheritance (a)
 
Stoop 440-adaptor
Stoop 440-adaptorStoop 440-adaptor
Stoop 440-adaptor
 
Stoop 436-strategy
Stoop 436-strategyStoop 436-strategy
Stoop 436-strategy
 
Stoop 439-decorator
Stoop 439-decoratorStoop 439-decorator
Stoop 439-decorator
 
Stoop ed-inheritance composition
Stoop ed-inheritance compositionStoop ed-inheritance composition
Stoop ed-inheritance composition
 
Stoop 450-s unit
Stoop 450-s unitStoop 450-s unit
Stoop 450-s unit
 
Stoop ed-lod
Stoop ed-lodStoop ed-lod
Stoop ed-lod
 
Stoop 400 o-metaclassonly
Stoop 400 o-metaclassonlyStoop 400 o-metaclassonly
Stoop 400 o-metaclassonly
 
Stoop 390-instruction stream
Stoop 390-instruction streamStoop 390-instruction stream
Stoop 390-instruction stream
 
Stoop ed-unit ofreuse
Stoop ed-unit ofreuseStoop ed-unit ofreuse
Stoop ed-unit ofreuse
 
Stoop 303-advanced blocks
Stoop 303-advanced blocksStoop 303-advanced blocks
Stoop 303-advanced blocks
 
Stoop 437-proxy
Stoop 437-proxyStoop 437-proxy
Stoop 437-proxy
 

Ähnlich wie 04 idioms

Smalltalk In A Nutshell
Smalltalk In A NutshellSmalltalk In A Nutshell
Smalltalk In A Nutshell
scg
 
27.2.9 lab regular expression tutorial
27.2.9 lab   regular expression tutorial27.2.9 lab   regular expression tutorial
27.2.9 lab regular expression tutorial
Freddy Buenaño
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
Skills Matter
 
Pharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source SmalltalkPharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source Smalltalk
Serge Stinckwich
 

Ähnlich wie 04 idioms (20)

09 metaclasses
09 metaclasses09 metaclasses
09 metaclasses
 
Class 32: Interpreters
Class 32: InterpretersClass 32: Interpreters
Class 32: Interpreters
 
99 questions
99 questions99 questions
99 questions
 
Stoop 305-reflective programming5
Stoop 305-reflective programming5Stoop 305-reflective programming5
Stoop 305-reflective programming5
 
Bioinformatics v2014 wim_vancriekinge
Bioinformatics v2014 wim_vancriekingeBioinformatics v2014 wim_vancriekinge
Bioinformatics v2014 wim_vancriekinge
 
VUB Brussels Lecture 2019: Advanced Reflection: MetaLinks
VUB Brussels Lecture 2019: Advanced Reflection: MetaLinksVUB Brussels Lecture 2019: Advanced Reflection: MetaLinks
VUB Brussels Lecture 2019: Advanced Reflection: MetaLinks
 
Smalltalk In A Nutshell
Smalltalk In A NutshellSmalltalk In A Nutshell
Smalltalk In A Nutshell
 
Lecture: "Advanced Reflection: MetaLinks"
Lecture: "Advanced Reflection: MetaLinks"Lecture: "Advanced Reflection: MetaLinks"
Lecture: "Advanced Reflection: MetaLinks"
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service Clients
 
Lecture. Advanced Reflection: MetaLinks
Lecture. Advanced Reflection: MetaLinksLecture. Advanced Reflection: MetaLinks
Lecture. Advanced Reflection: MetaLinks
 
Stoop 304-metaclasses
Stoop 304-metaclassesStoop 304-metaclasses
Stoop 304-metaclasses
 
Refactoring
RefactoringRefactoring
Refactoring
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San Francisco
 
27.2.9 lab regular expression tutorial
27.2.9 lab   regular expression tutorial27.2.9 lab   regular expression tutorial
27.2.9 lab regular expression tutorial
 
Demystifying NLP Transformers: Understanding the Power and Architecture behin...
Demystifying NLP Transformers: Understanding the Power and Architecture behin...Demystifying NLP Transformers: Understanding the Power and Architecture behin...
Demystifying NLP Transformers: Understanding the Power and Architecture behin...
 
Building reactive systems with Akka
Building reactive systems with AkkaBuilding reactive systems with Akka
Building reactive systems with Akka
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
 
Pharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source SmalltalkPharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source Smalltalk
 
Ml9 introduction to-unsupervised_learning_and_clustering_methods
Ml9 introduction to-unsupervised_learning_and_clustering_methodsMl9 introduction to-unsupervised_learning_and_clustering_methods
Ml9 introduction to-unsupervised_learning_and_clustering_methods
 
Getting Started with Apache Cassandra by Junior Evangelist Rebecca Mills
Getting Started with Apache Cassandra by Junior Evangelist Rebecca MillsGetting Started with Apache Cassandra by Junior Evangelist Rebecca Mills
Getting Started with Apache Cassandra by Junior Evangelist Rebecca Mills
 

Mehr von The World of Smalltalk (8)

05 seaside canvas
05 seaside canvas05 seaside canvas
05 seaside canvas
 
05 seaside
05 seaside05 seaside
05 seaside
 
01 intro
01 intro01 intro
01 intro
 
Stoop sed-smells
Stoop sed-smellsStoop sed-smells
Stoop sed-smells
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
Stoop metaclasses
Stoop metaclassesStoop metaclasses
Stoop metaclasses
 
Stoop ed-subtyping subclassing
Stoop ed-subtyping subclassingStoop ed-subtyping subclassing
Stoop ed-subtyping subclassing
 
Stoop ed-dual interface
Stoop ed-dual interfaceStoop ed-dual interface
Stoop ed-dual interface
 

Kürzlich hochgeladen

Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
fonyou31
 
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
 
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
kauryashika82
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
SoniaTolstoy
 

Kürzlich hochgeladen (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
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
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
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
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
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 ...
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 

04 idioms

  • 2. Birds-eye view © Oscar Nierstrasz ST — Introduction 1.2 Distribute responsibility — in a well-designed object- oriented system you will typically find many, small, carefully named methods. This promotes fluent interfaces, reuse, and maintainability. Distribute responsibility — in a well-designed object- oriented system you will typically find many, small, carefully named methods. This promotes fluent interfaces, reuse, and maintainability.
  • 3. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.3 Roadmap > Snakes and Ladders — Cascade and Yourself > Lots of Little Methods > Establishing class invariants > Printing state > Self and super > Accessors and Query methods > Decomposing and naming methods Selected material based on: Kent Beck, Smalltalk Best Practice Patterns, Prentice-Hall, 1997. Selected material courtesy Stéphane Ducasse
  • 4. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.4 Roadmap > Snakes and Ladders — Cascade and Yourself > Lots of Little Methods > Establishing class invariants > Printing state > Self and super > Accessors and Query methods > Decomposing and naming methods
  • 5. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.5 Snakes and Ladders See: http://en.wikipedia.org/wiki/Snakes_and_ladders
  • 6. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.6 Scripting a use case SnakesAndLadders class>>example "self example playToEnd" ^ (self new) add: FirstSquare new; add: (LadderSquare forward: 4); add: BoardSquare new; add: BoardSquare new; add: BoardSquare new; add: BoardSquare new; add: (LadderSquare forward: 2); add: BoardSquare new; add: BoardSquare new; add: BoardSquare new; add: (SnakeSquare back: 6); add: BoardSquare new; join: (GamePlayer named: 'Jack'); join: (GamePlayer named: 'Jill'); yourself We need a way to: —Construct the board —Add some players —Play the game The example script helps us to identify responsibilities, classes and needed interfaces
  • 7. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.7 Cascade How do you format multiple messages to the same receiver? > Use a Cascade. Separate the messages with a semicolon. Put each message on its own line and indent one tab. Only use Cascades for messages with zero or one argument.
  • 8. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.8 Yourself How can you use the value of a Cascade if the last message doesn’t return the receiver of the message? > Append the message yourself to the Cascade.
  • 9. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.9 About yourself > The effect of a cascade is to send all messages to the receiver of the first message in the cascade — self new add: FirstSquare new; … > But the value of the cascade is the value returned by the last message sent > To get the receiver as a result we must send the additional message yourself (OrderedCollection with: 1) add: 25; add: 35 (OrderedCollection with: 1) add: 25; add: 35; yourself 35 an OrderedCollection(1 25 35)
  • 10. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.10 Yourself implementation > The implementation of yourself is trivial, and occurs just once in the system: Object>>yourself ^ self
  • 11. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.11 Do we need yourself here? SnakesAndLadders class>>example "self example playToEnd" ^ self new add: FirstSquare new; … join: (GamePlayer named: 'Jill'); yourself Could be. Don’t really know yet …
  • 12. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.12 Roadmap > Snakes and Ladders — Cascade and Yourself > Lots of Little Methods > Establishing class invariants > Printing state > Self and super > Accessors and Query methods > Decomposing and naming methods
  • 13. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.13 Distributing responsibilities
  • 14. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.14 Lots of Little Methods > Once and only once — “In a program written with good style, everything is said once and only once.” > Lots of little pieces — “Good code invariably has small methods and small objects. Only by factoring the system into many small pieces of state and function can you hope to satisfy the ‘once and only once’ rule.” – Kent Beck, Smalltalk Best Practice Patterns
  • 15. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.15 Class responsibilities and collaborations
  • 16. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.16 Class Comments > Add a comment to each class indicating its responsibilities — Optionally include sample code to run an example
  • 17. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.17 Inheritance in Smalltalk > Single inheritance > Static for the instance variables — Instance variables are collected from the class and its direct and indirect superclasses. > Dynamic for the methods — Methods are looked up at run-time depending on the dynamic type of the receiver.
  • 18. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.18 Roadmap > Snakes and Ladders — Cascade and Yourself > Lots of Little Methods > Establishing class invariants > Printing state > Self and super > Accessors and Query methods > Decomposing and naming methods
  • 19. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.19 Creating classes > A class is created by sending a message to its superclass Object subclass: #SnakesAndLadders instanceVariableNames: 'players squares turn die over' classVariableNames: '' poolDictionaries: '' category: 'SnakesAndLadders'
  • 20. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.20 Named Instance Variables > Instance variables: — Begin with a lowercase letter — Must be explicitly declared: a list of instance variables — Name should be unique in the inheritance chain — Default value of instance variable is nil — Private to the instance, not the class (in contrast to Java) — Can be accessed by all the methods of the class and its subclasses — Instance variables cannot be accessed by class methods. — The clients must use accessors to access an instance variable. Design Hint: — Do not directly access instance variables of a superclass from subclass methods. This way classes are not strongly linked.
  • 21. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.21 Problem — how to initialize objects? Problem > To create a new instance of a class, the message new must be sent to the class — But the class (an object) cannot access the instance variables of the new object (!) — So how can the class establish the invariant of the new object? Solution > Provide instance-side initialization methods in the protocol initialize-release that can be used to create a valid instance
  • 22. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.22 Explicit Initialization How do you initialize instance variables to their default values? > Implement a method initialize that sets all the values explicitly. —Override the class message new to invoke it on new instances SnakesAndLadders>>initialize super initialize. die := Die new. squares := OrderedCollection new. players := OrderedCollection new. turn := 1. over := false.
  • 23. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.23 > In Pharo, the method new calls initialize by default. > NB: You can override new, but you should never override basicNew! > Every metaclass ultimately inherits from Behavior – More on this later … Behavior>>new ^ self basicNew initialize Who calls initialize?
  • 24. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.24 Ordered Collection How do you code Collections whose size can’t be determined when they are created? > Use an OrderedCollection as your default dynamically sized Collection.
  • 25. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.25 Invariants > If your objects have non-trivial invariants, or if they can only be initialized incrementally, consider explicitly implementing an invariant-checking method: SnakesAndLadders>>invariant "Should also check that snakes and ladders lead to ordinary squares, and do not bounce past the beginning or end of the board." ^ squares size > 1 and: [players size > 1] and: [turn >= 1] and: [turn <= players size]
  • 26. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.26 Contracts > Apply Design by Contract — Aid debugging by checking – Pre-conditions to public methods – Non-trivial invariants – Non-trivial post-conditions BoardSquare>>nextSquare self assert: self isLastSquare not. ^ board at: position + 1 SnakesAndLadders>>reset die := Die new. turn := 1. over := false. players do: [:each | each moveTo: self firstSquare ]. self assert: self invariant.
  • 27. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.27 Constructor Method How do you represent instance creation? > Provide methods in the class side “instance creation” protocol that create well-formed instances. Pass all required parameters to them. LadderSquare class>>forward: number ^ self new setForward: number SnakeSquare class>>back: number ^ self new setBack: number
  • 28. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.28 Constructor Parameter Method How do you set instance variables from the parameters to a Constructor Method? > Code a single method that sets all the variables. Preface its name with “set”, then the names of the variables. SnakeSquare>>setBack: aNumber back := aNumber. BoardSquare>>setPosition: aNumber board: aBoard position := aNumber. board := aBoard LadderSquare>>setForward: aNumber forward := aNumber.
  • 29. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.29 Roadmap > Snakes and Ladders — Cascade and Yourself > Lots of Little Methods > Establishing class invariants > Printing state > Self and super > Accessors and Query methods > Decomposing and naming methods
  • 30. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.30 Viewing the game state SnakesAndLadders example inspect In order to provide a simple way to monitor the game state and to ease debugging, we need a textual view of the game Not very informative
  • 31. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.31 Debug Printing Method How do you code the default printing method? — There are two audiences: – you (wanting a lot of information) – your clients (wanting only external properties) > Override printOn: to provide information about object’s structure to the programmer — Put printing methods in the “printing” protocol
  • 32. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.32 Implementing printOn: SnakesAndLadders>>printOn: aStream squares do: [:each | each printOn: aStream] BoardSquare>>printOn: aStream aStream nextPutAll: '[', position printString, self contents, ']' LadderSquare>>printOn: aStream super printOn: aStream. aStream nextPutAll: forward asString, '+>' SnakeSquare>>printOn: aStream aStream nextPutAll: '<-', back asString. super printOn: aStream GamePlayer>>printOn: aStream aStream nextPutAll: name
  • 33. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.33 Viewing the game state SnakesAndLadders example inspect
  • 34. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.34 Interacting with the game With a bit of care, the Inspector can serve as a basic GUI for objects we are developing
  • 35. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.35 Roadmap > Snakes and Ladders — Cascade and Yourself > Lots of Little Methods > Establishing class invariants > Printing state > Self and super > Accessors and Query methods > Decomposing and naming methods
  • 36. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.36 Super How can you invoke superclass behaviour? > Invoke code in a superclass explicitly by sending a message to super instead of self. — The method corresponding to the message will be found in the superclass of the class implementing the sending method. — Always check code using super carefully. Change super to self if doing so does not change how the code executes! — Caveat: If subclasses are expected to call super, consider using a Template Method instead!
  • 37. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.37 Extending Super How do you add to the implementation of a method inherited from a superclass? > Override the method and send a message to super in the overriding method.
  • 38. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.38 A closer look at super > Snake and Ladder both extend the printOn: method of their superclass BoardSquare>>printOn: aStream aStream nextPutAll: '[', position printString, self contents, ']' LadderSquare>>printOn: aStream super printOn: aStream. aStream nextPutAll: forward asString, '+>' SnakeSquare>>printOn: aStream aStream nextPutAll: '<-', back asString. super printOn: aStream.
  • 39. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.39 Normal method lookup Two step process: — Lookup starts in the class of the receiver (an object) 1. If the method is defined in the method dictionary, it is used 2. Else, the search continues in the superclass — If no method is found, this is an error …
  • 40. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.40 Message not understood NB: The default implementation of doesNotUnderstand: may be overridden by any class. When method lookup fails, an error message is sent to the object and lookup starts again with this new message.
  • 41. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.41 Super > Super modifies the usual method lookup to start in the superclass of the class whose method sends to super — NB: lookup does not start in the superclass of the receiver! – Cf. C new bar on next slide — Super is not the superclass!
  • 42. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.42 Super sends A new bar B new bar C new bar D new bar E new bar 'Abar' 'Abar & Afoo' 'Abar & Cfoo' 'Abar & Cfoo & Cfoo' 'Abar & Efoo & Cfoo' NB: It is usually a mistake to super-send to a different method. D>>bar should probably do self foo, not super foo!
  • 43. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.43 Self and super Sending to self is always dynamic Sending to super is always static
  • 44. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.44 Roadmap > Snakes and Ladders — Cascade and Yourself > Lots of Little Methods > Establishing class invariants > Printing state > Self and super > Accessors and Query methods > Decomposing and naming methods
  • 45. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.45 SnakesAndLaddersTest>>setUp eg := self example. loadedDie := LoadedDie new. eg setDie: loadedDie. jack := eg players first. jill := eg players last. Testing > In order to enable deterministic test scenarios, we need to fix the game with a loaded die! – The loaded die will turn up the numbers we tell it to.
  • 46. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.46 Getting Method How do you provide access to an instance variable? > Provide a method that returns the value of the variable. — Give it the same name as the variable. – NB: not called “get…” LoadedDie>>roll self assert: roll notNil. ^ roll
  • 47. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.47 Setting Method How do you change the value of an instance variable? > Provide a method with the same name as the variable. — Have it take a single parameter, the value to be set. – NB: not called “set…” LoadedDie>>roll: aNumber self assert: ((1 to: 6) includes: aNumber). roll := aNumber.
  • 48. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.48 Testing the state of objects > To enable tests, we will need to implement various query methods SnakesAndLaddersTest>>testStartPosition self assert: eg lastPosition = 12. self assert: eg isNotOver. self assert: eg currentPlayer = jack. self assert: eg firstSquare isFirstSquare. self assert: eg firstSquare isLastSquare not. self assert: eg firstSquare position = 1. self assert: eg firstSquare isOccupied. self assert: (eg at: eg lastPosition) isFirstSquare not. self assert: (eg at: eg lastPosition) isLastSquare. self assert: (eg at: eg lastPosition) position = 12. self assert: (eg at: eg lastPosition) isOccupied not. self assert: jack name = 'Jack'. self assert: jill name = 'Jill'. self assert: jack position = 1. self assert: jill position = 1.
  • 49. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.49 Query Method How do you represent testing a property of an object? > Provide a method that returns a Boolean. — Name it by prefacing the property name with a form of “be” — is, was, will etc.
  • 50. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.50 Some query methods SnakesAndLadders>>isNotOver ^ self isOver not BoardSquare>>isFirstSquare ^ position = 1 BoardSquare>>isLastSquare ^ position = board lastPosition BoardSquare>>isOccupied ^ player notNil FirstSquare>>isOccupied ^ players size > 0
  • 51. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.51 A Test Scenario SnakesAndLaddersTest>>testExample self assert: eg currentPlayer = jack. loadedDie roll: 1. eg playOneMove. self assert: jack position = 6. … self assert: eg currentPlayer = jack. loadedDie roll: 2. eg playOneMove. self assert: jack position = 12. self assert: eg isOver. > To carry out a test scenario, we need to play a fixed game instead of a random one.
  • 52. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.52 Roadmap > Snakes and Ladders — Cascade and Yourself > Lots of Little Methods > Establishing class invariants > Printing state > Self and super > Accessors and Query methods > Decomposing and naming methods
  • 53. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.53 Composed Method How do you divide a program into methods? > Divide your program into methods that perform one identifiable task. — Keep all of the operations in a method at the same level of abstraction. — This will naturally result in programs with many small methods, each a few lines long.
  • 54. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.54 Method size > Most methods will be small and self-documenting — Few exceptions: – Complex algorithms – Scripts (configurations) – Tests SnakesAndLadders>>playOneMove | result | self assert: self invariant. ^ self isOver ifTrue: ['The game is over'] ifFalse: [ result := (self currentPlayer moveWith: die), self checkResult. self upDateTurn. result ]
  • 55. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.55 Snakes and Ladders methods • 68 methods • only 7 are more than 6 LOC (including comments!) — 1 of these is the “main” method — the other 6 are test methods
  • 56. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.56 Intention Revealing Message How do you communicate your intent when the implementation is simple? > Send a message to self. — Name the message so it communicates what is to be done rather than how it is to be done. — Code a simple method for the message SnakesAndLadders>>currentPlayer ^ players at: turn
  • 57. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.57 Intention Revealing Selector What do you name a method? > Name methods after what they accomplish. — Well-named methods can eliminate the need for most comments SnakesAndLadders>>upDateTurn turn := 1 + (turnplayers size).
  • 58. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.58 Some Naming Conventions > Use imperative verbs for methods performing an action — moveTo:, leaveCurrentSquare, playOneMove > Prefix testing methods (i.e., that return a boolean) with “is” or “has” — isNil, isNotOver, isOccupied > Prefix converting methods with “as” — asString
  • 59. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.59 Message Comment How do you comment methods? > Communicate important information that is not obvious from the code in a comment at the beginning of the method. — Method dependencies — To-do items — Sample code to execute SnakesAndLadders>>playToEnd "SnakesAndLadders example playToEnd" … Hint: comments may be code smells in disguise! — Try to refactor code and rename methods to get rid of comments!
  • 60. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.60 What you should know! What does yourself return? Why is it needed? How is a new instance of a class initialized? When should you implement invariants and preconditions? What happens when we evaluate an expression with “print it”? Why should a method never send super a different message? How is super static and self dynamic? How do you make your code self-documenting?
  • 61. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.61 Can you answer these questions? When should you override new? If instance variables are really private, why can we see them with an inspector? When does self = super? When does super = self? Which classes implement assert: ? What does self refer to in the method SnakesAndLadders class>>example?
  • 62. © Oscar Nierstrasz ST — Introduction 1.62 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/

Hinweis der Redaktion

  1. A new bar --&amp;gt; Abar B new bar --&amp;gt; Abar &amp; Afoo C new bar --&amp;gt; Abar &amp; Cfoo D new bar --&amp;gt; Abar &amp; Cfoo &amp; Cfoo E new bar --&amp;gt; Abar &amp; Efoo &amp; Cfoo
  2. SnakesAndLadders&amp;gt;&amp;gt;playToEnd is 15 LOC, including comment and blank line