SlideShare une entreprise Scribd logo
1  sur  52
8. Refactoring and Design Patterns
Birds-eye view
© Oscar Nierstrasz
ST — Introduction
1.2
Beware of misplaced
responsibilities — cluttered code
impacts extensibility.
Beware of misplaced
responsibilities — cluttered code
impacts extensibility.
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.3
Roadmap
> Some Principles
> What is Refactoring?
> The Law of Demeter
> Common Code Smells
> Design Patterns
> The Singleton Pattern
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.4
Literature
> Martin Fowler, Kent Beck, John Brant, William Opdyke and Don
Roberts, Refactoring: Improving the Design of Existing Code,
Addison Wesley, 1999.
> Serge Demeyer, Stéphane Ducasse and Oscar Nierstrasz, Object-
Oriented Reengineering Patterns, Morgan Kaufmann, 2002.
> Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides,
Design Patterns: Elements of Reusable Object-Oriented Software,
Addison Wesley, Reading, Mass., 1995.
> Sherman R. Alpert, Kyle Brown and Bobby Woolf, The Design
Patterns Smalltalk Companion, Addison Wesley, 1998.
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.5
Roadmap
> Some Principles
> What is Refactoring?
> The Law of Demeter
> Common Code Smells
> Design Patterns
> The Singleton Pattern
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.6
The Open-Closed Principle
> Software entities should be open for extension but
closed for modifications.
— Design classes and packages so their functionality can be
extended without modifying the source code
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.7
The Object Manifesto
> Delegation and encapsulation:
— “Don’t do anything you can push off to someone else.”
— “Don’t let anyone else play with you.”
– Joseph Pelrine
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.8
The Programmer Manifesto
> Once and only once
— Avoiding writing the same code more than once
> Don’t ask, tell!
MyWindow>>displayObject: aGrObject
aGrObject displayOn: self
MyWindow>>displayObject: aGrObject
aGrObject isSquare ifTrue: […]
aGrObject isCircle ifTrue: […]
…
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.9
Good Signs of OO Thinking
> Short methods
— Simple method logic
> Few instance variables
> Clear object responsibilities
— State the purpose of the class in one sentence
— No super-intelligent objects
— No manager objects
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.10
Some Principles
> The Dependency Inversion Principle
— Depend on abstractions, not concrete implementations
– Write to an interface, not a class
> The Interface Segregation Principle
— Many small interfaces are better than one “fat” one
> The Acyclic Dependencies Principle
— Dependencies between package must not form cycles.
– Break cycles by forming new packages
http://www.objectmentor.com/resources/articles/Principles_and_Patterns.PDF
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.11
Packages, Modules and other
> The Common Closure Principle
— Classes that change together, belong together
– Classes within a released component should share common
closure. That is, if one needs to be changed, they all are likely to
need to be changed.
> The Common Reuse Principle
— Classes that aren’t reused together don’t belong together
– The classes in a package are reused together. If you reuse one of
the classes in a package, you reuse them all.
http://www.objectmentor.com/resources/articles/Principles_and_Patterns.PDF
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.12
Roadmap
> Some Principles
> What is Refactoring?
> The Law of Demeter
> Common Code Smells
> Design Patterns
> The Singleton Pattern
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.13
What is Refactoring?
> The process of changing a software system in such a
way that it does not alter the external behaviour of the
code, yet improves its internal structure.
— Fowler, et al., Refactoring, 1999.
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.14
Refactoring in the Package Browser
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.15
Typical Refactorings
Class Refactorings Method Refactorings Attribute
Refactorings
add (sub)class to hierarchy add method to class add variable to class
rename class rename method rename variable
remove class remove method remove variable
push method down push variable down
push method up pull variable up
add parameter to method create accessors
move method to component abstract variable
extract code in new method
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.16
Why Refactor?
“Grow, don’t build software”
— Fred Brooks
> The reality:
— Extremely difficult to get the design “right” the first time
— Hard to fully understand the problem domain
— Hard to understand user requirements, even if the user does!
— Hard to know how the system will evolve in five years
— Original design is often inadequate
— System becomes brittle over time, and more difficult to change
> Refactoring helps you to
— Manipulate code in a safe environment (behavior preserving)
— Recreate a situation where evolution is possible
— Understand existing code
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.17
Rename Method — manual steps
> Do it yourself approach:
— Check that no method with the new name already exists in any
subclass or superclass.
— Browse all the implementers (method definitions)
— Browse all the senders (method invocations)
— Edit and rename all implementers
— Edit and rename all senders
— Remove all implementers
— Test
> Automated refactoring is better !
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.18
Rename Method
> Rename Method (method, new name)
> Preconditions
— No method with the new name already exists in any subclass or
superclass.
— No methods with same signature as method outside the
inheritance hierarchy of method
> PostConditions
— method has new name
— relevant methods in the inheritance hierarchy have new name
— invocations of changed method are updated to new name
> Other Considerations
— Typed/Dynamically Typed Languages => Scope of the
renaming
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.19
Roadmap
> Some Principles
> What is Refactoring?
> The Law of Demeter
> Common Code Smells
> Design Patterns
> The Singleton Pattern
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.20
The Law of Demeter
> “Do not talk to strangers”
— You should only send messages to:
– an argument passed to you
– an object you create
– self, super
– your class
> Don’t send messages to objects returned from other
message sends
en.wikipedia.org/wiki/Law_Of_Demeter
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.21
Law of Demeter by Example
NodeManager>>declareNewNode: aNode
|nodeDescription|
(aNode isValid) "OK — passed as an argument to me"
ifTrue: [ aNode certified].
nodeDescription := NodeDescription for: aNode.
nodeDescription localTime. ”OK — I created it"
self addNodeDescription: nodeDescription.
”OK — I can talk to myself"
nodeDescription data "Wrong! I should not know"
at: self creatorKey "that data is a dictionary"
put: self creator
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.22
The Dark Side of the Law of Demeter
Class A
instVar: myCollection
A>>do: aBlock
myCollection do: aBlock
A>>collect: aBlock
^ myCollection collect: aBlock
A>>select: aBlock
^ myCollection select: aBlock
A>>detect: aBlock
^ myCollection detect: aBlock
A>>isEmpty
^ myCollection isEmpty
To avoid giving direct
access to instance
variables, you may
need to introduce
many delegating
methods …
Traits can help — see
final lecture
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.23
Curing Navigation Code
> Iteratively move behaviour close to data
— Use Extract Method and Move Method
See: Object-Oriented Reengineering Patterns
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.24
The Law of Demeter, violated
Indirect
Provider
doSomething()
Intermediate
Provider
+provider
getProvider()
Indirect
Client
intermediate.provider.doSomething()
or
intermediate.getProvider().doSomething()
provider intermediate
Law of Demeter: A method "M" of an object "O" should invoke only the
methods of the following kinds of objects.
1. itself 3. any object it creates /instantiates
2. its parameters 4. its direct component objects
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.25
Eliminate Navigation Code
…
engine.carburetor.fuelValveOpen = true
Engine
+carburetor
Car
-engine
+increaseSpeed()
Carburetor
+fuelValveOpen
Engine
-carburetor
+speedUp()
Car
-engine
+increaseSpeed()
…
engine.speedUp()
carburetor.fuelValveOpen = true
Carburetor
+fuelValveOpen
Car
-engine
+increaseSpeed()
Carburetor
-fuelValveOpen
+openFuelValve()
Engine
-carburetor
+speedUp()
carburetor.openFuelValve()fuelValveOpen = true
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.26
Roadmap
> Some Principles
> What is Refactoring?
> The Law of Demeter
> Common Code Smells
> Design Patterns
> The Singleton Pattern
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.27
Misplaced Methods
> Avoid implementing a method which neither accesses
instance variables nor accesses any state
— Probably belongs in one of the classes of the objects it does
send to
Klimas, et al., Smalltalk with Style
MyClass>>pop: anOrderedCollection
anOrderedCollection removeFirst.
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.28
Code Smells
“If it stinks, change it”
— Grandma Beck
— Duplicated Code
– Missing inheritance or delegation
— Long Method
– Inadequate decomposition
— Large Class / God Class
— Too many responsibilities
— Long Parameter List
— Object is missing
— Type Tests
— Missing polymorphism
— Shotgun Surgery
— Small changes affect too many objects
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.29
Code Smells
— Feature Envy
– Method needing too much information from another object
— Data Clumps
– Data always used together (x,y -> point)
— Parallel Inheritance Hierarchies
– Changes in one hierarchy require change in another hierarchy
— Lazy Class
– Does too little
— Middle Man
– Class with too many delegating methods
— Temporary Field
– Attributes only used partially under certain circumstances
— Data Classes
– Only accessors
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.30
Curing Long Methods
> Long methods
— Decompose into smaller methods
— Self sends should read like a script
— Comments are good delimiters
— A method is the smallest unit of overriding
self setUp; run; tearDown.
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.31
Curing Duplicated Code
> In the same class
— Extract Method
> Between two sibling subclasses
— Extract Method
— Push identical methods up to common superclass
— Form Template Method
> Between unrelated class
— Create common superclass
— Move to Component
— Extract Component (e.g., Strategy)
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.32
Curing God Class
> God Class
— Incrementally redistribute responsibilities to existing (or
extracted) collaborating classes
— Find logical sub-components
– Set of related working methods/instance variables
— Move methods and instance variables into components
— Extract component
— Extract Subclass
– If not using all the instance variables
See: Object-Oriented Reengineering Patterns
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.33
Curing Type Tests
> Missing Polymorphism
— Tell, don’t ask!
— Shift case bodies to (new) methods of object being tested
— Self type checks:
– Introduce hook methods and new subclasses
— Client type checks
– Introduce “tell” method into client hierarchy
— Possibly introduce State / Strategy or Null Object Design
Patterns
See: Object-Oriented Reengineering Patterns
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.34
Transformation
A
init()
Client
a : A
m()
switch (a.class)
case B: a.init(); ((B) a).x();
case C: a.init(); ((C)) a).y();
Case D: ((D) a).z()
B
x()
C
init()
Y()
D
z()
this.init (); this.x();
this.init (); this.y();
Client
a : A
m()
a.doit();
A
init()
doit()
B
x()
doit()
C
init()
Y()
doit()
D
z()
doit()
this.z();
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.35
Roadmap
> Some Principles
> What is Refactoring?
> The Law of Demeter
> Common Code Smells
> Design Patterns
> The Singleton Pattern
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.36
Design Patterns
> Design Patterns document recurrent solutions to design
problems
— They have names
– Composite, Visitor, Observer...
— They are not components!
— Design Patterns entail tradeoffs
— Will be implemented in different ways in different contexts
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.37
Why Design Patterns?
> Smart
— Elegant solutions that a novice would not think of
> Generic
— Independent of specific system type, language
> Well-proven
— Successfully tested in several systems
> Simple
— Combine them for more complex solutions
> Caveat
— Not everything that is called a “pattern” fulfils these criteria!
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.38
> Design Patterns are not “good” just because they are
patterns
— It is just as important to understand when not to use a Design
Pattern
— Every Design Pattern has tradeoffs
— Most Design Patterns will make your design more complicated
– More classes, more indirections, more messages
— Don’t use Design Patterns unless you really need them!
Alert!!! Patterns are invading!
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.39
About Pattern Implementation
> Do not confuse structure and intent!
— Design Patterns document a possible implementation
– Not a definitive one
— Design Patterns are about intent and tradeoffs
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.40
Common Design Patterns
Pattern Intent
Adapter
Convert the interface of a class into another
interface clients expect.
Proxy
Provide a surrogate or placeholder for
another object to control access to it.
Composite
Compose objects into part-whole hierarchies
so that clients can treat individual objects
and compositions uniformly.
Template Method
Define the skeleton of an algorithm in an
operation, deferring some steps so they can
be redefined by subclasses.
What tradeoffs do these patterns introduce?
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.41
Roadmap
> Some Principles
> What is Refactoring?
> The Law of Demeter
> Common Code Smells
> Design Patterns
> The Singleton Pattern
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.42
The Singleton Pattern
Intent:
> Ensure that a class has only one instance, and provide a
global point of access to it
Problem:
> We want a class with a unique instance.
Solution:
> Give the class the responsibility to initialize and provide
access to the unique instance. Forbid creation of new
instances.
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.43
Singleton Structure
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.44
Object subclass: #SystemChangeNotifier
instanceVariableNames: 'eventSource silenceLevel'
classVariableNames: 'UniqueInstance'
poolDictionaries: ''
category: 'System-Change Notification'
SystemChangeNotifier class
instanceVariableNames: ''
SystemChangeNotifier class>>new
^self error: self instanceCreationErrorString
SystemChangeNotifier class>>uniqueInstance
UniqueInstance ifNil: [UniqueInstance := self createInstance].
^UniqueInstance
Singleton Example: SystemChangeNotifier
NB: This example uses a class variable
rather than a class instance variable.
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.45
Singleton Example:
ChangeSet class
instanceVariableNames: 'current'
ChangeSet class>>new
^ self basicNewChangeSet: ChangeSet defaultName
ChangeSet class>>newChanges: aChangeSet
SystemChangeNotifier uniqueInstance noMoreNotificationsFor: current.
current isolationSet: nil.
current := aChangeSet.
…
ChangeSet class>>current
^ current
Here we have many instances, but only a Singleton is active.
A class instance variable is used. new is not forbidden.
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.46
Implementation Issues
> Class variable
— One singleton for a complete hierarchy
> Class instance variable
— One singleton per class
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.47
Implementation Issues
> Singletons may be accessed via a global variable
— E.g., NotificationManager uniqueInstance notifier
> Global Variable vs. Class Method Access
— Global Variable Access is dangerous: if we reassign Notifier we
lose all references to the current window.
— Class Method Access is better because it provides a single
access point.
SessionModel>>startupWindowSystem
Notifier initializeWindowHandles.
...
oldWindows := Notifier windows.
Notifier initialize.
...
^oldWindows
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.48
Implementation Issues
> Persistent Singleton:
— only one instance exists and its identity does not change
– E.g., notification manager
> Transient Singleton:
— only one instance exists at any time, but that instance changes
– E.g., current session
> Single Active Instance Singleton:
— a single instance is active at any point in time, but other dormant
instances may also exist.
– E.g., active project
Singleton is about time, not access
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.49
Access using new — not a good idea
> The intent (uniqueness) is not clear anymore!
— new is normally used to return newly created instances. The
programmer does not expect this:
Singleton class>>new
^self uniqueInstance
|screen1 screen2|
screen1 := Screen new.
screen2 := Screen uniqueInstance
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.50
What you should know!
How does the Open-Closed Principle apply to OOP?
What are signs that an object has clearly-defined
responsibilities?
How can you recognize misplaced methods?
How should you refactor long methods?
How can you eliminate duplicated code between
unrelated classes?
Why are type tests a code smell?
When do design patterns themselves turn into code
smells?
Why is it a bad idea to use global variables to store
Singleton instances?
© Oscar Nierstrasz
ST — Refactoring and Design Patterns
8.51
Can you answer these questions?
How do the Common Closure and Common Reuse
Principles alter the usual notion of cohesion?
How does refactoring differ from reengineering?
Can refactoring be fully automated?
In what situations does the Law of Demeter not apply?
How do design patterns make use of delegation?
Why are Long Parameter Lists a code smell?
Are isNil tests a code smell? What design pattern
could help you eliminate them?
Is the Smalltalk SystemDictionary a good example of a
Singleton?
© Oscar Nierstrasz
ST — Introduction
1.52
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/

