SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

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

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

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
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.pptxAreebaZafar22
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
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.christianmathematics
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdfssuserdda66b
 

Kürzlich hochgeladen (20)

Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).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
 
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
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
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.
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).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

Hinweis der Redaktion

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