SlideShare ist ein Scribd-Unternehmen logo
1 von 32
Downloaden Sie, um offline zu lesen
Refactoring: Improving the Design of
Existing Code
Chapter 11
Dealing with Generalization
Abner Huang
2013/10/11
Generalization
 Moving methods around a hierarchy of
inheritance
 Pull Up Field
 Pull Up Method
 Push Down Method
 Push Down Field
 Pull Up Constructor Body
 ……
12 techniques to clean a hierarchy of inheritance
Push down Field
 If a field is used only by some subclasses, then move
the field to those subclasses.
Push down Field (cont.)
 Declare the field in all subclasses.
 Remove the field from the superclass.
 Compile and test.
 Remove the field from all subclasses that don’t
need it.
 Compile and test.
Pull up Field
 Two subclasses have the same field. Move the field to
the superclass.
Push Down Method
 Behavior on a superclass is relevant only for some of its
subclasses. Move it to those subclasses
 Declare a method in all subclasses and copy the body
into each subclass.
 Remove method from superclass.
 Compile and test.
 Remove the method from each subclass that does not
need it.
 Compile and test.
Pull up Method
 You have methods with identical results on subclasses.
Move them to the superclass
 If the method calls another method that is present on
both subclasses but not the superclass, declare an
abstract method on the superclass.
 If the method uses a subclass field, use Pull Up Field or
Self Encapsulate Field and declare and use an abstract
getting method.
Pull up Constructor Body
 You have constructors on subclasses with mostly
identical bodies. Create a superclass constructor; call
this from the subclass methods.
 Use super() in JAVA
 C++ has no super(); it use child_ctor(): parent_ctor() {};
class Employee...
protected String _name;
protected String _id;
boolean isPriviliged() {..}
void assignCar() {..}
class Manager...
private int _grade;
public Manager (String name, String id, int
grade) {
super (name, id);
_grade = grade;
if (isPriviliged()) assignCar();
//every subclass does this
}
Extract Subclass
 A class has features that are used only in some
instances. Create a subclass for that subset of features
I’ll start with a job item class that determines prices for
items of work at a local garage. If we have the following
code
class JobItem ...
public JobItem (int unitPrice, int quantity, boolean
isLabor, Employee employee) {
_unitPrice = unitPrice;
_quantity = quantity;
_isLabor = isLabor;
_employee = employee;
}
public int getUnitPrice(){
return (_isLabor)? _employee.getRate():
_unitPrice;
}
We add the following class
class LaborItem ...
public LaborItem (int quantity, Employee employee) {
super (0, quantity, true);
_employee = employee;
}
get rid of the isLabor field.
class JobItem...
protected boolean isLabor() {
return false;
}
class LaborItem...
protected boolean isLabor() {
return true;
}
class JobItem...
public int getUnitPrice(){
return (isLabor()) ? _employee.getRate():
_unitPrice;
}
replace it with
class JobItem...
public int getUnitPrice(){return _unitPrice; }
class LaborItem...
public int getUnitPrice(){return _employee.getRate(); }
Extract Superclass
 You have two classes with similar features. Create a
superclass and move the common features to the
superclass.
class Employee...
public Employee (String name, String id, int
annualCost) {
_name = name;
_id = id;
_annualCost = annualCost;
}
private String _name;
private int _annualCost;
private String _id;
. . .
//And their getters.
public class Department...
public Department (String name) {
_name = name;
}
public int getTotalAnnualCost(){
Enumeration e = getStaff();
int result = 0;
while (e.hasMoreElements()) {
Employee each = (Employee) e.nextElement();
result += each.getAnnualCost();
}
return result;
}
private String _name;
private Vector _staff = new Vector();
. . .
 Use Pull Up Constructor Body to assign the name
class Party...
protected Party (String name) { _name = name; }
private String _name;
class Department...
public Department (String name) { super (name); }
class Employee...
public Employee (String name, String id, int
annualCost) {
super (name);
_id = id;
_annualCost = annualCost;
}
 The methods Department.getTotalAnnualCost and
