SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

Linq Sanjay Vyas
Linq   Sanjay VyasLinq   Sanjay Vyas
Linq Sanjay Vyasrsnarayanan
 
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-13Abu Saleh
 
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 versionsaber tabatabaee
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1Teksify
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overviewgourav kottawar
 
Refactoring and code smells
Refactoring and code smellsRefactoring and code smells
Refactoring and code smellsPaul Nguyen
 
Extend GraphQL with directives
Extend GraphQL with directivesExtend GraphQL with directives
Extend GraphQL with directivesGreg Bergé
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and JavaSasha Goldshtein
 
Jumping-with-java8
Jumping-with-java8Jumping-with-java8
Jumping-with-java8Dhaval Dalal
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code DevelopmentPeter Gfader
 

Mais procurados (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
 

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

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 RavenDBtdc-globalcode
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEDarwin Durand
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в JavaDEVTYPE
 
Domänenspezifische Sprachen mit Xtext
Domänenspezifische Sprachen mit XtextDomänenspezifische Sprachen mit Xtext
Domänenspezifische Sprachen mit XtextDr. Jan Köhnlein
 
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.pdfamirthagiftsmadurai
 
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....NET Conf UY
 
TDC2016SP - Trilha .NET
TDC2016SP - Trilha .NETTDC2016SP - Trilha .NET
TDC2016SP - Trilha .NETtdc-globalcode
 
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 RavenDBOren Eini
 
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.pdfsales88
 
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.pdfallystraders
 
Ast transformations
Ast transformationsAst transformations
Ast transformationsHamletDRC
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsSam Hennessy
 
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.docxhoney725342
 
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 .docxSHIVA101531
 
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 Ali Parmaksiz
 
Combatendo code smells em Java
Combatendo code smells em Java Combatendo code smells em Java
Combatendo code smells em Java Emmanuel Neri
 

Semelhante a 重構—改善既有程式的設計(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
 

Mais de Chris Huang

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 learningChris Huang
 
Kks sre book_ch10
Kks sre book_ch10Kks sre book_ch10
Kks sre book_ch10Chris Huang
 
Kks sre book_ch1,2
Kks sre book_ch1,2Kks sre book_ch1,2
Kks sre book_ch1,2Chris 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 ecosystemChris Huang
 
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...Chris Huang
 
Approaching real-time-hadoop
Approaching real-time-hadoopApproaching real-time-hadoop
Approaching real-time-hadoopChris Huang
 
20130310 solr tuorial
20130310 solr tuorial20130310 solr tuorial
20130310 solr tuorialChris Huang
 
Scaling big-data-mining-infra2
Scaling big-data-mining-infra2Scaling big-data-mining-infra2
Scaling big-data-mining-infra2Chris Huang
 
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...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 2012Chris 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 2012Chris 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 SystemsChris Huang
 

Mais de 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
 

Último

Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 

Último (20)

Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 

重構—改善既有程式的設計(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

Notas do Editor

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