14 - refactoring · ch t 14 r f t ichapter 14: refactoring (continuously) improving the design of...

52
Ch t 14 R f t i Chapter 14: Refactoring (Continuously) Improving the Design of Existing Code O O Object-Oriented Software Construction Armin B. Cremers, T obias Rho, Daniel Speicher , Holger Mügge (based on Bruegge & Dutoit)

Upload: others

Post on 27-May-2020

8 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Ch t 14 R f t iChapter 14: Refactoring(Continuously) Improving the Design of Existing Code

O OObject-Oriented

Software Construction

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge, , p , g gg(based on Bruegge & Dutoit)

Page 2: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Outline

♦ Preface, Some Small Talk♦ Safe changes to the design ♦ Clean code and good design♦ Improving the design of existing code

Unmaintainable Classes: Stable but only specificLow Cohesion, Identity Disharmonies, TanglingHigh Coupling, Collaboration Disharmonies, ScatteringCl ifi ti Di h iClassification DisharmoniesUseless Classes: Abstract but unstable

♦ Review♦ Review

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 3

Page 3: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

What‘s the responsibility of this class?

Class A {

B<C> d;

void e(F g,F h,int i) {) {...

}

C j(j(int k) {...

}

}

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 4

Page 4: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

What‘s the responsibility of this class?

Class A {

B<C> d;

Class Library {

List<Book> books;

Class PartsDepot {

List<Part> parts;

void e(F g,F h,int i) {

void addBook(String name,String author,int bookNo) {

void addPart(String name,String manufacturer,int partNo) {) {

...}

C j(

) {...

}

Book getBook(

p ) {...

}

Part getPart(j(int k) {...

}

g (int bookNo){...

}

g (int partNo) {...

}

} } }

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 5

Page 5: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

What does this method?

public static int s(int[] y, int x) {int a = 0;int a = 0;int b = y.length-1;

while(true) {int i = (a + b)/2;

if (y[i] == x) return i;return i;

if (y[index] < x) a = i+1;

else b = i-1;

if (a > b) break;if (a > b) break;}

return -1;

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 6

}

Page 6: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

What does this method?

public static int binarySearch(int[] numbers, long searchedNumber) {int start = 0;int start = 0;int end = numbers.length-1;

while(true) {int middle = (start + end)/2;

if (numbers[index] == searchedNumber) return index;return index;

if (numbers[index] < searchedNumber) start = middle+1;

else end = middle-1;

if (start > end) break;if (start > end) break;}

return -1;

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 7

}

Page 7: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Clean Code! Naming is essential!

Clean code doesn‘t make your code correct,Clean code doesn t make your code correct,but it makes it much more difficult for a bug to hide.

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 8

Page 8: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Bad Signs of Rotting Design, [M96]

♦ RigidityCode difficult to changeManagement reluctance to change anything becomes policy

F ili♦ FragilityEven small changes can cause cascading effectsCode breaks in unexpected placesCode breaks in unexpected places

♦ ImmobilityCode is so tangled that it’s impossible to reuse anythingCode is so tangled that it s impossible to reuse anythinga module could be reused in another system, but the effort and risk of separating the module from original environment is

h htoo high

♦ ViscosityM h i t h k th t i i l d i

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 9

Much easier to hack than to preserve original design.

Page 9: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Separation of Concerns

Let me try to explain to you, what to my taste ischaracteristic for all intelligent thinking It is that one ischaracteristic for all intelligent thinking. It is, that one iswilling to study in depth an aspect of one’s subjectmatter in isolation for the sake of its ownconsistency all the time knowing that one isconsistency, all the time knowing that one isoccupying oneself only with one of the aspects.

We know that a program must be correct and we canp gstudy it from that viewpoint only; we also know that itshould be efficient and we can study its efficiency onanother day [ ] But nothing is gained – on the contraryanother day […] But nothing is gained on the contrary– by tackling these various aspects simultaneously. It iswhat I sometimes have called “the separation ofconcerns” [ ]concerns […]

[Edsger W. Dijkstra, "On the role of scientific thought“, 1974]

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 10

Page 10: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Outline

♦ Preface, Some Small Talk♦ Safe changes to the design ♦ Clean code and good design♦ Improving the design of existing code

Unmaintainable Classes: Stable but only specificLow Cohesion, Identity Disharmonies, TanglingHigh Coupling, Collaboration Disharmonies, ScatteringCl ifi ti Di h iClassification DisharmoniesUseless Classes: Abstract but unstable

♦ Review♦ Review

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 12

Page 11: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Course : Kent Beck's “Hats-metaphor"Wh t i it I t t t t ?What is it I want to restructure?Is there a test? → Write test!Apply refactoringApply refactoringTest Refactoring Hat

Wh i i I dd?

Programmer

What is it I want to add?Write test and see it failAdd functionality

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 13

Add functionalityTest and see the test succeedFunction Adding Hat

Page 12: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Safety: Small steps, Automation

♦ Fowler‘s book: Excellent guidance to execute R f t i i ll d f tRefactorings in small and safe steps.

I d D l E i lik E li ff♦ Integrated Development Environments like Eclipse offer many automated Refactorings:

In depth analysis of the preconditionsIn depth analysis of the preconditions.Derivation of the required changes.Preview lets the developer check the exected result.pExecution of the changes.(Still small bugs every now and then.)

♦ Good tests are indispensible in both cases.

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 14

Page 13: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Example: Rename Method

♦ [Check for overriden and overrding methods.]♦ Declare a new method with the new name. ♦ Copy the old body of code over to the new method.♦ Compile!♦ Change the old method so that it calls the new one.♦ Compile and test!♦ For all references to the old method name:

Change them to refer to the new one. Compile and test! It‘s safe! Because of your precaution,

♦ Remove the old method.♦ Compile and test!

you can even leave for a vacationafter changing the 72nd reference and continue with the 73rd when you return

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 16

return.

Page 14: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Automated Refactorings

♦ Example 1: Rename method Demo

♦ Example 2: Extract local variableDemo

♦ Very fast! Almost reliable.

♦ You still need the expertise what to do where!

♦ Even there tool support exists, but can not replace your judgementjudgement.

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 18

Page 15: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Refactorings in Eclipse (Java)

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 19

Page 16: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Outline

♦ Preface, Some Small Talk♦ Safe changes to the design ♦ Clean code and good design♦ Improving the design of existing code

Unmaintainable Classes: Stable but only specificLow Cohesion, Identity Disharmonies, TanglingHigh Coupling, Collaboration Disharmonies, ScatteringCl ifi ti Di h iClassification DisharmoniesUseless Classes: Abstract but unstable

♦ Review♦ Review

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 21

Page 17: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Concepts - Modules in 1-1 Relation

♦ Comprehensibilityp y♦ Natural Implementation♦ Easy identification of the parts to change

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 22

y p g

Page 18: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

OO based Modularity is natural

♦ Object = Identity + State + Behavior♦ Objects Things♦ Compounds consist of parts♦ Compounds consist of parts ♦ Abstraction, classification

S b tit t bilit C b d/Substitutability Can be used/seen as …Inheritance Is a … and therefore has/can …

d ll f l♦ 1-1 Modelling of real entities♦ Programming by combining virtual entities.

The core success story of OO: Graphical user interfaces build from “buttons”, “windows”.

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 23

♦ Classes are a giant step towards the 1-1 ideal

Page 19: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Visible Interfaces & Hidden Details

Benefits of Modularisation:P ll l D l Ch bili C h ibili♦ Parallel Development + Changability + Comprehensibility[David L. Parnas: On the Criteria to Be Used in Decomposing Systems into Modules, 1972]

♦ Reusability of common / abstract Functionality

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 24

y / y[Dependency Inversion Principle: „Depend on abstractions not on concretions.”]

Page 20: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

DIP/SDP, [M96]

Useless Class More ReusableRACT

Useless Class Class

ABST

DIP

no cycles!

D

Unmaintainable ClassLess ReusableClRE

TE

Class

CON

C

STABLEUNSTABLE SDP

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 25

Page 21: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Design Principles, [M96]

♦ Dependency Inversion Principle (DIP)Depend upon Abstraction, Do NOT Depend upon Concretions.

♦ Acyclic Dependencies Principle (ADP)The dependency structure for released component must be a Directed Acyclic Graph (DAG). There can be no cycles.

♦ Stable Dependencies Principle (SDP)♦ Stable Dependencies Principle (SDP)The dependencies between components in a design should be in the direction of stability. A component should only depend

h bl h i iupon components that are more stable than it is.

♦ Stable Abstractions Principle (SAP)Th b t ti f k h ld b ti l t itThe abstraction of a package should be proportional to its stability! Packages that are maximally stable should be maximally abstract. Instable packages should be concrete.

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 26

Page 22: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Outline

♦ Preface, Some Small Talk♦ Safe changes to the design ♦ Clean code and good design♦ Improving the design of existing code

Unmaintainable Classes: Stable but only specificLow Cohesion, Identity Disharmonies, TanglingHigh Coupling, Collaboration Disharmonies, ScatteringCl ifi ti Di h iClassification DisharmoniesUseless Classes: Abstract but unstable

♦ Review♦ Review

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 28

Page 23: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Outline

♦ Preface, Some Small Talk♦ Safe changes to the design ♦ Clean code and good design♦ Improving the design of existing code

Unmaintainable Classes: Stable but only specificLow Cohesion, Identity Disharmonies, TanglingHigh Coupling, Collaboration Disharmonies, ScatteringCl ifi ti Di h iClassification DisharmoniesUseless Classes: Abstract but unstable

♦ Review♦ Review

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 29

Page 24: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Unmaintainable Classes: Stable but only specificy p

Smell Refactoring

Duplicated Code Extract Method, Extract Class, Hide Delegate, Remove Middle Man

Comments Extract Method, Introduce Assertion

Replace Type Code with State/StrategySwitch Statements

Replace Type Code with State/Strategy, Replace Type Code with Subclasses, Introduce Null Object, Replace Conditional with Polymorphism, Replace Parameter with Explicit Methods

Data Class Move Method, Encapsulate Field, Encapsulate Collectionp

Data Clumps Extract Class, Introduce Parameter Object, Preserve Whole Object

Extract Class, Replace Data Value with Object, ReplacePrimitve Obsession

Extract Class, Replace Data Value with Object, Replace Type Code with Class (Enumeration), Introduce Parameter Object, Replace Array with Object, Replace Type Code with State/Strategy, Replace Type Code with Subclasses

d Obj h l ObjLong Parameter List Introduce Parameter Object, Preserve Whole Object, Replace Parameter with Method

Long Method Extract Subclass, Decompose Conditional, Replace Inheritance with Delegation Replace Temp with Query

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 31

gwith Delegation, Replace Temp with Query

Large Class Extract Class, Extract Subclass, Extract Interface, Duplicate Observed Data

Page 25: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Smell: Duplication

♦ The cost of code cloning:♦ If you have to change the code of one clone, you

probably have to change the code of every clone.O i l d b d l k♦ Once you miss one clone and somebody else works on that code, it is not clear, which variant of the code is the correct one.correct one.

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 32

Page 26: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Smell: Comments

♦ Comments are good, aren’t they?♦ They are good: Document your public interface with

JavaDoc (or similar tool for the language of your choice).

♦ In of method bodies comments smell.♦ Writing comments might be an excuse for not writing

clean code.Comments tend to become outdated♦ Comments tend to become outdated.

Comments that e plain h o did something in a♦ Comments that explain why you did something in a different than the obvious way are of course necessary. (“What” in body = smell, “Why” if necessary o.k.)

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 33

( y , y y )

Page 27: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Extract Method

Indication: Cohesive set of statements.How to handle? Extract in to a well-named method, replace t t t ith ll t th th d

void printOwing(double amount) {printBanner();

statements with call to the method.

printBanner();

// print detailsSystem.out.println(“name“+_name);System.out.println(“amount“+ amount);System.out.println( amount + amount);

}

void printOwing (double amount) {printBanner();printDetails(amount);

}

void printDetails (double amount) {System.out.println (“name“+_name);System.out.println (“amount“+ amount);

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 34

}

Page 28: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Steps (1/2)

Defining new and well-named methods

always „private“

Copy the Code

h f h l l bl d dSearching for the local variables in extracted code

Variables that will be used just in new methodsl l i bl f th dlocal variables of new methods

Variables which are changed in new methods and will be used in old methods

If only one: give it back as the result of new method

more than one: Parts that can not be extracted!(„Replace Temp with Query“ or try to „Split Temp Variable“)

Variables that will be read in new methodsParameters of new methods

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 35

Page 29: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Steps (2/2)

♦ Compile

♦ In original methodReplace the extracted code with a call of the new methodDelete the declaration of local variables which have no use anymore

♦ Compile♦ Test♦ Test

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 36

Page 30: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Example: no local variablesid i i (d bl ) {void printOwing(double amount) {

Enumeration e = orders.elements();double outstanding = 0.0;

// print bannerSystem.out.println("**********************");System.out.println("*** Customer owes ****");S t t i tl ("**********************")System.out.println("**********************");

// calculate outstandingwhile (e.hasMoreElements()) {

O d h (O d ) tEl t()Order each = (Order) e.nextElement();outstanding += each.getAmount();

// print detailsS t t i tl (“ “+ )System.out.println(“name“+ _name);System.out.println(“amount“+ outstanding);

}

Extraction of code for print banner

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 37

Page 31: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Example: no local variablesid i i (d bl ) {void printOwing(double amount) {

Enumeration e = orders.elements();double outstanding = 0.0;

printBanner();private void printBanner() {

System.out.println("**********************");System.out.println("*** Customer owes ****");System.out.println("**********************");

// calculate outstandingwhile (e.hasMoreElements()) {

O d h (O d ) tEl t()

}

Order each = (Order) e.nextElement();outstanding += each.getAmount();

// print detailsS t t i tl (“ “+ )System.out.println(“name“+ _name);System.out.println(“amount“+ outstanding);

}

Extraction of code for print banner

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 38

Unaltered local variable: outstanding

Page 32: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Local variable which is not alteredid i i (d bl ) {void printOwing(double amount) {

Enumeration e = orders.elements();double outstanding = 0.0;

printBanner();

// calculate outstandingwhile (e.hasMoreElements()) {

O d h (O d ) tEl t()Order each = (Order) e.nextElement();outstanding += each.getAmount();

printDetails(outstanding); private void printDetails(double outstanding) {

}

System.out.println(“name“+ _name);System.out.println(“amount“+ outstanding);

}

Extraction of codes for calculationLocal variable , which is altered and finally used: outstanding

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 39

Local variable , which is altered and will not be used anymore: e

Page 33: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Local variable that will be alteredid i i (d bl ) {void printOwing(double amount) {

Enumeration e = orders.elements();double outstanding = 0.0;

printBanner();

outstanding = getOutstanding();

printDetails(outstanding);

private double getOutstanding() {Enumeration e = orders.elements();double outstanding = 0.0;while (e.hasMoreElements()) {

}

Order each = (Order) e.nextElement();outstanding += each.getAmount();

}return outstanding;

Extracting code for calculation

}

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 40

If local variable is assigned before in original method

Page 34: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Example : local variable altered beforeid i i (d bl ) {void printOwing(double amount) {

double outstanding = amount *1.2;

printBanner();

outstanding = getOutstanding(outstanding);

printDetails(outstanding);

private double getOutstanding(double startValue) {Enumeration e = orders.elements();double result = startValue;while (e.hasMoreElements()) {

}

Order each = (Order) e.nextElement();result += each.getAmount();

}return result;

}

Now are more Rafactorings possibletwice „inline temp“ for assigning to local variable outstanding

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 41

p g g g

In this way we can eliminate outstanding from printOwing-Method

Page 35: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Example: Elimination of „outstanding“id i i (d bl ) {void printOwing(double amount) {

double outstanding = amount *1.2;

printBanner();

outstanding = getOutstanding(outstanding);

printDetails(outstanding);

}

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 42

Page 36: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Example: Resulti d bl di (d bl l ) {private double getOutstanding(double startValue) {Enumeration e = orders.elements();double result = startValue;while (e.hasMoreElements()) {

O d h (O d ) l ()Order each = (Order) e.nextElement();result += each.getAmount();

}return result;

}}

private void printBanner() {System.out.println("**********************");S t t i tl ("*** C t ****")System.out.println("*** Customer owes ****");System.out.println("**********************");

}

i t id i tD t il (d bl t t di ) {private void printDetails(double outstanding) {System.out.println(“name“+ _name);System.out.println(“amount“+ outstanding);

}

void printOwing(double amount) {printBanner();printDetails(getOutstanding(amount *1.2));

}

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 43

}

Page 37: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Outline

♦ Preface, Some Small Talk♦ Safe changes to the design ♦ Clean code and good design♦ Improving the design of existing code

Unmaintainable Classes: Stable but only specificLow Cohesion, Identity Disharmonies, TanglingHigh Coupling, Collaboration Disharmonies, ScatteringCl ifi ti Di h iClassification DisharmoniesUseless Classes: Abstract but unstable

♦ Review♦ Review

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 45

Page 38: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Low Cohesion, Identity Disharmonies, Tanglingy g g

Smell Refactoring

Feature Envy Extract Method, Move Field, Move Method

Divergent Change Extract Class

Temporary Field Extract Class Introduce Null ObjectTemporary Field Extract Class, Introduce Null Object

♦ Feature Envy: A method is more interested in features♦ Feature Envy: A method is more interested in features (fields and methods) of another class.

♦ Divergent Change: The reason a class has to change are too many. A class should have a clear responsibility.

♦ Temporary Field: A field that is set only in certain i tcircumstances.

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 47

Page 39: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Outline

♦ Preface, Some Small Talk♦ Safe changes to the design ♦ Clean code and good design♦ Improving the design of existing code

Unmaintainable Classes: Stable but only specificLow Cohesion, Identity Disharmonies, TanglingHigh Coupling, Collaboration Disharmonies, ScatteringCl ifi ti Di h iClassification DisharmoniesUseless Classes: Abstract but unstable

♦ Review♦ Review

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 48

Page 40: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

High Coupling, Collaboration Disharmonies, Scatteringg

Smell Refactoring

Inappropriate IntimacyMove Field, Move Method, Change Bidirectional Association to Undirectional, Hide Delegate, Replace Inheritance with Delegation

Shotg n S ge M Fi ld M M h d I li ClShotgun Surgery Move Field, Move Method, Inline Class

Message Chains Hide Delegate

♦ Inappropriate Intimacy: Too strong mutual dependency fi ld d th d f t lon fields and methods of two or more classes.

♦ Shotgun Surgery: A certain kind of change requires to change the code in many different places (=Scattering)change the code in many different places. (=Scattering)

♦ Message Chain: You retrieve a reference to another object, to retrieve another reference to a third object, to

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 50

j , j ,… to finally call a method that really does something.

Page 41: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Outline

♦ Preface, Some Small Talk♦ Safe changes to the design ♦ Clean code and good design♦ Improving the design of existing code

Unmaintainable Classes: Stable but only specificLow Cohesion, Identity Disharmonies, TanglingHigh Coupling, Collaboration Disharmonies, ScatteringCl ifi ti Di h iClassification DisharmoniesUseless Classes: Abstract but unstable

♦ Review♦ Review

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 51

Page 42: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Classification Disharmonies

Smell Refactoring

Refused Bequest Replace Inheritance with DelegationDuplicated Code (in siblings)

Pull Up Method, Form Template Method

Parallel Inheritance Hierarchies

Move Field, Move Method (from classes in one hierarchy to classes in the other)

Alternative Classes with Move Method Rename MethodAlternative Classes with Different Interface

Move Method, Rename Method

Replace Inheritance with Delegation

Vector

Replace Inheritance with Delegation

StackVectorStack

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 53

Stack

Page 43: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Form Template Method

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 54

Page 44: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Outline

♦ Preface, Some Small Talk♦ Safe changes to the design ♦ Clean code and good design♦ Improving the design of existing code

Unmaintainable Classes: Stable but only specificLow Cohesion, Identity Disharmonies, TanglingHigh Coupling, Collaboration Disharmonies, ScatteringCl ifi ti Di h iClassification DisharmoniesUseless Classes: Abstract but unstable

♦ Review♦ Review

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 55

Page 45: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Useless Classes: Abstract but unstable

Smell Refactoring

Speculative Generality

Collapse Hierarchy, Inline Class, Remove Parameter, Rename Class, Rename Field, Rename Interface, Rename Local Variable, Rename Method, Rename P k R PPackage, Rename Parameter

Middle Man Inline Method, Remove Middle Man, Replace Delegation with Inheritance

Lazy Class Collapse Hierarchy, Inline Class

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 57

Page 46: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Screenshot: Code Analysis Plugin

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 58

Page 47: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Outline

♦ Preface, Some Small Talk♦ Safe changes to the design ♦ Clean code and good design♦ Improving the design of existing code

Unmaintainable Classes: Stable but only specificLow Cohesion, Identity Disharmonies, TanglingHigh Coupling, Collaboration Disharmonies, ScatteringCl ifi ti Di h iClassification DisharmoniesUseless Classes: Abstract but unstable

♦ Review♦ Review

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 60

Page 48: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Master Craftsman‘s Advice

♦ Some time ago, Kent Beck offered the following " l " f i l d i"rules" for simple design. In priority order, the code must:

1 Run all the tests1. Run all the tests 2. Contain no duplicate code 3 Express all the ideas the author wants to express3. Express all the ideas the author wants to express 4. Minimize classes and methods

1..few 1

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 61

Page 49: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

XP: Refactor mercilessly

♦ Refactor mercilessly to keep the design simple as you d t id dl l tt d l it Kgo and to avoid needless clutter and complexity. Keep

your code clean and concise so it is easier to understand, modify, and extend. Make sure everything is od y, a d d su y g sexpressed once and only once. In the end it takes less time to produce a system that is well groomed.

(Don Wells http://www extremeprogramming org/rules/refactor html)(Don Wells, http://www.extremeprogramming.org/rules/refactor.html)

1 1

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 62

Page 50: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Expressing ideas

♦ Expressing ideas gives meaningful names to the classes and methods we have and tothe classes and methods we have and to those that are created by the duplication rule. As well, we are often moved to create newAs well, we are often moved to create new classes and methods just for improved expression. For example, it is common to replace a switch statement with a few classes with a polymorphic method. When we

th ti l id th t d li thsee the essential idea that underlies the switch, the classes, and the name of the method tend to pop right outmethod, tend to pop right out.

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 63

(Ron Jeffries: http://www.xprogramming.com/xpmag/expEmergentDesign.htm)

Page 51: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Literature

♦ [Fo99] Martin Fowler: Refactoring: Improving the Design f E i ti C d (htt // f t i / t l )of Existing Code (http://www.refactoring.com/catalog)

♦ M. Lanza, R. Marinescu: Object-Oriented Metrics in Practice 2006 [LM06]Practice, 2006. [LM06]

♦ [M96] Robert C. Martin: Design Principles and Design PatternsDesign Principles and Design Patternshttp://www.objectmentor.com/resources/articles/Principles_and_Patterns.PDF

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 64

Page 52: 14 - Refactoring · Ch t 14 R f t iChapter 14: Refactoring (Continuously) Improving the Design of Existing Code O bject-O riented S oftware C onstruction Armin B. Cremers, Tobias

Some tools for quality assessment

♦ Metrics – Plugin for EclipseCalculation of common metrics (e.g. LCOM, WMC, etc.)Calculation of common metrics (e.g. LCOM, WMC, etc.)http://sourceforge.net/projects/metrics

♦ Creole – Plugin for EclipseVi li ti f th t f th ft

g pVisualization of the strucure of the softwarehttp://www.thechiselgroup.org/creole

CodeCrawler Freeware (Mainly Smalltalk)♦ CodeCrawler – Freeware (Mainly Smalltalk)Visualization of the strucure of the software, Metrics are represented by the shape an color or the rectangles and lines. (Polymetric view)( y )(http://sourceforge.net/projects/codecrawler

♦ CAP - Code Analysis Plugin (http://cap.xore.de/)♦ Checkstyle (http://checkstyle.sourceforge.net/)♦ Simian (http://www.redhillconsulting.com.au/products/simian/)

Armin B. Cremers, Tobias Rho, Daniel Speicher, Holger Mügge (based on Bruegge & Dutoit) Object-Oriented Software Construction 14 - 65