Employee.getAnnualCost, do carry out the same intention, so
they should have the same name.
 cannot use Pull Up Method
 Add abstract public int getAnnualCost() to superclass.
class Department...
public int getAnnualCost(){
Enumeration e = getStaff();
int result = 0;
while (e.hasMoreElements()) {
Party each = (Party) e.nextElement();
result += each.getAnnualCost();
}
return result;
}
Extract Interface
Several clients use the same subset of a class’s interface,
or two classes have part of their interfaces in common.
Collapse Hierarchy
 A superclass and subclass are not very different. Merge
them together.
Form Template Method
 You have two methods in subclasses that perform
similar steps in the same order, yet the steps are
different.
Class Customer {
public String statement() { … }
public String html_statement() { … }
…
}
1. Template Method [GoF]:
 Build a template for functions for the same tasks with
the same workflow
2. Pull up Method
class Customer...
public String statement() {
return new TextStatement().value(this);}
public String htmlStatement() {
return new HtmlStatement().value(this);}
class Statement...
abstract String headerString(Customer aCustomer);
abstract String eachRentalString (Rental aRental);
abstract String footerString (Customer aCustomer);
public String value(Customer aCustomer) {
out = headerString(aCustomer);
while (rentals.hasMoreElements()) {
out += eachRentalString(each);
}
out += footerString(aCustomer);
}
Replace Inheritance with Delegation
 A subclass uses only part of a superclasses interface or
does not want to inherit data. Create a field for the
superclass, adjust methods to delegate to the
superclass, and remove the subclassing.
Replace Delegation with Inheritance
 You’re using delegation and are often writing many
simple delegations for the entire interface. Make the
delegating class a subclass of the delegate.
 A couple of caveats
 Don’t use this technique, if you aren’t using all the
methods of the class to which you are delegating
 beware of is that in which the delegate is shared by more
than one object and is mutable.
References
 http://sourcemaking.com/refactoring
 http://en.wikipedia.org/wiki/Category:Software_desig
n_patterns

Weitere ähnliche Inhalte

Was ist angesagt?

Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
lykado0dles
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
Terry Yoast
 

Was ist angesagt? (20)

Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
 
4. method overloading
4. method overloading4. method overloading
4. method overloading
 
java Method Overloading
java Method Overloadingjava Method Overloading
java Method Overloading
 
Abstract classes
Abstract classesAbstract classes
Abstract classes
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)
 
Java constructors
Java constructorsJava constructors
Java constructors
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and object
 
Introduction to method overloading & method overriding in java hdm
Introduction to method overloading & method overriding  in java  hdmIntroduction to method overloading & method overriding  in java  hdm
Introduction to method overloading & method overriding in java hdm
 
11. java methods
11. java methods11. java methods
11. java methods
 
StringTokenizer in java
StringTokenizer in javaStringTokenizer in java
StringTokenizer in java
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
 
Intercepting Filters Design Pattern
Intercepting Filters Design PatternIntercepting Filters Design Pattern
Intercepting Filters Design Pattern
 
Java String
Java String Java String
Java String
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Method Overloading In Java
Method Overloading In JavaMethod Overloading In Java
Method Overloading In Java
 

Ähnlich wie Refactoring Chapter11

Interface and abstraction
Interface and abstractionInterface and abstraction
Interface and abstraction
Raghav Chhabra
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
Abed Bukhari
 

Ähnlich wie Refactoring Chapter11 (20)

Design patterns
Design patternsDesign patterns
Design patterns
 
Interface and abstraction
Interface and abstractionInterface and abstraction
Interface and abstraction
 
java_inheritance.pdf
java_inheritance.pdfjava_inheritance.pdf
java_inheritance.pdf
 
Java basics
Java basicsJava basics
Java basics
 
Reflection
ReflectionReflection
Reflection
 
13 inheritance
13   inheritance13   inheritance
13 inheritance
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
 
Chap-3 Inheritance.pptx
Chap-3 Inheritance.pptxChap-3 Inheritance.pptx
Chap-3 Inheritance.pptx
 
Core java oop
Core java oopCore java oop
Core java oop
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Classes2
Classes2Classes2
Classes2
 
