lecture # 20 improving the existing design: refactoring

30
SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture To be able to improve the existing design using refactoring Most of the material and the slides of this presentation are adopted from: 1. “Refactoring, Improving the Design of Existing Code” by Martin Fowler, Addison Wesley, 1999. 2. presentation by Martin Fowler. 3. http://www.refactoring.com Handout

Upload: dixie

Post on 24-Feb-2016

55 views

Category:

Documents


0 download

DESCRIPTION

SWE 316: Software Design and Architecture. Handout. Lecture # 20 Improving the existing design: Refactoring. To be able to improve the existing design using refactoring. Most of the material and the slides of this presentation are adopted from: - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Objectives

Lecture # 20Improving the existing design: Refactoring

SWE 316: Software Design and Architecture

To be able to improve the existing design using refactoring

Most of the material and the slides of this presentation are adopted from:1. “Refactoring, Improving the Design of Existing Code” by Martin Fowler,

Addison Wesley, 1999.2. presentation by Martin Fowler.3. http://www.refactoring.com

Handout

Page 2: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

What is refactoring? “Refactoring is the art of improving the design

of existing code. Refactoring provides us with ways to recognize problematic code and gives us recipes for improving it.” [William C. Wake]

“A change to the system that leaves its behavior unchanged, but enhances some non-functional quality - simplicity, flexibility, understandability, ...” [Kent Beck]

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 2/30

Page 3: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

What is refactoring? (cont...) “The process of changing a software system in

such a way that it does not alter the external behavior of the code, yet improves its internal structure” [Fowler]

Verify no change in external behavior by Testing: in practice good tests are essential Formal code analysis by tool

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 3/30

Page 4: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

The two hats

Adding Function Add new capabilities to

the system Adds new tests Get the test working

Refactoring Does not add any new

features Does not add tests (but

may change some) Restructure the code to

remove redundancy

Swap frequently between the hats, but only wear one at a time

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 4/30

Page 5: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Why refactoring? (1 of 2) To improve the software design

Makes the program easier to change

To make the software easier to understand Write for people, not the compiler Understand unfamiliar code

To help find bugs Refactor while debugging to clarify the code

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 5/30

Page 6: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Why refactoring? (2 of 2) Some argue that good design does not lead to

code needing refactoring but: It is extremely difficult to get the design right the

first time Original design is often inadequate You may not understand user requirements, if he

does!

Refactoring helps you to: Manipulate code in a safe environment Understand existing code

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 6/30

Page 7: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

When should you refactor? To add new functionality:

Refactor existing code until you understand it Refactor the design to make it easy to add

To find bugs: Refactor to understand the code

For code reviews: Immediate effect of code review

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 7/30

Page 8: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Team techniques Encourage refactoring culture

Nobody gets things right first time Nobody can write clear code without reviews

Provide sound testing base Tests are essential for refactoring Build system and run tests daily

Pair programming Two programmers working together can be quicker

than working separately

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 8/30

Page 9: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Creating your own refactorings Consider a change to a program

Should it change the external behavior of the system

Break down the change into small steps Look for points where you can compile and test

Carry out the change, note what you do If a problem occurs, consider how to eliminate it in

the future Carry it out again, follow and refine the notes After two or three times you have a workable

refactoring

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 9/30

Page 10: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Typical Refactorings

Class Refactorings Method Refactorings Attribute Refactoringsadd (sub)class to hierarchy

add method to class add variable to class

rename 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

List of refactorings:

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 10/30

Page 11: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

A Longer List (martinfowler.com/refactoring/catalog)1. Add Parameter2. Change Bidirectional

Association to Unidirectional3. Change Reference to Value4. Change Unidirectional

Association to Bidirectional5. Change Value to Reference6. Collapse Hierarchy7. Consolidate Conditional

Expression8. Consolidate Duplicate

Conditional Fragments9. Convert Dynamic to Static

Construction by Gerard M. Davison

10. Convert Static to Dynamic

Construction by Gerard M. Davison

11. Decompose Conditional12. Duplicate Observed Data13. Eliminate Inter-Entity Bean

Communication (Link Only)14. Encapsulate Collection15. Encapsulate Downcast16. Encapsulate Field17. Extract Class18. Extract Interface19. Extract Method20. Extract Package by Gerard M.

Davison21. Extract Subclass

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 11/30

Page 12: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

A Longer List (martinfowler.com/refactoring/catalog)22. Extract Superclass23. Form Template Method24. Hide Delegate25. Hide Method26. Hide presentation tier-specific

details from the business tier (Link Only)

27. Inline Class28. Inline Method29. Inline Temp30. Introduce A Controller (Link

Only)31. Introduce Assertion32. Introduce Business Delegate

(Link Only)33. Introduce Explaining Variable

34. Introduce Foreign Method35. Introduce Local Extension36. Introduce Null Object37. Introduce Parameter Object38. Introduce Synchronizer Token

(Link Only)39. Localize Disparate Logic (Link

Only)40. Merge Session Beans (Link

Only)41. Move Business Logic to

Session (Link Only)42. Move Class by Gerard M.

Davison43. Move Field44. Move Method

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 12/30

Page 13: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

A Longer List (martinfowler.com/refactoring/catalog)45. Parameterize Method46. Preserve Whole Object47. Pull Up Constructor Body48. Pull Up Field49. Pull Up Method50. Push Down Field51. Push Down Method52. Reduce Scope of Variable by

Mats Henricson53. Refactor Architecture by Tiers

(Link Only)54. Remove Assignments to

Parameters55. Remove Control Flag56. Remove Double Negative by

Ashley Frieze and Martin Fowler

