SlideShare a Scribd company logo
1 of 11
New Hires Orientation Refactoring Ch8 (part 1)Mel Huang
Outline 8.1 Self Encapsulate Field 8.2 Replace Data Value with Object 8.3 Change Value to Reference 8.4 Change Reference to Value 8.5 Replace Array with Object 8.6 Duplicate Observed Data 8.7 Change Unidirectional Association to Bidirectional 8.8 Change Bidirectional Association to Unidirectional Classification 5/10/2011 2
8.1 Self Encapsulate Field Classification 5/10/2011 3 direct access: simple! private int _low, _high; boolean includes (intarg) {   return arg >= _low && arg <= _high; } private int _low, _high; boolean includes(intarg) {   return arg >= getLow() && arg <= getHigh(); } intgetLow() { return _low; } intgetHigh() { return _high; } intsetLow(int low) { _low = low; } intsetHigh(int high) { _high = high; } getter/setter: flexible!
8.2 Replace Data Value with Object Classification 5/10/2011 4 class Customer {   public Customer (String name) {     _name = name;   }   public String getName() {     return _name;   }   private final String _name; } class Order {   public Order (String customer) { _customer = new Customer(customer);   }   private Customer _customer; } class Order {   public Order (String customer) { _customer = customer;   }   private String _customer; } data value object: easier to complicate data item(s)
8.3 Change Value to Reference Classification 5/10/2011 5 Order * Customer Order * … class Customer { public static Customer create (String name) {     return (Customer) _instances.get(name);   }   static void loadCustomers() {     new Customer("Lemon Car Hire").store();     new Customer("Associated Coffee Machines").store();     ...   }   private void store() {     _instances.put(this.getName(), this);   }   public String getNamed(String name) {     return (Customer) _instances.get(name);   }   private final String _name; private static Dictionary _instances = new Hashtable(); } class Order {   public Order (String customer) {     _customer = Customer.create(customer);   }   private Customer _customer; } Order Customer Order Customer … class Customer {   public Customer (String name) {     _name = name;   }   public String getName() {     return _name;   }   private final String _name; } class Order {   public Order (String customer) {     _customer = new Customer(customer);   }   private Customer _customer; }
8.4 Change Reference to Value Classification 5/10/2011 6 class Currency {   private String _code;   public String getCode() {     return _code;   }   private Currency (String code) {     _code = code;   } } class Currency {   private String _code;   public String getCode() {     return _code;   }   private Currency (String code) {     _code = code;   } public boolean equals(Object arg) {     if (! (arginstanceof Currency))       return false;     Currency other = (Currency) arg;     return (_code.equals(other._code));   }   public inthashCode() {     return _code.hashCode();   } } immutable?
8.5 Replace Array with Object Classification 5/10/2011 7 array: hard to remember each column String[] row = new String[3]; row[0] = "Liverpool"; row[1] = "15"; Performance row = new Performance(); row.setName("Liverpool"); row.setWins("15"); object: easy to maintain
8.6 Duplicate Observed Data Classification 5/10/2011 8 public class IntervalWindow extends Frame { TextField _startField; TextField _endField; TextField _lengthField;   void StartField_FocusLost(FocusEvent event) {     ... calculateLength();   }   void EndtField_FocusLost(FocusEvent event) {     ... calculateLength();   }   void StartField_FocusLost(FocusEvent event) {     ... calculateLength();   }   void calculateLength() {     ...   }   void calculateEnd() {     ...   } } public class IntervalWindow extends Frame implements Observer { private Interval _subject; TextField _startField; TextField _endField; TextField _lengthField;   public IntervalWindow() {     _subject = new Interval();     _subject.addObserver(this);     update(_subject, null);   } public void update(Observable observed, Object arg) {     _endField.setText(_subject.getEnd());   }   String getEnd() {     return _subject.getEnd();   }   void setEnd (Srtingarg) {     _subject.setEnd(arg);   }   void StartField_FocusLost(FocusEvent event) {     ... calculateLength();   }   void EndtField_FocusLost(FocusEvent event) {     ... calculateLength();   }   void StartField_FocusLost(FocusEvent event) {     ... calculateLength();   } } class Interval extends Observable {  void calculateLength() {     ...   }   void calculateEnd() {     ...   } }
8.7 Change Unidirectional Association to Bidirectional Classification 5/10/2011 9 Order Customer * Order Customer * class Order {   Customer getCustomer() {     return _customer;   }   void setCustomer (Customer arg) {     _customer = arg;   }   Customer _customer; // order->customer } class Customer {   private Set _orders = new HashSet(); } class Order {   Customer getCustomer() {     return _customer;   }   void setCustomer (Customer arg) { if (_customer != null) _customer.friendOrders().remove(this);     _customer = arg;     if (_customer != null) _customer.friendOrders().add(this);   }   Customer _customer; // order->customer } class Customer {   private Set _orders = new HashSet(); Set friendOrders() {     return _orders   }   void addOrder(Order arg) { arg.setCustomer(this);   } }
8.8 Change Bidirectional Association to Unidirectional Classification 5/10/2011 10 Order Customer * Order Customer * class Order {   Customer getCustomer() {     return _customer;   }   void setCustomer (Customer arg) {     if (_customer != null) _customer.friendOrders().remove(this);     _customer = arg;     if (_customer != null) _customer.friendOrders().add(this);   }   double getDiscountedPrice() {     return getGrossPrice() * (1 - _customer.getDiscount());   }   Customer _customer; // order->customer } class Customer { getPriceFor(Order order) { Assert.isTrue(_orders.contains(order));     return order.getDiscountedPrice();   } } class Order {   Customer getCustomer() {     return _customer;   } CustomersetCustomer () { Iteratoriter = Customer.getInstances().iterator();     while (iter.hasNext()) {       Customer each = (Customer)iter.next();       if (each.containsOrder(this)) return each;     }     return null;   }   double getDiscountedPrice(Customer customer) {     return getGrossPrice() * (1 - customer.getDiscount());   }   Customer _customer; // order->customer } class Customer { getPriceFor(Order order) { Assert.isTrue(_orders.contains(order));     return order.getDiscountedPrice(this);   } }
Thank You Classification 5/10/2011 11

More Related Content

What's hot

Linq Sanjay Vyas
Linq   Sanjay VyasLinq   Sanjay Vyas
Linq Sanjay Vyas
rsnarayanan
 

What's hot (20)

Linq Sanjay Vyas
Linq   Sanjay VyasLinq   Sanjay Vyas
Linq Sanjay Vyas
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Tdd.eng.ver
Tdd.eng.verTdd.eng.ver
Tdd.eng.ver
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
 
Specs2
Specs2Specs2
Specs2
 
Clean code
Clean codeClean code
Clean code
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoC
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
 
Ch5 array nota
Ch5 array notaCh5 array nota
Ch5 array nota
 
Bw14
Bw14Bw14
Bw14
 
Clean code
Clean codeClean code
Clean code
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
 
Refactoring and code smells
Refactoring and code smellsRefactoring and code smells
Refactoring and code smells
 
Extend GraphQL with directives
Extend GraphQL with directivesExtend GraphQL with directives
Extend GraphQL with directives
 
Monadic Java
Monadic JavaMonadic Java
Monadic Java
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and Java
 
Jumping-with-java8
Jumping-with-java8Jumping-with-java8
Jumping-with-java8
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code Development
 

Similar to 重構—改善既有程式的設計(chapter 8)part 1

VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
Darwin Durand
 
using the code below create a method called getCollisionCount that w.pdf
using the code below create a method called getCollisionCount that w.pdfusing the code below create a method called getCollisionCount that w.pdf
using the code below create a method called getCollisionCount that w.pdf
amirthagiftsmadurai
 
can you add a delete button and a add button to the below program. j.pdf
can you add a delete button and a add button to the below program. j.pdfcan you add a delete button and a add button to the below program. j.pdf
can you add a delete button and a add button to the below program. j.pdf
sales88
 
I have created a class hasdhedDictionary that implements the Diction.pdf
I have created a class hasdhedDictionary that implements the Diction.pdfI have created a class hasdhedDictionary that implements the Diction.pdf
I have created a class hasdhedDictionary that implements the Diction.pdf
allystraders
 
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
honey725342
 
Link.javaLink.javapackage com.bookstore.domain.model;import .docx
Link.javaLink.javapackage com.bookstore.domain.model;import .docxLink.javaLink.javapackage com.bookstore.domain.model;import .docx
Link.javaLink.javapackage com.bookstore.domain.model;import .docx
SHIVA101531
 

Similar to 重構—改善既有程式的設計(chapter 8)part 1 (20)

An intro to cqrs
An intro to cqrsAn intro to cqrs
An intro to cqrs
 
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
 
Domänenspezifische Sprachen mit Xtext
Domänenspezifische Sprachen mit XtextDomänenspezifische Sprachen mit Xtext
Domänenspezifische Sprachen mit Xtext
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
using the code below create a method called getCollisionCount that w.pdf
using the code below create a method called getCollisionCount that w.pdfusing the code below create a method called getCollisionCount that w.pdf
using the code below create a method called getCollisionCount that w.pdf
 
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
 
TDC2016SP - Trilha .NET
TDC2016SP - Trilha .NETTDC2016SP - Trilha .NET
TDC2016SP - Trilha .NET
 
Implementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBImplementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDB
 
can you add a delete button and a add button to the below program. j.pdf
can you add a delete button and a add button to the below program. j.pdfcan you add a delete button and a add button to the below program. j.pdf
can you add a delete button and a add button to the below program. j.pdf
 
I have created a class hasdhedDictionary that implements the Diction.pdf
I have created a class hasdhedDictionary that implements the Diction.pdfI have created a class hasdhedDictionary that implements the Diction.pdf
I have created a class hasdhedDictionary that implements the Diction.pdf
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
 
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
 
Link.javaLink.javapackage com.bookstore.domain.model;import .docx
Link.javaLink.javapackage com.bookstore.domain.model;import .docxLink.javaLink.javapackage com.bookstore.domain.model;import .docx
Link.javaLink.javapackage com.bookstore.domain.model;import .docx
 
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
 
Combatendo code smells em Java
Combatendo code smells em Java Combatendo code smells em Java
Combatendo code smells em Java
 
Neo4 J
Neo4 J Neo4 J
Neo4 J
 
Solid principles
Solid principlesSolid principles
Solid principles
 

More from Chris Huang

Real time big data applications with hadoop ecosystem
Real time big data applications with hadoop ecosystemReal time big data applications with hadoop ecosystem
Real time big data applications with hadoop ecosystem
Chris Huang
 
Approaching real-time-hadoop
Approaching real-time-hadoopApproaching real-time-hadoop
Approaching real-time-hadoop
Chris Huang
 
20130310 solr tuorial
20130310 solr tuorial20130310 solr tuorial
20130310 solr tuorial
Chris Huang
 
Scaling big-data-mining-infra2
Scaling big-data-mining-infra2Scaling big-data-mining-infra2
Scaling big-data-mining-infra2
Chris Huang
 
Hbase status quo apache-con europe - nov 2012
Hbase status quo   apache-con europe - nov 2012Hbase status quo   apache-con europe - nov 2012
Hbase status quo apache-con europe - nov 2012
Chris Huang
 
Hbase schema design and sizing apache-con europe - nov 2012
Hbase schema design and sizing   apache-con europe - nov 2012Hbase schema design and sizing   apache-con europe - nov 2012
Hbase schema design and sizing apache-con europe - nov 2012
Chris Huang
 
重構—改善既有程式的設計(chapter 12,13)
重構—改善既有程式的設計(chapter 12,13)重構—改善既有程式的設計(chapter 12,13)
重構—改善既有程式的設計(chapter 12,13)
Chris Huang
 
重構—改善既有程式的設計(chapter 10)
重構—改善既有程式的設計(chapter 10)重構—改善既有程式的設計(chapter 10)
重構—改善既有程式的設計(chapter 10)
Chris Huang
 
重構—改善既有程式的設計(chapter 7)
重構—改善既有程式的設計(chapter 7)重構—改善既有程式的設計(chapter 7)
重構—改善既有程式的設計(chapter 7)
Chris Huang
 
重構—改善既有程式的設計(chapter 6)
重構—改善既有程式的設計(chapter 6)重構—改善既有程式的設計(chapter 6)
重構—改善既有程式的設計(chapter 6)
Chris Huang
 
重構—改善既有程式的設計(chapter 4,5)
重構—改善既有程式的設計(chapter 4,5)重構—改善既有程式的設計(chapter 4,5)
重構—改善既有程式的設計(chapter 4,5)
Chris Huang
 
重構—改善既有程式的設計(chapter 2,3)
重構—改善既有程式的設計(chapter 2,3)重構—改善既有程式的設計(chapter 2,3)
重構—改善既有程式的設計(chapter 2,3)
Chris Huang
 
重構—改善既有程式的設計(chapter 1)
重構—改善既有程式的設計(chapter 1)重構—改善既有程式的設計(chapter 1)
重構—改善既有程式的設計(chapter 1)
Chris Huang
 
Designs, Lessons and Advice from Building Large Distributed Systems
Designs, Lessons and Advice from Building Large Distributed SystemsDesigns, Lessons and Advice from Building Large Distributed Systems
Designs, Lessons and Advice from Building Large Distributed Systems
Chris Huang
 

More from Chris Huang (20)

Data compression, data security, and machine learning
Data compression, data security, and machine learningData compression, data security, and machine learning
Data compression, data security, and machine learning
 
Kks sre book_ch10
Kks sre book_ch10Kks sre book_ch10
Kks sre book_ch10
 
Kks sre book_ch1,2
Kks sre book_ch1,2Kks sre book_ch1,2
Kks sre book_ch1,2
 
Real time big data applications with hadoop ecosystem
Real time big data applications with hadoop ecosystemReal time big data applications with hadoop ecosystem
Real time big data applications with hadoop ecosystem
 
A Graph Service for Global Web Entities Traversal and Reputation Evaluation B...
A Graph Service for Global Web Entities Traversal and Reputation Evaluation B...A Graph Service for Global Web Entities Traversal and Reputation Evaluation B...
A Graph Service for Global Web Entities Traversal and Reputation Evaluation B...
 
Approaching real-time-hadoop
Approaching real-time-hadoopApproaching real-time-hadoop
Approaching real-time-hadoop
 
20130310 solr tuorial
20130310 solr tuorial20130310 solr tuorial
20130310 solr tuorial
 
Scaling big-data-mining-infra2
Scaling big-data-mining-infra2Scaling big-data-mining-infra2
Scaling big-data-mining-infra2
 
Applying Media Content Analysis to the Production of Musical Videos as Summar...
Applying Media Content Analysis to the Production of Musical Videos as Summar...Applying Media Content Analysis to the Production of Musical Videos as Summar...
Applying Media Content Analysis to the Production of Musical Videos as Summar...
 
Wissbi osdc pdf
Wissbi osdc pdfWissbi osdc pdf
Wissbi osdc pdf
 
Hbase status quo apache-con europe - nov 2012
Hbase status quo   apache-con europe - nov 2012Hbase status quo   apache-con europe - nov 2012
Hbase status quo apache-con europe - nov 2012
 
Hbase schema design and sizing apache-con europe - nov 2012
Hbase schema design and sizing   apache-con europe - nov 2012Hbase schema design and sizing   apache-con europe - nov 2012
Hbase schema design and sizing apache-con europe - nov 2012
 
重構—改善既有程式的設計(chapter 12,13)
重構—改善既有程式的設計(chapter 12,13)重構—改善既有程式的設計(chapter 12,13)
重構—改善既有程式的設計(chapter 12,13)
 
重構—改善既有程式的設計(chapter 10)
重構—改善既有程式的設計(chapter 10)重構—改善既有程式的設計(chapter 10)
重構—改善既有程式的設計(chapter 10)
 
重構—改善既有程式的設計(chapter 7)
重構—改善既有程式的設計(chapter 7)重構—改善既有程式的設計(chapter 7)
重構—改善既有程式的設計(chapter 7)
 
重構—改善既有程式的設計(chapter 6)
重構—改善既有程式的設計(chapter 6)重構—改善既有程式的設計(chapter 6)
重構—改善既有程式的設計(chapter 6)
 
重構—改善既有程式的設計(chapter 4,5)
重構—改善既有程式的設計(chapter 4,5)重構—改善既有程式的設計(chapter 4,5)
重構—改善既有程式的設計(chapter 4,5)
 
重構—改善既有程式的設計(chapter 2,3)
重構—改善既有程式的設計(chapter 2,3)重構—改善既有程式的設計(chapter 2,3)
重構—改善既有程式的設計(chapter 2,3)
 
重構—改善既有程式的設計(chapter 1)
重構—改善既有程式的設計(chapter 1)重構—改善既有程式的設計(chapter 1)
重構—改善既有程式的設計(chapter 1)
 
Designs, Lessons and Advice from Building Large Distributed Systems
Designs, Lessons and Advice from Building Large Distributed SystemsDesigns, Lessons and Advice from Building Large Distributed Systems
Designs, Lessons and Advice from Building Large Distributed Systems
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 

重構—改善既有程式的設計(chapter 8)part 1

  • 1. New Hires Orientation Refactoring Ch8 (part 1)Mel Huang
  • 2. Outline 8.1 Self Encapsulate Field 8.2 Replace Data Value with Object 8.3 Change Value to Reference 8.4 Change Reference to Value 8.5 Replace Array with Object 8.6 Duplicate Observed Data 8.7 Change Unidirectional Association to Bidirectional 8.8 Change Bidirectional Association to Unidirectional Classification 5/10/2011 2
  • 3. 8.1 Self Encapsulate Field Classification 5/10/2011 3 direct access: simple! private int _low, _high; boolean includes (intarg) { return arg >= _low && arg <= _high; } private int _low, _high; boolean includes(intarg) { return arg >= getLow() && arg <= getHigh(); } intgetLow() { return _low; } intgetHigh() { return _high; } intsetLow(int low) { _low = low; } intsetHigh(int high) { _high = high; } getter/setter: flexible!
  • 4. 8.2 Replace Data Value with Object Classification 5/10/2011 4 class Customer { public Customer (String name) { _name = name; } public String getName() { return _name; } private final String _name; } class Order { public Order (String customer) { _customer = new Customer(customer); } private Customer _customer; } class Order { public Order (String customer) { _customer = customer; } private String _customer; } data value object: easier to complicate data item(s)
  • 5. 8.3 Change Value to Reference Classification 5/10/2011 5 Order * Customer Order * … class Customer { public static Customer create (String name) { return (Customer) _instances.get(name); } static void loadCustomers() { new Customer("Lemon Car Hire").store(); new Customer("Associated Coffee Machines").store(); ... } private void store() { _instances.put(this.getName(), this); } public String getNamed(String name) { return (Customer) _instances.get(name); } private final String _name; private static Dictionary _instances = new Hashtable(); } class Order { public Order (String customer) { _customer = Customer.create(customer); } private Customer _customer; } Order Customer Order Customer … class Customer { public Customer (String name) { _name = name; } public String getName() { return _name; } private final String _name; } class Order { public Order (String customer) { _customer = new Customer(customer); } private Customer _customer; }
  • 6. 8.4 Change Reference to Value Classification 5/10/2011 6 class Currency { private String _code; public String getCode() { return _code; } private Currency (String code) { _code = code; } } class Currency { private String _code; public String getCode() { return _code; } private Currency (String code) { _code = code; } public boolean equals(Object arg) { if (! (arginstanceof Currency)) return false; Currency other = (Currency) arg; return (_code.equals(other._code)); } public inthashCode() { return _code.hashCode(); } } immutable?
  • 7. 8.5 Replace Array with Object Classification 5/10/2011 7 array: hard to remember each column String[] row = new String[3]; row[0] = "Liverpool"; row[1] = "15"; Performance row = new Performance(); row.setName("Liverpool"); row.setWins("15"); object: easy to maintain
  • 8. 8.6 Duplicate Observed Data Classification 5/10/2011 8 public class IntervalWindow extends Frame { TextField _startField; TextField _endField; TextField _lengthField; void StartField_FocusLost(FocusEvent event) { ... calculateLength(); } void EndtField_FocusLost(FocusEvent event) { ... calculateLength(); } void StartField_FocusLost(FocusEvent event) { ... calculateLength(); } void calculateLength() { ... } void calculateEnd() { ... } } public class IntervalWindow extends Frame implements Observer { private Interval _subject; TextField _startField; TextField _endField; TextField _lengthField; public IntervalWindow() { _subject = new Interval(); _subject.addObserver(this); update(_subject, null); } public void update(Observable observed, Object arg) { _endField.setText(_subject.getEnd()); } String getEnd() { return _subject.getEnd(); } void setEnd (Srtingarg) { _subject.setEnd(arg); } void StartField_FocusLost(FocusEvent event) { ... calculateLength(); } void EndtField_FocusLost(FocusEvent event) { ... calculateLength(); } void StartField_FocusLost(FocusEvent event) { ... calculateLength(); } } class Interval extends Observable { void calculateLength() { ... } void calculateEnd() { ... } }
  • 9. 8.7 Change Unidirectional Association to Bidirectional Classification 5/10/2011 9 Order Customer * Order Customer * class Order { Customer getCustomer() { return _customer; } void setCustomer (Customer arg) { _customer = arg; } Customer _customer; // order->customer } class Customer { private Set _orders = new HashSet(); } class Order { Customer getCustomer() { return _customer; } void setCustomer (Customer arg) { if (_customer != null) _customer.friendOrders().remove(this); _customer = arg; if (_customer != null) _customer.friendOrders().add(this); } Customer _customer; // order->customer } class Customer { private Set _orders = new HashSet(); Set friendOrders() { return _orders } void addOrder(Order arg) { arg.setCustomer(this); } }
  • 10. 8.8 Change Bidirectional Association to Unidirectional Classification 5/10/2011 10 Order Customer * Order Customer * class Order { Customer getCustomer() { return _customer; } void setCustomer (Customer arg) { if (_customer != null) _customer.friendOrders().remove(this); _customer = arg; if (_customer != null) _customer.friendOrders().add(this); } double getDiscountedPrice() { return getGrossPrice() * (1 - _customer.getDiscount()); } Customer _customer; // order->customer } class Customer { getPriceFor(Order order) { Assert.isTrue(_orders.contains(order)); return order.getDiscountedPrice(); } } class Order { Customer getCustomer() { return _customer; } CustomersetCustomer () { Iteratoriter = Customer.getInstances().iterator(); while (iter.hasNext()) { Customer each = (Customer)iter.next(); if (each.containsOrder(this)) return each; } return null; } double getDiscountedPrice(Customer customer) { return getGrossPrice() * (1 - customer.getDiscount()); } Customer _customer; // order->customer } class Customer { getPriceFor(Order order) { Assert.isTrue(_orders.contains(order)); return order.getDiscountedPrice(this); } }
  • 11. Thank You Classification 5/10/2011 11

Editor's Notes

  1. Maybe need First name/Last name in the future.