Java class
Java classJava class
Java class
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 
CIS 407 STUDY Inspiring Innovation--cis407study.com
CIS 407 STUDY Inspiring Innovation--cis407study.comCIS 407 STUDY Inspiring Innovation--cis407study.com
CIS 407 STUDY Inspiring Innovation--cis407study.com
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
 
Chap2 class,objects
Chap2 class,objectsChap2 class,objects
Chap2 class,objects
 
Only oop
Only oopOnly oop
Only oop
 
Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 

Mehr von Abner Chih Yi Huang

Mehr von Abner Chih Yi Huang (11)

諾貝爾經濟學獎得主的獲利公式
諾貝爾經濟學獎得主的獲利公式諾貝爾經濟學獎得主的獲利公式
諾貝爾經濟學獎得主的獲利公式
 
Clip Tree Applications
Clip Tree ApplicationsClip Tree Applications
Clip Tree Applications
 
Introduction to Szemerédi regularity lemma
Introduction to Szemerédi regularity lemmaIntroduction to Szemerédi regularity lemma
Introduction to Szemerédi regularity lemma
 
Introduction to Algorithmic aspect of Market Equlibra
Introduction to Algorithmic aspect of Market EqulibraIntroduction to Algorithmic aspect of Market Equlibra
Introduction to Algorithmic aspect of Market Equlibra
 
An introduction to Google test framework
An introduction to Google test frameworkAn introduction to Google test framework
An introduction to Google test framework
 
SaaS: Science as a Service
SaaS: Science as a Service SaaS: Science as a Service
SaaS: Science as a Service
 
More on randomization semi-definite programming and derandomization
More on randomization semi-definite programming and derandomizationMore on randomization semi-definite programming and derandomization
More on randomization semi-definite programming and derandomization
 
Alignment spaced seed
Alignment spaced seedAlignment spaced seed
Alignment spaced seed
 
A small debate of power of randomness
A small debate of power of randomnessA small debate of power of randomness
A small debate of power of randomness
 
Dominating set of fixed size in degenerated graph
Dominating set of fixed size in degenerated graphDominating set of fixed size in degenerated graph
Dominating set of fixed size in degenerated graph
 
Introduction to algorithmic aspect of auction theory
Introduction to algorithmic aspect of auction theoryIntroduction to algorithmic aspect of auction theory
Introduction to algorithmic aspect of auction theory
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Kürzlich hochgeladen (20)

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 

