08 refactoring

52
8. Refactoring and Design Patterns

Transcript of 08 refactoring

Page 1: 08 refactoring

8. Refactoring and Design Patterns

Page 2: 08 refactoring

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.

Page 3: 08 refactoring

© 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

Page 4: 08 refactoring

© 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.

Page 5: 08 refactoring

© 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

Page 6: 08 refactoring

© 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

Page 7: 08 refactoring

© 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

Page 8: 08 refactoring

© 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: aGrObjectaGrObject displayOn: self

MyWindow>>displayObject: aGrObjectaGrObject isSquare ifTrue: […]aGrObject isCircle ifTrue: […]…

Page 9: 08 refactoring

© 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

Page 10: 08 refactoring

© 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

Page 11: 08 refactoring

© 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

Page 12: 08 refactoring

© 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

Page 13: 08 refactoring

© 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.

Page 14: 08 refactoring

© Oscar Nierstrasz

ST — Refactoring and Design Patterns

8.14

Refactoring in the Package Browser

Page 15: 08 refactoring

© Oscar Nierstrasz

ST — Refactoring and Design Patterns

8.15

Typical Refactorings

Class Refactorings Method Refactorings Attribute Refactoringsadd (sub)class to hierarchy add method to class add variable to classrename class rename method rename variableremove class remove method remove variable

push method down push variable downpush method up pull variable upadd parameter to method create accessorsmove method to component abstract variableextract code in new method

Page 16: 08 refactoring

© 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

Page 17: 08 refactoring

© 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 !

Page 18: 08 refactoring

© 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

Page 19: 08 refactoring

© 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

Page 20: 08 refactoring

© 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

Page 21: 08 refactoring

© 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

Page 22: 08 refactoring

© Oscar Nierstrasz

ST — Refactoring and Design Patterns

8.22

The Dark Side of the Law of Demeter

Class AinstVar: myCollection

A>>do: aBlockmyCollection 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

Page 23: 08 refactoring

© 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

Page 24: 08 refactoring

© Oscar Nierstrasz

ST — Refactoring and Design Patterns

8.24

The Law of Demeter, violated

IndirectProvider

doSomething()

IntermediateProvider+provider

getProvider()

IndirectClient

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 /instantiates2. its parameters 4. its direct component objects

Page 25: 08 refactoring

© 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

Page 26: 08 refactoring

© 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

Page 27: 08 refactoring

© 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: anOrderedCollectionanOrderedCollection removeFirst.

Page 28: 08 refactoring

© 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

Page 29: 08 refactoring

© 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

Page 30: 08 refactoring

© 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.

Page 31: 08 refactoring

© 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)

Page 32: 08 refactoring

© 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

Page 33: 08 refactoring

© 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

Page 34: 08 refactoring

© Oscar Nierstrasz

ST — Refactoring and Design Patterns

8.34

Transformation

Ainit()

Clienta : Am()

switch (a.class)case B: a.init(); ((B) a).x();case C: a.init(); ((C)) a).y();Case D: ((D) a).z()

Bx()

Cinit()Y()

Dz()

this.init (); this.x();

this.init (); this.y();

Clienta : Am()

a.doit();Ainit()doit()

Bx()doit()

Cinit()Y()doit()

Dz()doit()

this.z();

Page 35: 08 refactoring

© 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

Page 36: 08 refactoring

© 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

Page 37: 08 refactoring

© 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!

Page 38: 08 refactoring

© 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!

Page 39: 08 refactoring

© 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

Page 40: 08 refactoring

© Oscar Nierstrasz

ST — Refactoring and Design Patterns

8.40

Common Design Patterns

Pattern Intent

AdapterConvert the interface of a class into another interface clients expect.

ProxyProvide a surrogate or placeholder for another object to control access to it.

CompositeCompose objects into part-whole hierarchies so that clients can treat individual objects and compositions uniformly.

Template MethodDefine the skeleton of an algorithm in an operation, deferring some steps so they can be redefined by subclasses.

What tradeoffs do these patterns introduce?

Page 41: 08 refactoring

© 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

Page 42: 08 refactoring

© 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.

Page 43: 08 refactoring

© Oscar Nierstrasz

ST — Refactoring and Design Patterns

8.43

Singleton Structure

Page 44: 08 refactoring

© Oscar Nierstrasz

ST — Refactoring and Design Patterns

8.44

Object subclass: #SystemChangeNotifierinstanceVariableNames: 'eventSource silenceLevel'classVariableNames: 'UniqueInstance'poolDictionaries: ''category: 'System-Change Notification'

SystemChangeNotifier classinstanceVariableNames: ''

SystemChangeNotifier class>>new^self error: self instanceCreationErrorString

SystemChangeNotifier class>>uniqueInstanceUniqueInstance ifNil: [UniqueInstance := self createInstance].^UniqueInstance

Singleton Example: SystemChangeNotifier

NB: This example uses a class variable rather than a class instance variable.

Page 45: 08 refactoring

© Oscar Nierstrasz

ST — Refactoring and Design Patterns

8.45

Singleton Example:

ChangeSet classinstanceVariableNames: '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.

Page 46: 08 refactoring

© 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

Page 47: 08 refactoring

© 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>>startupWindowSystemNotifier initializeWindowHandles....oldWindows := Notifier windows.Notifier initialize....^oldWindows

Page 48: 08 refactoring

© 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

Page 49: 08 refactoring

© 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

Page 50: 08 refactoring

© 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?

Page 51: 08 refactoring

© 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?

Page 52: 08 refactoring

© Oscar Nierstrasz

ST — Introduction

1.52

Attribution-ShareAlike 3.0 UnportedYou are free:

to Share — to copy, distribute and transmit the workto 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/