SlideShare a Scribd company logo
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

More Related Content

What's hot

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
ASHNA nadhm
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects newlykado0dles
 
4. method overloading
4. method overloading4. method overloading
4. method overloading
Indu Sharma Bhardwaj
 
java Method Overloading
java Method Overloadingjava Method Overloading
java Method Overloading
omkar bhagat
 
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)
Nuzhat Memon
 
Java constructors
Java constructorsJava constructors
Java constructors
QUONTRASOLUTIONS
 
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
Radhika Talaviya
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
Pavith Gunasekara
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08Terry Yoast
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and object
Fajar Baskoro
 
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
Harshal Misalkar
 
11. java methods
11. java methods11. java methods
11. java methods
M H Buddhika Ariyaratne
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
Mahmoud Ali
 
Intercepting Filters Design Pattern
Intercepting Filters Design PatternIntercepting Filters Design Pattern
Intercepting Filters Design Pattern
ProdigyView
 
Java String
Java String Java String
Java String
SATYAM SHRIVASTAV
 
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
MOHIT AGARWAL
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Method Overloading In Java
Method Overloading In JavaMethod Overloading In Java
Method Overloading In Java
CharthaGaglani
 

What's hot (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
 

Similar to Refactoring Chapter11

Design patterns
Design patternsDesign patterns
Design patterns
Anas Alpure
 
Interface and abstraction
Interface and abstractionInterface and abstraction
Interface and abstractionRaghav Chhabra
 
java_inheritance.pdf
java_inheritance.pdfjava_inheritance.pdf
java_inheritance.pdf
JayMistry91473
 
Java basics
Java basicsJava basics
Java basics
Shivanshu Purwar
 
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#
Abid Kohistani
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
Tareq Hasan
 
Chap-3 Inheritance.pptx
Chap-3 Inheritance.pptxChap-3 Inheritance.pptx
Chap-3 Inheritance.pptx
chetanpatilcp783
 
Core java oop
Core java oopCore java oop
Core java oop
Parth Shah
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Pankhuree Srivastava
 
Java class
Java classJava class
Java class
Arati Gadgil
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
Tushar Desarda
 
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
KeatonJennings91
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
Naresh Jain
 
Chap2 class,objects
Chap2 class,objectsChap2 class,objects
Chap2 class,objects
raksharao
 
Only oop
Only oopOnly oop
Only oop
anitarooge
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_typesAbed Bukhari
 

Similar to 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
 

More from Abner Chih Yi Huang

諾貝爾經濟學獎得主的獲利公式
諾貝爾經濟學獎得主的獲利公式諾貝爾經濟學獎得主的獲利公式
諾貝爾經濟學獎得主的獲利公式
Abner Chih Yi Huang
 
Clip Tree Applications
Clip Tree ApplicationsClip Tree Applications
Clip Tree Applications
Abner Chih Yi Huang
 
Introduction to Szemerédi regularity lemma
Introduction to Szemerédi regularity lemmaIntroduction to Szemerédi regularity lemma
Introduction to Szemerédi regularity lemma
Abner Chih Yi Huang
 
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
Abner Chih Yi Huang
 
An introduction to Google test framework
An introduction to Google test frameworkAn introduction to Google test framework
An introduction to Google test framework
Abner Chih Yi Huang
 
SaaS: Science as a Service
SaaS: Science as a Service SaaS: Science as a Service
SaaS: Science as a Service
Abner Chih Yi Huang
 
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
Abner Chih Yi Huang
 
Alignment spaced seed
Alignment spaced seedAlignment spaced seed
Alignment spaced seed
Abner Chih Yi Huang
 
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
Abner Chih Yi Huang
 
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
Abner Chih Yi Huang
 
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
Abner Chih Yi Huang
 

More from 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
 

Recently uploaded

Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 

Recently uploaded (20)

Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 

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.