Contenu connexe

Tendances

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
 
Cassandra Day Atlanta 2015: Data Modeling 101
Cassandra Day Atlanta 2015: Data Modeling 101Cassandra Day Atlanta 2015: Data Modeling 101
Cassandra Day Atlanta 2015: Data Modeling 101DataStax Academy
 
Collaborative Cuisine's 1 Hour JNDI Cookbook
Collaborative Cuisine's 1 Hour JNDI CookbookCollaborative Cuisine's 1 Hour JNDI Cookbook
Collaborative Cuisine's 1 Hour JNDI CookbookKen Lin
 
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
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVMMario Fusco
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with ClojureJohn Stevenson
 
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 inheritanceKuntal Bhowmick
 
Sedna XML Database: Memory Management
Sedna XML Database: Memory ManagementSedna XML Database: Memory Management
Sedna XML Database: Memory ManagementIvan Shcheklein
 
NoSQL - Cassandra & MongoDB.pptx
NoSQL -  Cassandra & MongoDB.pptxNoSQL -  Cassandra & MongoDB.pptx
NoSQL - Cassandra & MongoDB.pptxNaveen Kumar
 

Tendances (14)

8 - OOP - Syntax & Messages
8 - OOP - Syntax & Messages8 - OOP - Syntax & Messages
8 - OOP - Syntax & Messages
 
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
 