57. Remove Middle Man58. Remove Parameter59. Remove Setting Method60. Rename Method61. Replace Array with Object62. Replace Assignment with

Initialization by Mats Henricson63. Replace Conditional with

Polymorphism64. Replace Conditional with

Visitor by Ivan Mitrovic65. Replace Constructor with

Factory Method

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 13/30

Page 14: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

A Longer List (martinfowler.com/refactoring/catalog)66. Replace Data Value with

Object67. Replace Delegation with

Inheritance68. Replace Error Code with

Exception69. Replace Exception with Test70. Replace Inheritance with

Delegation71. Replace Iteration with

Recursion by Dave Whipp72. Replace Magic Number with

Symbolic Constant73. Replace Method with Method

Object74. Replace Nested Conditional

with Guard Clauses75. Replace Parameter with

Explicit Methods76. Replace Parameter with

Method77. Replace Record with Data

Class78. Replace Recursion with

Iteration by Ivan Mitrovic79. Replace Static Variable with

Parameter by Marian Vittek80. Replace Subclass with Fields81. Replace Temp with Query82. Replace Type Code with Class

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 14/30

Page 15: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

A Longer List (martinfowler.com/refactoring/catalog)83. Replace Type Code with

State/Strategy84. Replace Type Code with

Subclasses85. Reverse Conditional by Bill

Murphy and Martin Fowler86. Self Encapsulate Field87. Separate Data Access Code

(Link Only)88. Separate Query from Modifier89. Split Loop by Martin Fowler90. Split Temporary Variable91. Substitute Algorithm92. Use a Connection Pool (Link

Only)93. Wrap entities with session

(Link Only)

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 15/30

Page 16: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Extract Method You have a code

fragment that can be grouped together

Turn the fragment into a method whose name explains the purpose of the method.

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 16/30

Page 17: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Steps for Extract Method Create method named after intention of code

Copy extracted code

Look for local variables and parameters Turn into parameter Turn into return value Declare within method

Compile Replace code fragment with call to new method Compile and test

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 17/30

Page 18: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Move Method

aMethod()

Class 1

Class 2

Class 1

aMethod()

Class 2

A method is, or will be, using or used by more features of another class than the class it is defined on.

Create a new method with a similar body in the class it uses most. Either turn the old method into a simple delegation, or remove it altogether.

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 18/30

Page 19: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Steps for Move method Declare method in target class Copy and fit code Set up a reference from the source object

to the target Turn the original method into a delegating

method Compile and test Find all users of the method

Adjust them to call method on target Remove original method Compile and test

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 19/30

Page 20: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Replace Temp with Query You are using a

temporary variable to hold the result of an expression.

Extract the expression into a method. Replace all references to the temp with the expression. The new method can then be used in other methods.

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 20/30

Page 21: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Steps for Replace temp with Query Find temp with a single assignment

Extract Right Hand Side of assignment

Replace all references of temp with new method

Remove declaration and assignment of temp

Compile and test

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 21/30

Page 22: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Replace Type Code with State You have a type code which affects the behavior

of a class but you cannot use subclassing. Replace the type code with a state object.

ENGINEER : intSALESMAN : inttype : intEmployee

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 22/30

Page 23: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Replace Type Code with State class Employee { private int _type; static final int ENGINEER = 0; static final int SALESMAN = 1; static final int MANAGER = 2; Employee (int type) { _type = type; } int payAmount() { switch (_type) { case ENGINEER: return _monthlySalary; case SALESMAN: return _monthlySalary + _commission; case MANAGER: return _monthlySalary + _bonus; default: throw new RuntimeException("Incorrect Employee"); } } : : }

M s ENGINEER : intSALESMAN : inttype : intEmployee

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 23/30

Page 24: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Steps for Replace Type Code with State Create a new state class for the type code Add subclasses of the state object, one for each

type code. Create an abstract query in the superclass to

return the type code. Override in subclasses to return correct type code

Compile Create field in old class for the state object. Change the type code query to delegate to the

state object. Change the type code setting methods to assign

an instance of the subclass. Compile and test.

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 24/30

Page 25: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Bad Smells You are not limited to those

refactoring techniques!

Always check for: Bad smells within classes Bad smells between classes

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 25/30

Page 26: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Obstacles to refactoring (1 of 2) Complexity

Changing design is hard Understanding code is hard

Possibility to introduce errors Run tests if possible Build tests

Cultural Issues “We pay you to add new features, not to

improve the code!”

What should I do in these

cases?

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 26/30

Page 27: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Obstacles to refactoring (2 of 2) Performance issue

Refactoring may slow down the execution

Normally only 10% of your system consumes 90% of the resources so just focus on 10 %. Refactorings help to localize the part that need

change Refactorings help to concentrate the optimizations

Development is always under time pressure Refactoring takes time Refactoring better after delivery

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References 27/30

Page 28: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Summary “The process of changing a software system in

such a way that it does not alter the external behavior of the code, yet improves its internal structure” [Fowler]

Refactor to: Improve the software design Make the software easier to understand Help find bugs

A catalog of refactoring exists: Extract Method, Move Method, Replace Temp with Query, etc…

Refactoring has some obstacles

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References28/30

Page 29: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Resourceshttp://www.refactoring.com

“Refactoring, Improving the Design of Existing Code” by Martin Fowler, Addison Wesley, 1999.

“Refactoring to Patterns” by Joshua Kerievsky, Addison Wesley, 2004.

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References29/30

Page 30: Lecture  # 20 Improving the existing design:  Refactoring

SWE 316: Software Design and Architecture

Resources (cont...)

“Refactoring Workbook”, by William C. Wake, Addison Wesley, 2003.

Introduction Why refactoring?

Typical Refactorings Examples Obstacles Summary &

References30/30