Refactoring Chapter11

  • 1. Refactoring: Improving the Design of Existing Code Chapter 11 Dealing with Generalization Abner Huang 2013/10/11
  • 2. Generalization  Moving methods around a hierarchy of inheritance  Pull Up Field  Pull Up Method  Push Down Method  Push Down Field  Pull Up Constructor Body  ……
  • 3. 12 techniques to clean a hierarchy of inheritance
  • 4. Push down Field  If a field is used only by some subclasses, then move the field to those subclasses.
  • 5. Push down Field (cont.)  Declare the field in all subclasses.  Remove the field from the superclass.  Compile and test.  Remove the field from all subclasses that don’t need it.  Compile and test.
  • 6. Pull up Field  Two subclasses have the same field. Move the field to the superclass.
  • 7. Push Down Method  Behavior on a superclass is relevant only for some of its subclasses. Move it to those subclasses
  • 8.  Declare a method in all subclasses and copy the body into each subclass.  Remove method from superclass.  Compile and test.  Remove the method from each subclass that does not need it.  Compile and test.
  • 9. Pull up Method  You have methods with identical results on subclasses. Move them to the superclass
  • 10.  If the method calls another method that is present on both subclasses but not the superclass, declare an abstract method on the superclass.  If the method uses a subclass field, use Pull Up Field or Self Encapsulate Field and declare and use an abstract getting method.
  • 11. Pull up Constructor Body  You have constructors on subclasses with mostly identical bodies. Create a superclass constructor; call this from the subclass methods.  Use super() in JAVA  C++ has no super(); it use child_ctor(): parent_ctor() {};
  • 12. class Employee... protected String _name; protected String _id; boolean isPriviliged() {..} void assignCar() {..} class Manager... private int _grade; public Manager (String name, String id, int grade) { super (name, id); _grade = grade; if (isPriviliged()) assignCar(); //every subclass does this }
  • 13. Extract Subclass  A class has features that are used only in some instances. Create a subclass for that subset of features
  • 14. I’ll start with a job item class that determines prices for items of work at a local garage. If we have the following code class JobItem ... public JobItem (int unitPrice, int quantity, boolean isLabor, Employee employee) { _unitPrice = unitPrice; _quantity = quantity; _isLabor = isLabor; _employee = employee; } public int getUnitPrice(){ return (_isLabor)? _employee.getRate(): _unitPrice; }
  • 15. We add the following class class LaborItem ... public LaborItem (int quantity, Employee employee) { super (0, quantity, true); _employee = employee; }
  • 16. get rid of the isLabor field. class JobItem... protected boolean isLabor() { return false; } class LaborItem... protected boolean isLabor() { return true; }
  • 17. class JobItem... public int getUnitPrice(){ return (isLabor()) ? _employee.getRate(): _unitPrice; } replace it with class JobItem... public int getUnitPrice(){return _unitPrice; } class LaborItem... public int getUnitPrice(){return _employee.getRate(); }
  • 18. Extract Superclass  You have two classes with similar features. Create a superclass and move the common features to the superclass.
  • 19. class Employee... public Employee (String name, String id, int annualCost) { _name = name; _id = id; _annualCost = annualCost; } private String _name; private int _annualCost; private String _id; . . . //And their getters.
  • 20. public class Department... public Department (String name) { _name = name; } public int getTotalAnnualCost(){ Enumeration e = getStaff(); int result = 0; while (e.hasMoreElements()) { Employee each = (Employee) e.nextElement(); result += each.getAnnualCost(); } return result; } private String _name; private Vector _staff = new Vector(); . . .
  • 21.  Use Pull Up Constructor Body to assign the name class Party... protected Party (String name) { _name = name; } private String _name; class Department... public Department (String name) { super (name); } class Employee... public Employee (String name, String id, int annualCost) { super (name); _id = id; _annualCost = annualCost; }
  • 22.  The methods Department.getTotalAnnualCost and Employee.getAnnualCost, do carry out the same intention, so they should have the same name.  cannot use Pull Up Method  Add abstract public int getAnnualCost() to superclass. class Department... public int getAnnualCost(){ Enumeration e = getStaff(); int result = 0; while (e.hasMoreElements()) { Party each = (Party) e.nextElement(); result += each.getAnnualCost(); } return result; }
  • 23. Extract Interface Several clients use the same subset of a class’s interface, or two classes have part of their interfaces in common.
  • 24. Collapse Hierarchy  A superclass and subclass are not very different. Merge them together.
  • 25. Form Template Method  You have two methods in subclasses that perform similar steps in the same order, yet the steps are different. Class Customer { public String statement() { … } public String html_statement() { … } … }
  • 26. 1. Template Method [GoF]:  Build a template for functions for the same tasks with the same workflow 2. Pull up Method
  • 27. class Customer... public String statement() { return new TextStatement().value(this);} public String htmlStatement() { return new HtmlStatement().value(this);} class Statement... abstract String headerString(Customer aCustomer); abstract String eachRentalString (Rental aRental); abstract String footerString (Customer aCustomer); public String value(Customer aCustomer) { out = headerString(aCustomer); while (rentals.hasMoreElements()) { out += eachRentalString(each); } out += footerString(aCustomer); }
  • 28. Replace Inheritance with Delegation  A subclass uses only part of a superclasses interface or does not want to inherit data. Create a field for the superclass, adjust methods to delegate to the superclass, and remove the subclassing.
  • 29. Replace Delegation with Inheritance  You’re using delegation and are often writing many simple delegations for the entire interface. Make the delegating class a subclass of the delegate.
  • 30.  A couple of caveats  Don’t use this technique, if you aren’t using all the methods of the class to which you are delegating  beware of is that in which the delegate is shared by more than one object and is mutable.
  • 31.