SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design:...

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

Transcript of SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design:...

Page 1: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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]

IntroductionWhy

refactoring?Typical

RefactoringsExamples Obstacles

Summary & References

2/30

Page 3: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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

IntroductionWhy

refactoring?Typical

RefactoringsExamples Obstacles

Summary & References

3/30

Page 4: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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

IntroductionWhy

refactoring?Typical

RefactoringsExamples Obstacles

Summary & References

4/30

Page 5: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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 ObstaclesSummary & References

5/30

Page 6: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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 ObstaclesSummary & References

6/30

Page 7: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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 ObstaclesSummary & References

7/30

Page 8: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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 ObstaclesSummary & References

8/30

Page 9: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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 ObstaclesSummary & References

9/30

Page 10: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

SWE 316: Software Design and Architecture

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

List of refactorings:

IntroductionWhy

refactoring?Typical

RefactoringsExamples Obstacles

Summary & References

10/30

Page 11: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

SWE 316: Software Design and Architecture

A Longer List (martinfowler.com/refactoring/catalog)

1. Add Parameter

2. Change Bidirectional Association to Unidirectional

3. Change Reference to Value

4. Change Unidirectional Association to Bidirectional

5. Change Value to Reference

6. Collapse Hierarchy

7. Consolidate Conditional Expression

8. Consolidate Duplicate Conditional Fragments

9. Convert Dynamic to Static Construction by Gerard M. Davison

10. Convert Static to Dynamic

Construction by Gerard M. Davison

11. Decompose Conditional

12. Duplicate Observed Data

13. Eliminate Inter-Entity Bean Communication (Link Only)

14. Encapsulate Collection

15. Encapsulate Downcast

16. Encapsulate Field

17. Extract Class

18. Extract Interface

19. Extract Method

20. Extract Package by Gerard M. Davison

21. Extract Subclass

IntroductionWhy

refactoring?Typical

RefactoringsExamples Obstacles

Summary & References

11/30

Page 12: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

SWE 316: Software Design and Architecture

A Longer List (martinfowler.com/refactoring/catalog)

22. Extract Superclass

23. Form Template Method

24. Hide Delegate

25. Hide Method

26. Hide presentation tier-specific details from the business tier (Link Only)

27. Inline Class

28. Inline Method

29. Inline Temp

30. Introduce A Controller (Link Only)

31. Introduce Assertion

32. Introduce Business Delegate (Link Only)

33. Introduce Explaining Variable

34. Introduce Foreign Method

35. Introduce Local Extension

36. Introduce Null Object

37. Introduce Parameter Object

38. 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. Davison

43. Move Field

44. Move Method

IntroductionWhy

refactoring?Typical

RefactoringsExamples Obstacles

Summary & References

12/30

Page 13: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

SWE 316: Software Design and Architecture

A Longer List (martinfowler.com/refactoring/catalog)

45. Parameterize Method

46. Preserve Whole Object

47. Pull Up Constructor Body

48. Pull Up Field

49. Pull Up Method

50. Push Down Field

51. Push Down Method

52. Reduce Scope of Variable by Mats Henricson

53. Refactor Architecture by Tiers (Link Only)

54. Remove Assignments to Parameters

55. Remove Control Flag

56. Remove Double Negative by

Ashley Frieze and Martin Fowler

57. Remove Middle Man

58. Remove Parameter

59. Remove Setting Method

60. Rename Method

61. Replace Array with Object

62. Replace Assignment with Initialization by Mats Henricson

63. Replace Conditional with Polymorphism

64. Replace Conditional with Visitor by Ivan Mitrovic

65. Replace Constructor with Factory Method

IntroductionWhy

refactoring?Typical

RefactoringsExamples Obstacles

Summary & References

13/30

Page 14: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

SWE 316: Software Design and Architecture

A Longer List (martinfowler.com/refactoring/catalog)

66. Replace Data Value with Object

67. Replace Delegation with Inheritance

68. Replace Error Code with Exception

69. Replace Exception with Test

70. Replace Inheritance with Delegation

71. Replace Iteration with Recursion by Dave Whipp

72. Replace Magic Number with Symbolic Constant

73. Replace Method with Method Object

74. Replace Nested Conditional

with Guard Clauses

75. Replace Parameter with Explicit Methods

76. Replace Parameter with Method

77. Replace Record with Data Class

78. Replace Recursion with Iteration by Ivan Mitrovic

79. Replace Static Variable with Parameter by Marian Vittek

80. Replace Subclass with Fields

81. Replace Temp with Query

82. Replace Type Code with Class

IntroductionWhy

refactoring?Typical

RefactoringsExamples Obstacles

Summary & References

14/30

Page 15: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

SWE 316: Software Design and Architecture

A Longer List (martinfowler.com/refactoring/catalog)

83. Replace Type Code with State/Strategy

84. Replace Type Code with Subclasses

85. Reverse Conditional by Bill Murphy and Martin Fowler

86. Self Encapsulate Field

87. Separate Data Access Code (Link Only)

88. Separate Query from Modifier

89. Split Loop by Martin Fowler

90. Split Temporary Variable

91. Substitute Algorithm

92. Use a Connection Pool (Link

Only)

93. Wrap entities with session (Link Only)

IntroductionWhy

refactoring?Typical

RefactoringsExamples Obstacles

Summary & References

15/30

Page 16: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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.

IntroductionWhy

refactoring?Typical

Refactorings Examples ObstaclesSummary & References

16/30

Page 17: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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

IntroductionWhy

refactoring?Typical

Refactorings Examples ObstaclesSummary & References

17/30

Page 18: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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.

IntroductionWhy

refactoring?Typical

Refactorings Examples ObstaclesSummary & References

18/30

Page 19: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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

IntroductionWhy

refactoring?Typical

Refactorings Examples ObstaclesSummary & References

19/30

Page 20: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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.

IntroductionWhy

refactoring?Typical

Refactorings Examples ObstaclesSummary & References

20/30

Page 21: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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

IntroductionWhy

refactoring?Typical

Refactorings Examples ObstaclesSummary & References

21/30

Page 22: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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

IntroductionWhy

refactoring?Typical

Refactorings Examples ObstaclesSummary & References

22/30

Page 23: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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

IntroductionWhy

refactoring?Typical

Refactorings Examples ObstaclesSummary & References

23/30

Page 24: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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.

IntroductionWhy

refactoring?Typical

Refactorings Examples ObstaclesSummary & References

24/30

Page 25: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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

IntroductionWhy

refactoring?Typical

Refactorings Examples ObstaclesSummary & References

25/30

Page 26: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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?

IntroductionWhy

refactoring?Typical

RefactoringsExamples Obstacles

Summary & References

26/30

Page 27: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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

IntroductionWhy

refactoring?Typical

RefactoringsExamples Obstacles

Summary & References

27/30

Page 28: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

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

IntroductionWhy

refactoring?Typical

RefactoringsExamples Obstacles Summary &

References28/30

Page 29: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

SWE 316: Software Design and Architecture

Resources

http://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.

IntroductionWhy

refactoring?Typical

RefactoringsExamples Obstacles Summary &

References29/30

Page 30: SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.

SWE 316: Software Design and Architecture

Resources (cont...)

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

IntroductionWhy

refactoring?Typical

RefactoringsExamples Obstacles Summary &

References30/30