Drools
DroolsDrools
Drools
 
Cassandra Day Atlanta 2015: Data Modeling 101
Cassandra Day Atlanta 2015: Data Modeling 101Cassandra Day Atlanta 2015: Data Modeling 101
Cassandra Day Atlanta 2015: Data Modeling 101
 
Collaborative Cuisine's 1 Hour JNDI Cookbook
Collaborative Cuisine's 1 Hour JNDI CookbookCollaborative Cuisine's 1 Hour JNDI Cookbook
Collaborative Cuisine's 1 Hour JNDI Cookbook
 
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
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVM
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
 
4 - OOP - Taste of Smalltalk (Squeak)
4 - OOP - Taste of Smalltalk (Squeak)4 - OOP - Taste of Smalltalk (Squeak)
4 - OOP - Taste of Smalltalk (Squeak)
 
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
 
SAX PARSER
SAX PARSER SAX PARSER
SAX PARSER
 
Sedna XML Database: Memory Management
Sedna XML Database: Memory ManagementSedna XML Database: Memory Management
Sedna XML Database: Memory Management
 
NoSQL - Cassandra & MongoDB.pptx
NoSQL -  Cassandra & MongoDB.pptxNoSQL -  Cassandra & MongoDB.pptx
NoSQL - Cassandra & MongoDB.pptx
 

