SlideShare ist ein Scribd-Unternehmen logo
1 von 51
7. Best Practice Patterns
Birds-eye view
© Oscar Nierstrasz
ST — Introduction
1.2
Let your code talk — Names matter. Let the
code say what it means.
Introduce a method for everything that needs to be
done. Don’t be afraid to delegate, even to yourself.
Let your code talk — Names matter. Let the
code say what it means.
Introduce a method for everything that needs to be
done. Don’t be afraid to delegate, even to yourself.
© Oscar Nierstrasz
ST — Best Practice Patterns
7.3
Roadmap
> Naming conventions
> Delegation and Double Dispatch
> Conversion and Extension
> Being Lazy
> Collections, Intervals and Streams
Selected material based on: Kent Beck, Smalltalk Best Practice Patterns, Prentice-Hall, 1997.
© Oscar Nierstrasz
ST — Best Practice Patterns
7.4
Roadmap
> Naming conventions
> Delegation and Double Dispatch
> Conversion and Extension
> Being Lazy
> Collections, Intervals and Streams
© Oscar Nierstrasz
ST — Best Practice Patterns
7.5
Simple Superclass Name
What should we call the root of a hierarchy?
> Use a single word that conveys its purpose in the design
— Number
— Collection
— VisualComponent
— BoardSquare
© Oscar Nierstrasz
ST — Best Practice Patterns
7.6
Qualified Subclass Name
What should you call a subclass that plays a role
similar to its superclass?
> Use names that indicate the distinct role. Otherwise
prepend an adjective that communicates the relationship
— OrderedCollection (vs. Array)
— UndefinedObject
— FirstSquare (vs. Snake and Ladder)
© Oscar Nierstrasz
ST — Best Practice Patterns
7.7
Naming methods and variables
> Choose method and variable names so that expressions
can be read like (pidgin) sentences.
— Spell out names in full
– Avoid abbreviations!
players do: [:each | each moveTo: self firstSquare ].
© Oscar Nierstrasz
ST — Best Practice Patterns
7.8
Intention Revealing Selector
What do you name a method?
> Name methods after what they accomplish, not how.
— Change state of the receiver:
– translateBy:, add: …
— Change state of the argument:
– displayOn:, addTo:, printOn:
— Return value from receiver:
– translatedBy:, size, topLeft
© Oscar Nierstrasz
ST — Best Practice Patterns
7.9
Role Suggesting Instance Variable Name
What do you name an instance variable?
> Name instance variables for the role they play in the
computation.
— Make the name plural if the variable will hold a Collection
Object subclass: #SnakesAndLadders
instanceVariableNames: 'players squares turn die over'
…
© Oscar Nierstrasz
ST — Best Practice Patterns
7.10
Type Suggesting Parameter Name
What do you call a method parameter?
> Name parameters according to their most general
expected class, preceded by “a” or “an”.
— Don’t need to do this if the method name already specifies the
type, or if the type is obvious.
— If there is more than one argument with the same expected
type, precede the type with its role.
BoardSquare>>setPosition: aNumber board: aBoard
position := aNumber.
board := aBoard
Collection>>reject: rejectBlock thenDo: doBlock
"Utility method to improve readability."
^ (self reject: rejectBlock) do: doBlock
© Oscar Nierstrasz
ST — Best Practice Patterns
7.11
Role Suggesting Temporary Variable Name
What do you call a temporary variable?
> Name a temporary variable for the role it plays in the
computation.
— Use temporaries to:
– collect intermediate results
– reuse the result of an expression
– name the result of an expression
— Methods are often simpler when they don’t use temporaries!
GamePlayer>>moveWith: aDie
| roll destination |
roll := aDie roll.
destination := square forwardBy: roll.
self moveTo: destination.
^ name, ' rolls ', roll asString
© Oscar Nierstrasz
ST — Best Practice Patterns
7.12
Methods from Comments
> Be suspicious of comments
— If you feel the need to comment your code, try instead to introduce a
new method
— “Do not comment bad code — rewrite it”
– Kernighan ’78
GamePlayer>>moveTo: aSquare
square notNil ifTrue: [ square remove: self ].
"leave the current square"
square := aSquare landHere: self.
GamePlayer>>moveTo: aSquare
self leaveCurrentSquare.
square := aSquare landHere: self.
GamePlayer>>leaveCurrentSquare
square notNil ifTrue: [ square remove: self ].
Exception: always write class comments!
© Oscar Nierstrasz
ST — Best Practice Patterns
7.13
Roadmap
> Naming conventions
> Delegation and Double Dispatch
> Conversion and Extension
> Being Lazy
> Collections, Intervals and Streams
© Oscar Nierstrasz
ST — Best Practice Patterns
7.14
Delegation
How does an object share implementation without
inheritance?
> Pass part of its work on to another object
— Many objects need to display, all objects delegate to a brush-
like object (Pen in VisualSmalltalk, GraphicsContext in
VisualAge and VisualWorks)
— All the detailed code is concentrated in a single class and the
rest of the system has a simplified view of the displaying.
© Oscar Nierstrasz
ST — Best Practice Patterns
7.15
Simple Delegation
How do you invoke a disinterested delegate?
> Delegate messages unchanged
— Is the identity of the delegating object important?
– No
— Is the state of the delegating object important?
– No
— Use simple delegation!
SnakesAndLadders>>at: position
^ squares at: position
© Oscar Nierstrasz
ST — Best Practice Patterns
7.16
Self Delegation
How do you implement delegation to an object
that needs reference to the delegating object?
> Pass along the delegating object (i.e., self ) in an
additional parameter.
— Commonly called “for:”
GamePlayer>>moveTo: aSquare
self leaveCurrentSquare.
square := aSquare landHere: self.
© Oscar Nierstrasz
ST — Best Practice Patterns
7.17
Reversing Method
How do you code a smooth flow of messages?
> Code a method on the parameter.
— Derive its name form the original message.
— Take the original receiver as a parameter to the new method.
— Implement the method by sending the original message to the original
receiver.
Point>>printOn: aStream
x printOn: aStream
aStream nextPutAll: '@'.
y printOn: aStream
Stream>>print: anObject
anObject printOn: self
Point>>printOn: aStream
aStream print: x; nextPutAll: '@'; print: y
Caveat: Creating new selectors just
for fun is not a good idea. Each
selector must justify its existence.
© Oscar Nierstrasz
ST — Best Practice Patterns
7.18
Execute Around Method
How do you represent pairs of actions that have to be taken
together?
> Code a method that takes a Block as an argument.
— Name the method by appending “During: aBlock” to the name of
the first method to be invoked.
— In the body, invoke the first method, evaluate the block, then invoke the
second method.
File>>openDuring: aBlock
self open.
aBlock value.
self close
File>>openDuring: aBlock
self open.
[aBlock value]
ensure: [self close]
Or better:
© Oscar Nierstrasz
ST — Best Practice Patterns
7.19
Method Object
How do you break up a method where many lines
of code share many arguments and temporary
variables?
> Create a class named after the method.
— Give it an instance variable for the receiver of the original
method, each argument and each temporary.
— Give it a Constructor Method that takes the original receiver and
method arguments.
— Give it one method, compute, implemented by the original
method body.
— Replace the original method with a call to an instance of the
new class.
— Refactor the compute method into lots of little methods.
© Oscar Nierstrasz
ST — Best Practice Patterns
7.20
Method Object
Obligation>>sendTask: aTask job: aJob
| notprocessed processed copied executed |
... 150 lines of heavily commented code
Object subclass: #TaskSender
instanceVariableNames: 'obligation task job
notprocessed processed copied executed'
...
TaskSender class>>obligation: anObligation task: aTask job: aJob
^ self new
setObligation: anObligation task: aTask job: aJob
TaskSender>>compute
... 150 lines of heavily commented code (to be refactored)
Obligation>>sendTask: aTask job: aJob
(TaskSender obligation: self task: aTask job: aJob) compute
© Oscar Nierstrasz
ST — Best Practice Patterns
7.21
Choosing Object
How do you execute one of several alternatives?
> Send a message to one of several different kinds of
objects, each of which executes one alternative.
© Oscar Nierstrasz
ST — Best Practice Patterns
7.22
Choosing Object
square destinationBoardSquare>>destination
^ self
LadderSquare>>destination
^ self forwardBy: forward
SnakeSquare>>destination
^ self backwardBy: back
square isSnake
ifTrue: [
destination := square backwardBy: square back ]
ifFalse: [
square isLadder
ifTrue: [ destination := square forwardBy: square forward ]
ifFalse: [ destination := square ] ]
© Oscar Nierstrasz
ST — Best Practice Patterns
7.23
Double Dispatch
> How can you code a computation that has many cases,
the cross product of two families of classes?
> Send a message to the argument.
— Append the class or “species” name of the receiver to the
selector.
— Pass the receiver as an argument.
— Caveat: Can lead to a proliferation of messages
© Oscar Nierstrasz
ST — Best Practice Patterns
7.24
Maresey Doats
Mares eat oats and does eat oats,
And little lambs eat ivy,
A kid will eat ivy too,
Wouldn't you?
MareTest>>testEating
self assert:
((mare eats: oats)
and: [ doe eats: oats ]
and: [ lamb eats: ivy ]
and: [ kid eats: ivy ]
).
© Oscar Nierstrasz
ST — Best Practice Patterns
7.25
Bad Solutions
Mare>>eats: aFood
^ aFood class = Oats
• Breaks encapsulation
• Hard to extend
• Fragile with respect to changes
Mare>>eats: aFood
^ aFood isGoodForMares
Food>>isGoodForMares
^ false
Oats>>isGoodForMares
^ true
Better, but:
• Mixes responsibilities
• Still hard to extend
© Oscar Nierstrasz
ST — Best Practice Patterns
7.26
Double Dispatch — Interaction
• Separates responsibilities
• Easy to extend
• Handles multiple kinds of food
© Oscar Nierstrasz
ST — Best Practice Patterns
7.27
Double Dispatch — Hierarchy
© Oscar Nierstrasz
ST — Best Practice Patterns
7.28
Roadmap
> Naming conventions
> Delegation and Double Dispatch
> Conversion and Extension
> Being Lazy
> Collections, Intervals and Streams
© Oscar Nierstrasz
ST — Best Practice Patterns
7.29
Converter Method
How do you convert an object of one class to that
of another that supports the same protocol?
> Provide a converter method in the interface of the object
to be converted.
— Name it by prepending “as” to the class of the object returned
— E.g., asArray, asSet, asOrderedCollection etc.
© Oscar Nierstrasz
ST — Best Practice Patterns
7.30
Converter Constructor Method
How do you convert an object of one class to that
of another that supports a different protocol?
> Introduce a Constructor Method that takes the object to
be converted as an argument
— Name it by prepending “from” to the class of the object to be
converted
Date class>>fromString:
…
Date fromString: "Jan 1, 2006"
String>>asDate
…
"Jan 1, 2006" asDate
Don’t confuse responsibilities!
© Oscar Nierstrasz
ST — Best Practice Patterns
7.31
Shortcut Constructor Method
What is the external interface for creating a new
object when a Constructor Method is too
wordy?
> Represent object creation as a message to one of the
arguments of the Constructor Method.
— Add no more than three of these methods per system you
develop!
Point x: 3 y: 5
3@5
© Oscar Nierstrasz
ST — Best Practice Patterns
7.32
Modifying Super
> How do you change part of the behaviour of a super
class method without modifying it?
> Override the method and invoke super.
— Then execute the code to modify the results.
SnakesAndLadders>>initialize
die := Die new.
…
ScriptedSnakesAndLadders>>initialize
super initialize
die := LoadedDie new.
…
© Oscar Nierstrasz
ST — Best Practice Patterns
7.33
Roadmap
> Naming conventions
> Delegation and Double Dispatch
> Conversion and Extension
> Being Lazy
> Collections, Intervals and Streams
© Oscar Nierstrasz
ST — Best Practice Patterns
7.34
Default Value Method
How do you represent the default value of a
variable?
> Create a method that returns the value.
— Prepend “default” to the name of the variable as the name of the
method
DisplayScanner>>defaultFont
^ TextStyle defaultFont
© Oscar Nierstrasz
ST — Best Practice Patterns
7.35
Constant Method
How do you code a constant?
> Create a method that returns the constant
Fraction>>one
^ self numerator: 1 denominator: 1
© Oscar Nierstrasz
ST — Best Practice Patterns
7.36
Lazy Initialization
How do you initialize an instance variable to its default
value?
> Write a Getting Method for the variable.
— Initialize it if necessary with a Default Value Method
— Useful if:
– The variable is not always needed
– The variable consumes expensive resources (e.g., space)
– Initialization is expensive.
XWindows>>windowManager
windowManager isNil ifTrue: [
windowManager := self defaultWindowManager ].
^ windowManager
© Oscar Nierstrasz
ST — Best Practice Patterns
7.37
Lookup Cache
> How do you optimize repeated access to objects that
are expensive to compute?
> Cache the values of the computation
— Prepend “lookup” to the name of the expensive method
— Add an instance variable holding a Dictionary to cache the
results.
— Make the parameters of the method be the search keys of the
dictionary and the results be its values.
© Oscar Nierstrasz
ST — Best Practice Patterns
7.38
Slow Fibonacci
Fibs>>at: anIndex
self assert: anIndex >= 1.
anIndex = 1 ifTrue: [ ^ 1 ].
anIndex = 2 ifTrue: [ ^ 1 ].
^ (self at: anIndex - 1) + (self at: anIndex - 2)
Fibs new at: 35 9227465
Takes 8 seconds.
Forget about larger values!
© Oscar Nierstrasz
ST — Best Practice Patterns
7.39
Cacheing Fibonacci
Object subclass: #Fibs
instanceVariableNames: 'fibCache'
classVariableNames: ''
poolDictionaries: ''
category: 'Misc'
Fibs>>initialize
fibCache := Dictionary new
Fibs>>fibCache
^ fibCache
Introduce the cache …
© Oscar Nierstrasz
ST — Best Practice Patterns
7.40
Cacheing Fibonacci
Fibs>>lookup: anIndex
^ self fibCache at: anIndex ifAbsentPut: [ self at: anIndex ]
Fibs>>at: anIndex
self assert: anIndex >= 1.
anIndex = 1 ifTrue: [ ^ 1 ].
anIndex = 2 ifTrue: [ ^ 1 ].
^ (self lookup: anIndex - 1) + (self lookup: anIndex - 2)
Now we introduce the lookup method, and
redirect all accesses to use the cache lookup
Fibs new at: 100 354224848179261915075
… is virtually instantaneous!
© Oscar Nierstrasz
ST — Best Practice Patterns
7.41
Roadmap
> Naming conventions
> Delegation and Double Dispatch
> Conversion and Extension
> Being Lazy
> Collections, Intervals and Streams
© Oscar Nierstrasz
ST — Best Practice Patterns
7.42
Comparing Method
How do you order objects with respect to each
other?
> Implement <= to return true if the receiver should be
ordered before the argument
— <,<=,>,>= are defined for Magnitude and its subclasses.
— Implement <= in the “comparing” protocol
© Oscar Nierstrasz
ST — Best Practice Patterns
7.43
Sorted Collection
How do you sort a collection?
> Use a Sorted Collection.
— Set its sort block if you want to sort by some other criterion than
<=
#( 'Snakes' 'Ladders' ) asSortedCollection
a SortedCollection('Snakes' 'Ladders')
#( 'Snakes' 'Ladders' ) asSortedCollection: [:a :b | b<=a ]
a SortedCollection('Ladders' 'Snakes')
a SortedCollection('Snakes' 'Ladders')
#( 'Snakes' 'Ladders' ) asSortedCollection
sortBlock: [:a :b | b<=a ]
© Oscar Nierstrasz
ST — Best Practice Patterns
7.44
Interval
How do you code a collection of numbers in a
sequence?
> Use an Interval with start, stop and optional step
value.
— Use the Shortcut Constructor methods Number>>to: and
Number>>to:by: to build intervals
1 to: 5
(1 to: 5) asSet
(10 to: 100 by: 20) asOrderedCollection
(1 to: 5)
a Set(1 2 3 4 5)
an OrderedCollection(10 30 50 70 90)
© Oscar Nierstrasz
ST — Best Practice Patterns
7.45
Duplicate Removing Set
How do you remove the duplicates from a
Collection?
> Send asSet to the collection
'hello world' asSet
a Set(Character space $r $d $e $w $h $l $o)
© Oscar Nierstrasz
ST — Best Practice Patterns
7.46
Searching Literal
How do you test if an object is equal to one of
several literal values?
> Ask a literal Collection if it includes the element you
seek
'aeiou' includes: char asLowercase
char = $a | char = $e | char = $i | char = $o | char = $u |
char = $A | char = $E | char = $I | char = $O | char = $U
© Oscar Nierstrasz
ST — Best Practice Patterns
7.47
Concatenation
How do you put two collections together?
> Send “,” to the first with the second as argument
(1 to: 3), (4 to: 6)
a Dictionary(#a->1 #b->2 )
(Dictionary newFrom: { #a -> 1}), (Dictionary newFrom: { #b -> 2})
#(1 2 3 4 5 6)
© Oscar Nierstrasz
ST — Best Practice Patterns
7.48
Concatenating Stream
How do you concatenate several Collections?
> Use a Stream on a new collection of the result type.
writer := WriteStream on: String new.
Smalltalk keys do: [ : each | writer nextPutAll: each, '::' ].
writer contents
Can be vastly more efficient than building a
new collection with each concatenation.
© Oscar Nierstrasz
ST — Best Practice Patterns
7.49
What you should know!
How should you name instance variables?
Why should you be suspicious of comments?
How does Simple Delegation differ from Self
Delegation?
When would you use Double Dispatch?
Why should you avoid introducing a Converter Method
for an object supporting a different protocol?
How do you sort a Collection?
When should you use Lazy Initialization?
© Oscar Nierstrasz
ST — Best Practice Patterns
7.50
Can you answer these questions?
Which patterns would you use to implement a
transactional interface?
How can Method Object help you to decompose long
methods?
Why is it a bad idea to query an object for its class?
Why are you less likely to see Double Dispatch in a
statically-typed language?
How can you avoid Modifying Super?
How can you avoid writing case statements?
What pattern does Object>>-> illustrate?
© Oscar Nierstrasz
ST — Introduction
1.51
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
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with ClojureJohn Stevenson
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugketan_patel25
 
Fun with Functional Programming in Clojure
Fun with Functional Programming in ClojureFun with Functional Programming in Clojure
Fun with Functional Programming in ClojureCodemotion
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developersJohn Stevenson
 
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
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with pythonArslan Arshad
 
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScriptLotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScriptBill Buchan
 

Was ist angesagt? (20)

13 traits
13 traits13 traits
13 traits
 
8 - OOP - Syntax & Messages
8 - OOP - Syntax & Messages8 - OOP - Syntax & Messages
8 - OOP - Syntax & Messages
 
4 - OOP - Taste of Smalltalk (Tamagoshi)
4 - OOP - Taste of Smalltalk (Tamagoshi)4 - OOP - Taste of Smalltalk (Tamagoshi)
4 - OOP - Taste of Smalltalk (Tamagoshi)
 
8 - OOP - Smalltalk Syntax
8 - OOP - Smalltalk Syntax8 - OOP - Smalltalk Syntax
8 - OOP - Smalltalk Syntax
 
4 - OOP - Taste of Smalltalk (Squeak)
4 - OOP - Taste of Smalltalk (Squeak)4 - OOP - Taste of Smalltalk (Squeak)
4 - OOP - Taste of Smalltalk (Squeak)
 
06 debugging
06 debugging06 debugging
06 debugging
 
Stoop ed-class forreuse
Stoop ed-class forreuseStoop ed-class forreuse
Stoop ed-class forreuse
 
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
 
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
 
Drools
DroolsDrools
Drools
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
 
Fun with Functional Programming in Clojure
Fun with Functional Programming in ClojureFun with Functional Programming in Clojure
Fun with Functional Programming in Clojure
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developers
 
4 - OOP - Taste of Smalltalk (VisualWorks)
4 - OOP - Taste of Smalltalk (VisualWorks)4 - OOP - Taste of Smalltalk (VisualWorks)
4 - OOP - Taste of Smalltalk (VisualWorks)
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
Python advance
Python advancePython advance
Python advance
 
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScriptLotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
 

Andere mochten auch (20)

11 - OOP - Numbers
11 - OOP - Numbers11 - OOP - Numbers
11 - OOP - Numbers
 
Stoop 433-chain
Stoop 433-chainStoop 433-chain
Stoop 433-chain
 
Stoop 300-block optimizationinvw
Stoop 300-block optimizationinvwStoop 300-block optimizationinvw
Stoop 300-block optimizationinvw
 
Stoop 450-s unit
Stoop 450-s unitStoop 450-s unit
Stoop 450-s unit
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
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 ed-lod
Stoop ed-lodStoop ed-lod
Stoop ed-lod
 
Stoop 437-proxy
Stoop 437-proxyStoop 437-proxy
Stoop 437-proxy
 
Stoop 305-reflective programming5
Stoop 305-reflective programming5Stoop 305-reflective programming5
Stoop 305-reflective programming5
 
Stoop 301-internal objectstructureinvw
Stoop 301-internal objectstructureinvwStoop 301-internal objectstructureinvw
Stoop 301-internal objectstructureinvw
 
Stoop 400-metaclass only
Stoop 400-metaclass onlyStoop 400-metaclass only
Stoop 400-metaclass only
 
Stoop sed-smells
Stoop sed-smellsStoop sed-smells
Stoop sed-smells
 
Stoop 431-visitor
Stoop 431-visitorStoop 431-visitor
Stoop 431-visitor
 
Stoop 303-advanced blocks
Stoop 303-advanced blocksStoop 303-advanced blocks
Stoop 303-advanced blocks
 
Stoop ed-inheritance composition
Stoop ed-inheritance compositionStoop ed-inheritance composition
Stoop ed-inheritance composition
 
Stoop 439-decorator
Stoop 439-decoratorStoop 439-decorator
Stoop 439-decorator
 
9 - OOP - Smalltalk Classes (b)
9 - OOP - Smalltalk Classes (b)9 - OOP - Smalltalk Classes (b)
9 - OOP - Smalltalk Classes (b)
 
12 - Conditions and Loops
12 - Conditions and Loops12 - Conditions and Loops
12 - Conditions and Loops
 

Ähnlich wie 07 bestpractice

Smalltalk In A Nutshell
Smalltalk In A NutshellSmalltalk In A Nutshell
Smalltalk In A Nutshellscg
 
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 javalet's go to study
 
SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSergey Karpushin
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An IntroductionManvendra Singh
 
NET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptxNET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptxpetabridge
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanJimin Hsieh
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26Bilal Ahmed
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java conceptsChikugehlot
 
Powershell for Log Analysis and Data Crunching
 Powershell for Log Analysis and Data Crunching Powershell for Log Analysis and Data Crunching
Powershell for Log Analysis and Data CrunchingMichelle D'israeli
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Troy Miles
 
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 SmalltalkSerge Stinckwich
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6Nitay Neeman
 
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...PROIDEA
 
Dynamic C++ Silicon Valley Code Camp 2012
Dynamic C++ Silicon Valley Code Camp 2012Dynamic C++ Silicon Valley Code Camp 2012
Dynamic C++ Silicon Valley Code Camp 2012aleks-f
 

Ähnlich wie 07 bestpractice (20)

Day 2
Day 2Day 2
Day 2
 
Smalltalk In A Nutshell
Smalltalk In A NutshellSmalltalk In A Nutshell
Smalltalk In A Nutshell
 
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
 
SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principles
 
Python lec4
Python lec4Python lec4
Python lec4
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
NET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptxNET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptx
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
Powershell for Log Analysis and Data Crunching
 Powershell for Log Analysis and Data Crunching Powershell for Log Analysis and Data Crunching
Powershell for Log Analysis and Data Crunching
 
iOS Session-2
iOS Session-2iOS Session-2
iOS Session-2
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 
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
 
I phone 12
I phone 12I phone 12
I phone 12
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6
 
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...
 
Reversing JavaScript
Reversing JavaScriptReversing JavaScript
Reversing JavaScript
 
Dynamic C++ Silicon Valley Code Camp 2012
Dynamic C++ Silicon Valley Code Camp 2012Dynamic C++ Silicon Valley Code Camp 2012
Dynamic C++ Silicon Valley Code Camp 2012
 

Mehr von The World of Smalltalk (11)

05 seaside canvas
05 seaside canvas05 seaside canvas
05 seaside canvas
 
99 questions
99 questions99 questions
99 questions
 
09 metaclasses
09 metaclasses09 metaclasses
09 metaclasses
 
05 seaside
05 seaside05 seaside
05 seaside
 
01 intro
01 intro01 intro
01 intro
 
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-frameworks
Stoop ed-frameworksStoop ed-frameworks
Stoop ed-frameworks
 
Stoop ed-dual interface
Stoop ed-dual interfaceStoop ed-dual interface
Stoop ed-dual interface
 

Kürzlich hochgeladen

Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesShubhangi Sonawane
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxNikitaBankoti2
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 

Kürzlich hochgeladen (20)

Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
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 ...
 
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
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 

07 bestpractice

  • 1. 7. Best Practice Patterns
  • 2. Birds-eye view © Oscar Nierstrasz ST — Introduction 1.2 Let your code talk — Names matter. Let the code say what it means. Introduce a method for everything that needs to be done. Don’t be afraid to delegate, even to yourself. Let your code talk — Names matter. Let the code say what it means. Introduce a method for everything that needs to be done. Don’t be afraid to delegate, even to yourself.
  • 3. © Oscar Nierstrasz ST — Best Practice Patterns 7.3 Roadmap > Naming conventions > Delegation and Double Dispatch > Conversion and Extension > Being Lazy > Collections, Intervals and Streams Selected material based on: Kent Beck, Smalltalk Best Practice Patterns, Prentice-Hall, 1997.
  • 4. © Oscar Nierstrasz ST — Best Practice Patterns 7.4 Roadmap > Naming conventions > Delegation and Double Dispatch > Conversion and Extension > Being Lazy > Collections, Intervals and Streams
  • 5. © Oscar Nierstrasz ST — Best Practice Patterns 7.5 Simple Superclass Name What should we call the root of a hierarchy? > Use a single word that conveys its purpose in the design — Number — Collection — VisualComponent — BoardSquare
  • 6. © Oscar Nierstrasz ST — Best Practice Patterns 7.6 Qualified Subclass Name What should you call a subclass that plays a role similar to its superclass? > Use names that indicate the distinct role. Otherwise prepend an adjective that communicates the relationship — OrderedCollection (vs. Array) — UndefinedObject — FirstSquare (vs. Snake and Ladder)
  • 7. © Oscar Nierstrasz ST — Best Practice Patterns 7.7 Naming methods and variables > Choose method and variable names so that expressions can be read like (pidgin) sentences. — Spell out names in full – Avoid abbreviations! players do: [:each | each moveTo: self firstSquare ].
  • 8. © Oscar Nierstrasz ST — Best Practice Patterns 7.8 Intention Revealing Selector What do you name a method? > Name methods after what they accomplish, not how. — Change state of the receiver: – translateBy:, add: … — Change state of the argument: – displayOn:, addTo:, printOn: — Return value from receiver: – translatedBy:, size, topLeft
  • 9. © Oscar Nierstrasz ST — Best Practice Patterns 7.9 Role Suggesting Instance Variable Name What do you name an instance variable? > Name instance variables for the role they play in the computation. — Make the name plural if the variable will hold a Collection Object subclass: #SnakesAndLadders instanceVariableNames: 'players squares turn die over' …
  • 10. © Oscar Nierstrasz ST — Best Practice Patterns 7.10 Type Suggesting Parameter Name What do you call a method parameter? > Name parameters according to their most general expected class, preceded by “a” or “an”. — Don’t need to do this if the method name already specifies the type, or if the type is obvious. — If there is more than one argument with the same expected type, precede the type with its role. BoardSquare>>setPosition: aNumber board: aBoard position := aNumber. board := aBoard Collection>>reject: rejectBlock thenDo: doBlock "Utility method to improve readability." ^ (self reject: rejectBlock) do: doBlock
  • 11. © Oscar Nierstrasz ST — Best Practice Patterns 7.11 Role Suggesting Temporary Variable Name What do you call a temporary variable? > Name a temporary variable for the role it plays in the computation. — Use temporaries to: – collect intermediate results – reuse the result of an expression – name the result of an expression — Methods are often simpler when they don’t use temporaries! GamePlayer>>moveWith: aDie | roll destination | roll := aDie roll. destination := square forwardBy: roll. self moveTo: destination. ^ name, ' rolls ', roll asString
  • 12. © Oscar Nierstrasz ST — Best Practice Patterns 7.12 Methods from Comments > Be suspicious of comments — If you feel the need to comment your code, try instead to introduce a new method — “Do not comment bad code — rewrite it” – Kernighan ’78 GamePlayer>>moveTo: aSquare square notNil ifTrue: [ square remove: self ]. "leave the current square" square := aSquare landHere: self. GamePlayer>>moveTo: aSquare self leaveCurrentSquare. square := aSquare landHere: self. GamePlayer>>leaveCurrentSquare square notNil ifTrue: [ square remove: self ]. Exception: always write class comments!
  • 13. © Oscar Nierstrasz ST — Best Practice Patterns 7.13 Roadmap > Naming conventions > Delegation and Double Dispatch > Conversion and Extension > Being Lazy > Collections, Intervals and Streams
  • 14. © Oscar Nierstrasz ST — Best Practice Patterns 7.14 Delegation How does an object share implementation without inheritance? > Pass part of its work on to another object — Many objects need to display, all objects delegate to a brush- like object (Pen in VisualSmalltalk, GraphicsContext in VisualAge and VisualWorks) — All the detailed code is concentrated in a single class and the rest of the system has a simplified view of the displaying.
  • 15. © Oscar Nierstrasz ST — Best Practice Patterns 7.15 Simple Delegation How do you invoke a disinterested delegate? > Delegate messages unchanged — Is the identity of the delegating object important? – No — Is the state of the delegating object important? – No — Use simple delegation! SnakesAndLadders>>at: position ^ squares at: position
  • 16. © Oscar Nierstrasz ST — Best Practice Patterns 7.16 Self Delegation How do you implement delegation to an object that needs reference to the delegating object? > Pass along the delegating object (i.e., self ) in an additional parameter. — Commonly called “for:” GamePlayer>>moveTo: aSquare self leaveCurrentSquare. square := aSquare landHere: self.
  • 17. © Oscar Nierstrasz ST — Best Practice Patterns 7.17 Reversing Method How do you code a smooth flow of messages? > Code a method on the parameter. — Derive its name form the original message. — Take the original receiver as a parameter to the new method. — Implement the method by sending the original message to the original receiver. Point>>printOn: aStream x printOn: aStream aStream nextPutAll: '@'. y printOn: aStream Stream>>print: anObject anObject printOn: self Point>>printOn: aStream aStream print: x; nextPutAll: '@'; print: y Caveat: Creating new selectors just for fun is not a good idea. Each selector must justify its existence.
  • 18. © Oscar Nierstrasz ST — Best Practice Patterns 7.18 Execute Around Method How do you represent pairs of actions that have to be taken together? > Code a method that takes a Block as an argument. — Name the method by appending “During: aBlock” to the name of the first method to be invoked. — In the body, invoke the first method, evaluate the block, then invoke the second method. File>>openDuring: aBlock self open. aBlock value. self close File>>openDuring: aBlock self open. [aBlock value] ensure: [self close] Or better:
  • 19. © Oscar Nierstrasz ST — Best Practice Patterns 7.19 Method Object How do you break up a method where many lines of code share many arguments and temporary variables? > Create a class named after the method. — Give it an instance variable for the receiver of the original method, each argument and each temporary. — Give it a Constructor Method that takes the original receiver and method arguments. — Give it one method, compute, implemented by the original method body. — Replace the original method with a call to an instance of the new class. — Refactor the compute method into lots of little methods.
  • 20. © Oscar Nierstrasz ST — Best Practice Patterns 7.20 Method Object Obligation>>sendTask: aTask job: aJob | notprocessed processed copied executed | ... 150 lines of heavily commented code Object subclass: #TaskSender instanceVariableNames: 'obligation task job notprocessed processed copied executed' ... TaskSender class>>obligation: anObligation task: aTask job: aJob ^ self new setObligation: anObligation task: aTask job: aJob TaskSender>>compute ... 150 lines of heavily commented code (to be refactored) Obligation>>sendTask: aTask job: aJob (TaskSender obligation: self task: aTask job: aJob) compute
  • 21. © Oscar Nierstrasz ST — Best Practice Patterns 7.21 Choosing Object How do you execute one of several alternatives? > Send a message to one of several different kinds of objects, each of which executes one alternative.
  • 22. © Oscar Nierstrasz ST — Best Practice Patterns 7.22 Choosing Object square destinationBoardSquare>>destination ^ self LadderSquare>>destination ^ self forwardBy: forward SnakeSquare>>destination ^ self backwardBy: back square isSnake ifTrue: [ destination := square backwardBy: square back ] ifFalse: [ square isLadder ifTrue: [ destination := square forwardBy: square forward ] ifFalse: [ destination := square ] ]
  • 23. © Oscar Nierstrasz ST — Best Practice Patterns 7.23 Double Dispatch > How can you code a computation that has many cases, the cross product of two families of classes? > Send a message to the argument. — Append the class or “species” name of the receiver to the selector. — Pass the receiver as an argument. — Caveat: Can lead to a proliferation of messages
  • 24. © Oscar Nierstrasz ST — Best Practice Patterns 7.24 Maresey Doats Mares eat oats and does eat oats, And little lambs eat ivy, A kid will eat ivy too, Wouldn't you? MareTest>>testEating self assert: ((mare eats: oats) and: [ doe eats: oats ] and: [ lamb eats: ivy ] and: [ kid eats: ivy ] ).
  • 25. © Oscar Nierstrasz ST — Best Practice Patterns 7.25 Bad Solutions Mare>>eats: aFood ^ aFood class = Oats • Breaks encapsulation • Hard to extend • Fragile with respect to changes Mare>>eats: aFood ^ aFood isGoodForMares Food>>isGoodForMares ^ false Oats>>isGoodForMares ^ true Better, but: • Mixes responsibilities • Still hard to extend
  • 26. © Oscar Nierstrasz ST — Best Practice Patterns 7.26 Double Dispatch — Interaction • Separates responsibilities • Easy to extend • Handles multiple kinds of food
  • 27. © Oscar Nierstrasz ST — Best Practice Patterns 7.27 Double Dispatch — Hierarchy
  • 28. © Oscar Nierstrasz ST — Best Practice Patterns 7.28 Roadmap > Naming conventions > Delegation and Double Dispatch > Conversion and Extension > Being Lazy > Collections, Intervals and Streams
  • 29. © Oscar Nierstrasz ST — Best Practice Patterns 7.29 Converter Method How do you convert an object of one class to that of another that supports the same protocol? > Provide a converter method in the interface of the object to be converted. — Name it by prepending “as” to the class of the object returned — E.g., asArray, asSet, asOrderedCollection etc.
  • 30. © Oscar Nierstrasz ST — Best Practice Patterns 7.30 Converter Constructor Method How do you convert an object of one class to that of another that supports a different protocol? > Introduce a Constructor Method that takes the object to be converted as an argument — Name it by prepending “from” to the class of the object to be converted Date class>>fromString: … Date fromString: "Jan 1, 2006" String>>asDate … "Jan 1, 2006" asDate Don’t confuse responsibilities!
  • 31. © Oscar Nierstrasz ST — Best Practice Patterns 7.31 Shortcut Constructor Method What is the external interface for creating a new object when a Constructor Method is too wordy? > Represent object creation as a message to one of the arguments of the Constructor Method. — Add no more than three of these methods per system you develop! Point x: 3 y: 5 3@5
  • 32. © Oscar Nierstrasz ST — Best Practice Patterns 7.32 Modifying Super > How do you change part of the behaviour of a super class method without modifying it? > Override the method and invoke super. — Then execute the code to modify the results. SnakesAndLadders>>initialize die := Die new. … ScriptedSnakesAndLadders>>initialize super initialize die := LoadedDie new. …
  • 33. © Oscar Nierstrasz ST — Best Practice Patterns 7.33 Roadmap > Naming conventions > Delegation and Double Dispatch > Conversion and Extension > Being Lazy > Collections, Intervals and Streams
  • 34. © Oscar Nierstrasz ST — Best Practice Patterns 7.34 Default Value Method How do you represent the default value of a variable? > Create a method that returns the value. — Prepend “default” to the name of the variable as the name of the method DisplayScanner>>defaultFont ^ TextStyle defaultFont
  • 35. © Oscar Nierstrasz ST — Best Practice Patterns 7.35 Constant Method How do you code a constant? > Create a method that returns the constant Fraction>>one ^ self numerator: 1 denominator: 1
  • 36. © Oscar Nierstrasz ST — Best Practice Patterns 7.36 Lazy Initialization How do you initialize an instance variable to its default value? > Write a Getting Method for the variable. — Initialize it if necessary with a Default Value Method — Useful if: – The variable is not always needed – The variable consumes expensive resources (e.g., space) – Initialization is expensive. XWindows>>windowManager windowManager isNil ifTrue: [ windowManager := self defaultWindowManager ]. ^ windowManager
  • 37. © Oscar Nierstrasz ST — Best Practice Patterns 7.37 Lookup Cache > How do you optimize repeated access to objects that are expensive to compute? > Cache the values of the computation — Prepend “lookup” to the name of the expensive method — Add an instance variable holding a Dictionary to cache the results. — Make the parameters of the method be the search keys of the dictionary and the results be its values.
  • 38. © Oscar Nierstrasz ST — Best Practice Patterns 7.38 Slow Fibonacci Fibs>>at: anIndex self assert: anIndex >= 1. anIndex = 1 ifTrue: [ ^ 1 ]. anIndex = 2 ifTrue: [ ^ 1 ]. ^ (self at: anIndex - 1) + (self at: anIndex - 2) Fibs new at: 35 9227465 Takes 8 seconds. Forget about larger values!
  • 39. © Oscar Nierstrasz ST — Best Practice Patterns 7.39 Cacheing Fibonacci Object subclass: #Fibs instanceVariableNames: 'fibCache' classVariableNames: '' poolDictionaries: '' category: 'Misc' Fibs>>initialize fibCache := Dictionary new Fibs>>fibCache ^ fibCache Introduce the cache …
  • 40. © Oscar Nierstrasz ST — Best Practice Patterns 7.40 Cacheing Fibonacci Fibs>>lookup: anIndex ^ self fibCache at: anIndex ifAbsentPut: [ self at: anIndex ] Fibs>>at: anIndex self assert: anIndex >= 1. anIndex = 1 ifTrue: [ ^ 1 ]. anIndex = 2 ifTrue: [ ^ 1 ]. ^ (self lookup: anIndex - 1) + (self lookup: anIndex - 2) Now we introduce the lookup method, and redirect all accesses to use the cache lookup Fibs new at: 100 354224848179261915075 … is virtually instantaneous!
  • 41. © Oscar Nierstrasz ST — Best Practice Patterns 7.41 Roadmap > Naming conventions > Delegation and Double Dispatch > Conversion and Extension > Being Lazy > Collections, Intervals and Streams
  • 42. © Oscar Nierstrasz ST — Best Practice Patterns 7.42 Comparing Method How do you order objects with respect to each other? > Implement <= to return true if the receiver should be ordered before the argument — <,<=,>,>= are defined for Magnitude and its subclasses. — Implement <= in the “comparing” protocol
  • 43. © Oscar Nierstrasz ST — Best Practice Patterns 7.43 Sorted Collection How do you sort a collection? > Use a Sorted Collection. — Set its sort block if you want to sort by some other criterion than <= #( 'Snakes' 'Ladders' ) asSortedCollection a SortedCollection('Snakes' 'Ladders') #( 'Snakes' 'Ladders' ) asSortedCollection: [:a :b | b<=a ] a SortedCollection('Ladders' 'Snakes') a SortedCollection('Snakes' 'Ladders') #( 'Snakes' 'Ladders' ) asSortedCollection sortBlock: [:a :b | b<=a ]
  • 44. © Oscar Nierstrasz ST — Best Practice Patterns 7.44 Interval How do you code a collection of numbers in a sequence? > Use an Interval with start, stop and optional step value. — Use the Shortcut Constructor methods Number>>to: and Number>>to:by: to build intervals 1 to: 5 (1 to: 5) asSet (10 to: 100 by: 20) asOrderedCollection (1 to: 5) a Set(1 2 3 4 5) an OrderedCollection(10 30 50 70 90)
  • 45. © Oscar Nierstrasz ST — Best Practice Patterns 7.45 Duplicate Removing Set How do you remove the duplicates from a Collection? > Send asSet to the collection 'hello world' asSet a Set(Character space $r $d $e $w $h $l $o)
  • 46. © Oscar Nierstrasz ST — Best Practice Patterns 7.46 Searching Literal How do you test if an object is equal to one of several literal values? > Ask a literal Collection if it includes the element you seek 'aeiou' includes: char asLowercase char = $a | char = $e | char = $i | char = $o | char = $u | char = $A | char = $E | char = $I | char = $O | char = $U
  • 47. © Oscar Nierstrasz ST — Best Practice Patterns 7.47 Concatenation How do you put two collections together? > Send “,” to the first with the second as argument (1 to: 3), (4 to: 6) a Dictionary(#a->1 #b->2 ) (Dictionary newFrom: { #a -> 1}), (Dictionary newFrom: { #b -> 2}) #(1 2 3 4 5 6)
  • 48. © Oscar Nierstrasz ST — Best Practice Patterns 7.48 Concatenating Stream How do you concatenate several Collections? > Use a Stream on a new collection of the result type. writer := WriteStream on: String new. Smalltalk keys do: [ : each | writer nextPutAll: each, '::' ]. writer contents Can be vastly more efficient than building a new collection with each concatenation.
  • 49. © Oscar Nierstrasz ST — Best Practice Patterns 7.49 What you should know! How should you name instance variables? Why should you be suspicious of comments? How does Simple Delegation differ from Self Delegation? When would you use Double Dispatch? Why should you avoid introducing a Converter Method for an object supporting a different protocol? How do you sort a Collection? When should you use Lazy Initialization?
  • 50. © Oscar Nierstrasz ST — Best Practice Patterns 7.50 Can you answer these questions? Which patterns would you use to implement a transactional interface? How can Method Object help you to decompose long methods? Why is it a bad idea to query an object for its class? Why are you less likely to see Double Dispatch in a statically-typed language? How can you avoid Modifying Super? How can you avoid writing case statements? What pattern does Object>>-> illustrate?
  • 51. © Oscar Nierstrasz ST — Introduction 1.51 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. http://www.metroactive.com/papers/metro/09.08.04/covers-0437.html