En vedette (20)

10 - OOP - Inheritance (a)
10 - OOP - Inheritance (a)10 - OOP - Inheritance (a)
10 - OOP - Inheritance (a)
 
Stoop 450-s unit
Stoop 450-s unitStoop 450-s unit
Stoop 450-s unit
 
Stoop 400 o-metaclassonly
Stoop 400 o-metaclassonlyStoop 400 o-metaclassonly
Stoop 400 o-metaclassonly
 
Stoop 416-lsp
Stoop 416-lspStoop 416-lsp
Stoop 416-lsp
 
5 - OOP - Smalltalk in a Nutshell (c)
5 - OOP - Smalltalk in a Nutshell (c)5 - OOP - Smalltalk in a Nutshell (c)
5 - OOP - Smalltalk in a Nutshell (c)
 
14 - Exceptions
14 - Exceptions14 - Exceptions
14 - Exceptions
 
Stoop 431-visitor
Stoop 431-visitorStoop 431-visitor
Stoop 431-visitor
 
Stoop 300-block optimizationinvw
Stoop 300-block optimizationinvwStoop 300-block optimizationinvw
Stoop 300-block optimizationinvw
 
8 - OOP - Smalltalk Model
8 - OOP - Smalltalk Model8 - OOP - Smalltalk Model
8 - OOP - Smalltalk Model
 
01 intro
01 intro01 intro
01 intro
 
09 metaclasses
09 metaclasses09 metaclasses
09 metaclasses
 
Stoop 433-chain
Stoop 433-chainStoop 433-chain
Stoop 433-chain
 
Stoop 434-composite
Stoop 434-compositeStoop 434-composite
Stoop 434-composite
 
03 standardclasses
03 standardclasses03 standardclasses
03 standardclasses
 
Stoop 414-smalltalk elementsofdesign
Stoop 414-smalltalk elementsofdesignStoop 414-smalltalk elementsofdesign
Stoop 414-smalltalk elementsofdesign
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
Double Dispatch
Double DispatchDouble Dispatch
Double Dispatch
 
Stoop ed-lod
Stoop ed-lodStoop ed-lod
Stoop ed-lod
 
Stoop 423-some designpatterns
Stoop 423-some designpatternsStoop 423-some designpatterns
Stoop 423-some designpatterns
 
Stoop sed-sharing ornot
Stoop sed-sharing ornotStoop sed-sharing ornot
Stoop sed-sharing ornot
 

Similaire à Refactoring Design Patterns

Beyond Text - Methods as Objects
Beyond Text - Methods as ObjectsBeyond Text - Methods as Objects
Beyond Text - Methods as ObjectsMarcus Denker
 
5 Design Patterns Explained
5 Design Patterns Explained5 Design Patterns Explained
5 Design Patterns ExplainedPrabhjit Singh
 
Applying Design Principles in Practice - ISEC 2015 Tutorial
Applying Design Principles in Practice - ISEC 2015 TutorialApplying Design Principles in Practice - ISEC 2015 Tutorial
Applying Design Principles in Practice - ISEC 2015 TutorialGanesh Samarthyam
 
Applying Design Principles in Practice
Applying Design Principles in PracticeApplying Design Principles in Practice
Applying Design Principles in PracticeTushar Sharma
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCAndy Butland
 
Software Patterns
Software PatternsSoftware Patterns
Software Patternskim.mens
 
Sub-method Structural and Behavioral Reflection
Sub-method Structural and Behavioral ReflectionSub-method Structural and Behavioral Reflection
Sub-method Structural and Behavioral ReflectionMarcus Denker
 
Modular ObjectLens
Modular ObjectLensModular ObjectLens
Modular ObjectLensESUG
 
Design Pattern Notes: Nagpur University
Design Pattern Notes: Nagpur UniversityDesign Pattern Notes: Nagpur University
Design Pattern Notes: Nagpur UniversityShubham Narkhede
 
Advanced OOP - Laws, Principles, Idioms
Advanced OOP - Laws, Principles, IdiomsAdvanced OOP - Laws, Principles, Idioms
Advanced OOP - Laws, Principles, IdiomsClint Edmonson
 

Similaire à Refactoring Design Patterns (20)

Refactoring
RefactoringRefactoring
Refactoring
 
Lecture: Reflection
Lecture: ReflectionLecture: Reflection
Lecture: Reflection
 
Beyond Text - Methods as Objects
Beyond Text - Methods as ObjectsBeyond Text - Methods as Objects
Beyond Text - Methods as Objects
 
5 Design Patterns Explained
5 Design Patterns Explained5 Design Patterns Explained
5 Design Patterns Explained
 
Applying Design Principles in Practice - ISEC 2015 Tutorial
Applying Design Principles in Practice - ISEC 2015 TutorialApplying Design Principles in Practice - ISEC 2015 Tutorial
Applying Design Principles in Practice - ISEC 2015 Tutorial
 
Applying Design Principles in Practice
Applying Design Principles in PracticeApplying Design Principles in Practice
Applying Design Principles in Practice
 
Lecture: Reflection
Lecture: ReflectionLecture: Reflection
Lecture: Reflection
 
L03 Design Patterns
L03 Design PatternsL03 Design Patterns
L03 Design Patterns
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVC
 
Software Patterns
Software PatternsSoftware Patterns
Software Patterns
 
Reflection
ReflectionReflection
Reflection
 
Reflectivity Demo
Reflectivity DemoReflectivity Demo
Reflectivity Demo
 
Sub-method Structural and Behavioral Reflection
Sub-method Structural and Behavioral ReflectionSub-method Structural and Behavioral Reflection
Sub-method Structural and Behavioral Reflection
 
Modular ObjectLens
Modular ObjectLensModular ObjectLens
Modular ObjectLens
 
Stoop 305-reflective programming5
Stoop 305-reflective programming5Stoop 305-reflective programming5
Stoop 305-reflective programming5
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
L05 Design Patterns
L05 Design PatternsL05 Design Patterns
L05 Design Patterns
 
Design Pattern Notes: Nagpur University
Design Pattern Notes: Nagpur UniversityDesign Pattern Notes: Nagpur University
Design Pattern Notes: Nagpur University
 
Clean Code V2
Clean Code V2Clean Code V2
Clean Code V2
 
Advanced OOP - Laws, Principles, Idioms
Advanced OOP - Laws, Principles, IdiomsAdvanced OOP - Laws, Principles, Idioms
Advanced OOP - Laws, Principles, Idioms
 

Plus de The World of Smalltalk (15)

05 seaside canvas
05 seaside canvas05 seaside canvas
05 seaside canvas
 
06 debugging
06 debugging06 debugging
06 debugging
 
02 basics
02 basics02 basics
02 basics
 
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-unit ofreuse
Stoop ed-unit ofreuseStoop ed-unit ofreuse
Stoop ed-unit ofreuse
 
Stoop ed-subtyping subclassing
Stoop ed-subtyping subclassingStoop ed-subtyping subclassing
Stoop ed-subtyping subclassing
 
Stoop ed-some principles
Stoop ed-some principlesStoop ed-some principles
Stoop ed-some principles
 
Stoop ed-inheritance composition
Stoop ed-inheritance compositionStoop ed-inheritance composition
Stoop ed-inheritance composition
 
Stoop ed-frameworks
Stoop ed-frameworksStoop ed-frameworks
Stoop ed-frameworks
 
Stoop ed-dual interface
Stoop ed-dual interfaceStoop ed-dual interface
Stoop ed-dual interface
 
Stoop ed-class forreuse
Stoop ed-class forreuseStoop ed-class forreuse
Stoop ed-class forreuse
 
Stoop 440-adaptor
Stoop 440-adaptorStoop 440-adaptor
Stoop 440-adaptor
 
Stoop 439-decorator
Stoop 439-decoratorStoop 439-decorator
Stoop 439-decorator
 

Dernier

AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 

Dernier (20)

AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 

Refactoring Design Patterns

  • 1. 8. Refactoring and Design Patterns
  • 2. Birds-eye view © Oscar Nierstrasz ST — Introduction 1.2 Beware of misplaced responsibilities — cluttered code impacts extensibility. Beware of misplaced responsibilities — cluttered code impacts extensibility.
  • 3. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.3 Roadmap > Some Principles > What is Refactoring? > The Law of Demeter > Common Code Smells > Design Patterns > The Singleton Pattern
  • 4. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.4 Literature > Martin Fowler, Kent Beck, John Brant, William Opdyke and Don Roberts, Refactoring: Improving the Design of Existing Code, Addison Wesley, 1999. > Serge Demeyer, Stéphane Ducasse and Oscar Nierstrasz, Object- Oriented Reengineering Patterns, Morgan Kaufmann, 2002. > Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software, Addison Wesley, Reading, Mass., 1995. > Sherman R. Alpert, Kyle Brown and Bobby Woolf, The Design Patterns Smalltalk Companion, Addison Wesley, 1998.
  • 5. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.5 Roadmap > Some Principles > What is Refactoring? > The Law of Demeter > Common Code Smells > Design Patterns > The Singleton Pattern
  • 6. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.6 The Open-Closed Principle > Software entities should be open for extension but closed for modifications. — Design classes and packages so their functionality can be extended without modifying the source code
  • 7. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.7 The Object Manifesto > Delegation and encapsulation: — “Don’t do anything you can push off to someone else.” — “Don’t let anyone else play with you.” – Joseph Pelrine
  • 8. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.8 The Programmer Manifesto > Once and only once — Avoiding writing the same code more than once > Don’t ask, tell! MyWindow>>displayObject: aGrObject aGrObject displayOn: self MyWindow>>displayObject: aGrObject aGrObject isSquare ifTrue: […] aGrObject isCircle ifTrue: […] …
  • 9. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.9 Good Signs of OO Thinking > Short methods — Simple method logic > Few instance variables > Clear object responsibilities — State the purpose of the class in one sentence — No super-intelligent objects — No manager objects
  • 10. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.10 Some Principles > The Dependency Inversion Principle — Depend on abstractions, not concrete implementations – Write to an interface, not a class > The Interface Segregation Principle — Many small interfaces are better than one “fat” one > The Acyclic Dependencies Principle — Dependencies between package must not form cycles. – Break cycles by forming new packages http://www.objectmentor.com/resources/articles/Principles_and_Patterns.PDF
  • 11. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.11 Packages, Modules and other > The Common Closure Principle — Classes that change together, belong together – Classes within a released component should share common closure. That is, if one needs to be changed, they all are likely to need to be changed. > The Common Reuse Principle — Classes that aren’t reused together don’t belong together – The classes in a package are reused together. If you reuse one of the classes in a package, you reuse them all. http://www.objectmentor.com/resources/articles/Principles_and_Patterns.PDF
  • 12. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.12 Roadmap > Some Principles > What is Refactoring? > The Law of Demeter > Common Code Smells > Design Patterns > The Singleton Pattern
  • 13. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.13 What is Refactoring? > The process of changing a software system in such a way that it does not alter the external behaviour of the code, yet improves its internal structure. — Fowler, et al., Refactoring, 1999.
  • 14. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.14 Refactoring in the Package Browser
  • 15. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.15 Typical Refactorings Class Refactorings Method Refactorings Attribute Refactorings add (sub)class to hierarchy add method to class add variable to class rename class rename method rename variable remove class remove method remove variable push method down push variable down push method up pull variable up add parameter to method create accessors move method to component abstract variable extract code in new method
  • 16. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.16 Why Refactor? “Grow, don’t build software” — Fred Brooks > The reality: — Extremely difficult to get the design “right” the first time — Hard to fully understand the problem domain — Hard to understand user requirements, even if the user does! — Hard to know how the system will evolve in five years — Original design is often inadequate — System becomes brittle over time, and more difficult to change > Refactoring helps you to — Manipulate code in a safe environment (behavior preserving) — Recreate a situation where evolution is possible — Understand existing code
  • 17. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.17 Rename Method — manual steps > Do it yourself approach: — Check that no method with the new name already exists in any subclass or superclass. — Browse all the implementers (method definitions) — Browse all the senders (method invocations) — Edit and rename all implementers — Edit and rename all senders — Remove all implementers — Test > Automated refactoring is better !
  • 18. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.18 Rename Method > Rename Method (method, new name) > Preconditions — No method with the new name already exists in any subclass or superclass. — No methods with same signature as method outside the inheritance hierarchy of method > PostConditions — method has new name — relevant methods in the inheritance hierarchy have new name — invocations of changed method are updated to new name > Other Considerations — Typed/Dynamically Typed Languages => Scope of the renaming
  • 19. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.19 Roadmap > Some Principles > What is Refactoring? > The Law of Demeter > Common Code Smells > Design Patterns > The Singleton Pattern
  • 20. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.20 The Law of Demeter > “Do not talk to strangers” — You should only send messages to: – an argument passed to you – an object you create – self, super – your class > Don’t send messages to objects returned from other message sends en.wikipedia.org/wiki/Law_Of_Demeter
  • 21. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.21 Law of Demeter by Example NodeManager>>declareNewNode: aNode |nodeDescription| (aNode isValid) "OK — passed as an argument to me" ifTrue: [ aNode certified]. nodeDescription := NodeDescription for: aNode. nodeDescription localTime. ”OK — I created it" self addNodeDescription: nodeDescription. ”OK — I can talk to myself" nodeDescription data "Wrong! I should not know" at: self creatorKey "that data is a dictionary" put: self creator
  • 22. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.22 The Dark Side of the Law of Demeter Class A instVar: myCollection A>>do: aBlock myCollection do: aBlock A>>collect: aBlock ^ myCollection collect: aBlock A>>select: aBlock ^ myCollection select: aBlock A>>detect: aBlock ^ myCollection detect: aBlock A>>isEmpty ^ myCollection isEmpty To avoid giving direct access to instance variables, you may need to introduce many delegating methods … Traits can help — see final lecture
  • 23. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.23 Curing Navigation Code > Iteratively move behaviour close to data — Use Extract Method and Move Method See: Object-Oriented Reengineering Patterns
  • 24. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.24 The Law of Demeter, violated Indirect Provider doSomething() Intermediate Provider +provider getProvider() Indirect Client intermediate.provider.doSomething() or intermediate.getProvider().doSomething() provider intermediate Law of Demeter: A method "M" of an object "O" should invoke only the methods of the following kinds of objects. 1. itself 3. any object it creates /instantiates 2. its parameters 4. its direct component objects
  • 25. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.25 Eliminate Navigation Code … engine.carburetor.fuelValveOpen = true Engine +carburetor Car -engine +increaseSpeed() Carburetor +fuelValveOpen Engine -carburetor +speedUp() Car -engine +increaseSpeed() … engine.speedUp() carburetor.fuelValveOpen = true Carburetor +fuelValveOpen Car -engine +increaseSpeed() Carburetor -fuelValveOpen +openFuelValve() Engine -carburetor +speedUp() carburetor.openFuelValve()fuelValveOpen = true
  • 26. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.26 Roadmap > Some Principles > What is Refactoring? > The Law of Demeter > Common Code Smells > Design Patterns > The Singleton Pattern
  • 27. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.27 Misplaced Methods > Avoid implementing a method which neither accesses instance variables nor accesses any state — Probably belongs in one of the classes of the objects it does send to Klimas, et al., Smalltalk with Style MyClass>>pop: anOrderedCollection anOrderedCollection removeFirst.
  • 28. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.28 Code Smells “If it stinks, change it” — Grandma Beck — Duplicated Code – Missing inheritance or delegation — Long Method – Inadequate decomposition — Large Class / God Class — Too many responsibilities — Long Parameter List — Object is missing — Type Tests — Missing polymorphism — Shotgun Surgery — Small changes affect too many objects
  • 29. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.29 Code Smells — Feature Envy – Method needing too much information from another object — Data Clumps – Data always used together (x,y -> point) — Parallel Inheritance Hierarchies – Changes in one hierarchy require change in another hierarchy — Lazy Class – Does too little — Middle Man – Class with too many delegating methods — Temporary Field – Attributes only used partially under certain circumstances — Data Classes – Only accessors
  • 30. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.30 Curing Long Methods > Long methods — Decompose into smaller methods — Self sends should read like a script — Comments are good delimiters — A method is the smallest unit of overriding self setUp; run; tearDown.
  • 31. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.31 Curing Duplicated Code > In the same class — Extract Method > Between two sibling subclasses — Extract Method — Push identical methods up to common superclass — Form Template Method > Between unrelated class — Create common superclass — Move to Component — Extract Component (e.g., Strategy)
  • 32. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.32 Curing God Class > God Class — Incrementally redistribute responsibilities to existing (or extracted) collaborating classes — Find logical sub-components – Set of related working methods/instance variables — Move methods and instance variables into components — Extract component — Extract Subclass – If not using all the instance variables See: Object-Oriented Reengineering Patterns
  • 33. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.33 Curing Type Tests > Missing Polymorphism — Tell, don’t ask! — Shift case bodies to (new) methods of object being tested — Self type checks: – Introduce hook methods and new subclasses — Client type checks – Introduce “tell” method into client hierarchy — Possibly introduce State / Strategy or Null Object Design Patterns See: Object-Oriented Reengineering Patterns
  • 34. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.34 Transformation A init() Client a : A m() switch (a.class) case B: a.init(); ((B) a).x(); case C: a.init(); ((C)) a).y(); Case D: ((D) a).z() B x() C init() Y() D z() this.init (); this.x(); this.init (); this.y(); Client a : A m() a.doit(); A init() doit() B x() doit() C init() Y() doit() D z() doit() this.z();
  • 35. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.35 Roadmap > Some Principles > What is Refactoring? > The Law of Demeter > Common Code Smells > Design Patterns > The Singleton Pattern
  • 36. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.36 Design Patterns > Design Patterns document recurrent solutions to design problems — They have names – Composite, Visitor, Observer... — They are not components! — Design Patterns entail tradeoffs — Will be implemented in different ways in different contexts
  • 37. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.37 Why Design Patterns? > Smart — Elegant solutions that a novice would not think of > Generic — Independent of specific system type, language > Well-proven — Successfully tested in several systems > Simple — Combine them for more complex solutions > Caveat — Not everything that is called a “pattern” fulfils these criteria!
  • 38. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.38 > Design Patterns are not “good” just because they are patterns — It is just as important to understand when not to use a Design Pattern — Every Design Pattern has tradeoffs — Most Design Patterns will make your design more complicated – More classes, more indirections, more messages — Don’t use Design Patterns unless you really need them! Alert!!! Patterns are invading!
  • 39. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.39 About Pattern Implementation > Do not confuse structure and intent! — Design Patterns document a possible implementation – Not a definitive one — Design Patterns are about intent and tradeoffs
  • 40. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.40 Common Design Patterns Pattern Intent Adapter Convert the interface of a class into another interface clients expect. Proxy Provide a surrogate or placeholder for another object to control access to it. Composite Compose objects into part-whole hierarchies so that clients can treat individual objects and compositions uniformly. Template Method Define the skeleton of an algorithm in an operation, deferring some steps so they can be redefined by subclasses. What tradeoffs do these patterns introduce?
  • 41. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.41 Roadmap > Some Principles > What is Refactoring? > The Law of Demeter > Common Code Smells > Design Patterns > The Singleton Pattern
  • 42. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.42 The Singleton Pattern Intent: > Ensure that a class has only one instance, and provide a global point of access to it Problem: > We want a class with a unique instance. Solution: > Give the class the responsibility to initialize and provide access to the unique instance. Forbid creation of new instances.
  • 43. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.43 Singleton Structure
  • 44. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.44 Object subclass: #SystemChangeNotifier instanceVariableNames: 'eventSource silenceLevel' classVariableNames: 'UniqueInstance' poolDictionaries: '' category: 'System-Change Notification' SystemChangeNotifier class instanceVariableNames: '' SystemChangeNotifier class>>new ^self error: self instanceCreationErrorString SystemChangeNotifier class>>uniqueInstance UniqueInstance ifNil: [UniqueInstance := self createInstance]. ^UniqueInstance Singleton Example: SystemChangeNotifier NB: This example uses a class variable rather than a class instance variable.
  • 45. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.45 Singleton Example: ChangeSet class instanceVariableNames: 'current' ChangeSet class>>new ^ self basicNewChangeSet: ChangeSet defaultName ChangeSet class>>newChanges: aChangeSet SystemChangeNotifier uniqueInstance noMoreNotificationsFor: current. current isolationSet: nil. current := aChangeSet. … ChangeSet class>>current ^ current Here we have many instances, but only a Singleton is active. A class instance variable is used. new is not forbidden.
  • 46. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.46 Implementation Issues > Class variable — One singleton for a complete hierarchy > Class instance variable — One singleton per class
  • 47. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.47 Implementation Issues > Singletons may be accessed via a global variable — E.g., NotificationManager uniqueInstance notifier > Global Variable vs. Class Method Access — Global Variable Access is dangerous: if we reassign Notifier we lose all references to the current window. — Class Method Access is better because it provides a single access point. SessionModel>>startupWindowSystem Notifier initializeWindowHandles. ... oldWindows := Notifier windows. Notifier initialize. ... ^oldWindows
  • 48. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.48 Implementation Issues > Persistent Singleton: — only one instance exists and its identity does not change – E.g., notification manager > Transient Singleton: — only one instance exists at any time, but that instance changes – E.g., current session > Single Active Instance Singleton: — a single instance is active at any point in time, but other dormant instances may also exist. – E.g., active project Singleton is about time, not access
  • 49. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.49 Access using new — not a good idea > The intent (uniqueness) is not clear anymore! — new is normally used to return newly created instances. The programmer does not expect this: Singleton class>>new ^self uniqueInstance |screen1 screen2| screen1 := Screen new. screen2 := Screen uniqueInstance
  • 50. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.50 What you should know! How does the Open-Closed Principle apply to OOP? What are signs that an object has clearly-defined responsibilities? How can you recognize misplaced methods? How should you refactor long methods? How can you eliminate duplicated code between unrelated classes? Why are type tests a code smell? When do design patterns themselves turn into code smells? Why is it a bad idea to use global variables to store Singleton instances?
  • 51. © Oscar Nierstrasz ST — Refactoring and Design Patterns 8.51 Can you answer these questions? How do the Common Closure and Common Reuse Principles alter the usual notion of cohesion? How does refactoring differ from reengineering? Can refactoring be fully automated? In what situations does the Law of Demeter not apply? How do design patterns make use of delegation? Why are Long Parameter Lists a code smell? Are isNil tests a code smell? What design pattern could help you eliminate them? Is the Smalltalk SystemDictionary a good example of a Singleton?
  • 52. © Oscar Nierstrasz ST — Introduction 1.52 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/

Notes de l'éditeur

  1. Tinguely car http://www.jaunted.com/story/2006/7/14/55234/2992/travel/When+Garbage+is+More+Than+Garbage
  2. Question the audience to ask how they would do the following DETECTION Class with lots of accessors and few methods Each change to a class, affects indirect clients See also next SLIDE WHEN NOT A PROBLEM User Interfaces or databases may need to have access to indirect providers Brokers or object servers are special objects returning objects