SlideShare a Scribd company logo
1 of 22
Refactoring Chapter 9 Simplifying Conditional Expressions
Read this and then read this Decompose Conditional if (date.before (SUMMER_START) || date.after(SUMMER_END)) 	charge = quantity * _winterRate + _winterServiceCharge; else charge = quantity * _summerRate; if (notSummer(date)) 	charge = winterCharge(quantity); else 	charge = summerCharge (quantity);
Consolidate Conditional Expression Before: After: double disabilityAmount() {        if (_seniority < 2) return 0;        if (_monthsDisabled > 12) return 0;        if (_isPartTime) return 0;        // ... } double disabilityAmount() {        if (isNotEligableForDisability()) return 0;        // ... }
Before if (isSpecialDeal()) { doSomePreparation(); doNonRelatedWork(); 	total = price * 0.95; 	send(); doSomeCleanUp(); } else { doSomePreparation(); 	total = price * 0.98; 	send(); doNonRelatedWork(); doSomeCleanUp(); } Consolidate Duplicate Conditional Fragments
Consolidate Duplicate Conditional Fragments After doNonRelatedWork(); doSomePreparation(); if (isSpecialDeal())  	total = price * 0.95; else 	total = price * 0.98; send(); doSomeCleanUp();
Remove Control Flag Trace this void checkSecurity(String[] people) { boolean found = false; 	for (int i = 0; i < people.length; i++) { 		if (! found) { 			if (people[i].equals ("Don")){ sendAlert(); 				found = true; 			} 			if (people[i].equals ("John")){ sendAlert(); 				found = true; 			} 		} 	} }
Remove Control Flag ○use return, break, continue … ✕set a flag and check somewhere later
Alternative 1: Remove Control Flag void checkSecurity(String[] people) { 	for (int i = 0; i < people.length; i++) { 		if (people[i].equals ("Don")){ sendAlert(); 			break; 		} 		if (people[i].equals ("John")){ sendAlert(); 			break; 		} 	} }
Alternative 2: Remove Control Flag void checkSecurity(String[] people) { 	String found = foundMiscreant(people); someLaterCode(found); } String foundMiscreant(String[] people) { 	for (int i = 0; i < people.length; i++) { 		if (people[i].equals ("Don")){ sendAlert(); 			return "Don"; 		} 		if (people[i].equals ("John")){ sendAlert(); 			return "John"; 		} 	} 	return ""; }
Before Replace Nested Conditional with Guard Clauses double getPayAmount() { 	double result; 	if (_isDead) { 		result = deadAmount(); 	} else { 		if (_isSeparated) { 		result = separatedAmount(); 		} else { 			if (_isRetired) result = retiredAmount(); 			else result = normalPayAmount(); 		} 	} 	return result; }
After Replace Nested Conditional with Guard Clauses double getPayAmount() { 	if (_isDead) 		return deadAmount(); 	if (_isSeparated) 		return separatedAmount(); 	if (_isRetired) 		return retiredAmount(); 	return normalPayAmount(); };
Mind implicit semantics ,[object Object],-> (somehow) exceptional condition ,[object Object],-> two equivalent normal conditions Replace Nested Conditional with Guard Clauses
Replace Nested Conditional with Guard Clauses However, you might have seen this … if (aquireResource1()) { 	if (aquireResource2()) { if (aquireResource3()){ 		if (aquireResource4()) { 			doRealWork(); releaseResource4(); 		} 			releaseResource3(); 	} 	releaseResource2(); 	} releaseResource1(); }
Replace Nested Conditional with Guard Clauses or this … if (false == aquireResource1()) return; if (false == aquireResource2()) { releaseResource1(); 	return; } if (false == aquireResource3()){ releaseResource2(); releaseResource1(); return; } doRealWork(); releaseResource3(); releaseResource2(); releaseResource1(); return;
Before Replace Conditional with Polymorphism class Employee...     int payAmount(Employee) {         switch (getType()) {             case EmployeeType.ENGINEER:                return _monthlySalary;             case EmployeeType.SALESMAN:                return _monthlySalary + _commission;             case EmployeeType.MANAGER:                return _monthlySalary + _bonus;             default:                throw new RuntimeException("Incorrect Employee");         }     }
! ○Polymorphism might be better, usually Replace Conditional with Polymorphism switch case clauses
class Employee... intpayAmount() {         return _type.payAmount(this); } class Salesman... intpayAmount(Employee emp) {         return emp.getMonthlySalary() + emp.getCommission();     } class Manager... intpayAmount(Employee emp) {         return emp.getMonthlySalary() + emp.getBonus();     } After Replace Conditional with Polymorphism
[object Object]
deal with special cases extensively checked
check type -> check NULL
Before:Introduce Null Object class Customer...     public String getName() {...}     public BillingPlangetPlan() {...}     public PaymentHistorygetHistory() {...} if (customer == null) plan = BillingPlan.basic(); else plan = customer.getPlan();
After Introduce Null Object plan = customer.getPlan(); class NullCustomer...     public BillingPlangetPlan(){         return BillingPlan.basic();     }

More Related Content

What's hot

12. stl örnekler
12.  stl örnekler12.  stl örnekler
12. stl örneklerkarmuhtam
 
Linq Sanjay Vyas
Linq   Sanjay VyasLinq   Sanjay Vyas
Linq Sanjay Vyasrsnarayanan
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overviewgourav kottawar
 
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
 
Presentacion clean code
Presentacion clean codePresentacion clean code
Presentacion clean codeIBM
 
Csharp In Detail Part1
Csharp In Detail Part1Csharp In Detail Part1
Csharp In Detail Part1Mohamed Krar
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptSeok-joon Yun
 
Extend GraphQL with directives
Extend GraphQL with directivesExtend GraphQL with directives
Extend GraphQL with directivesGreg Bergé
 
Welcome to Modern C++
Welcome to Modern C++Welcome to Modern C++
Welcome to Modern C++Seok-joon Yun
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answerssheibansari
 
What's New In Python 2.6
What's New In Python 2.6What's New In Python 2.6
What's New In Python 2.6Richard Jones
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code DevelopmentPeter Gfader
 
Rechecking SharpDevelop: Any New Bugs?
Rechecking SharpDevelop: Any New Bugs?Rechecking SharpDevelop: Any New Bugs?
Rechecking SharpDevelop: Any New Bugs?PVS-Studio
 

What's hot (20)

Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
12. stl örnekler
12.  stl örnekler12.  stl örnekler
12. stl örnekler
 
Linq Sanjay Vyas
Linq   Sanjay VyasLinq   Sanjay Vyas
Linq Sanjay Vyas
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
 
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
 
Presentacion clean code
Presentacion clean codePresentacion clean code
Presentacion clean code
 
Memory management in c++
Memory management in c++Memory management in c++
Memory management in c++
 
Csharp In Detail Part1
Csharp In Detail Part1Csharp In Detail Part1
Csharp In Detail Part1
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
 
Extend GraphQL with directives
Extend GraphQL with directivesExtend GraphQL with directives
Extend GraphQL with directives
 
Welcome to Modern C++
Welcome to Modern C++Welcome to Modern C++
Welcome to Modern C++
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
Specs2
Specs2Specs2
Specs2
 
Lecture04
Lecture04Lecture04
Lecture04
 
What's New In Python 2.6
What's New In Python 2.6What's New In Python 2.6
What's New In Python 2.6
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code Development
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
Bw14
Bw14Bw14
Bw14
 
Rechecking SharpDevelop: Any New Bugs?
Rechecking SharpDevelop: Any New Bugs?Rechecking SharpDevelop: Any New Bugs?
Rechecking SharpDevelop: Any New Bugs?
 

Viewers also liked

重構—改善既有程式的設計(chapter 4,5)
重構—改善既有程式的設計(chapter 4,5)重構—改善既有程式的設計(chapter 4,5)
重構—改善既有程式的設計(chapter 4,5)Chris Huang
 
重構—改善既有程式的設計(chapter 7)
重構—改善既有程式的設計(chapter 7)重構—改善既有程式的設計(chapter 7)
重構—改善既有程式的設計(chapter 7)Chris Huang
 
重構—改善既有程式的設計(chapter 2,3)
重構—改善既有程式的設計(chapter 2,3)重構—改善既有程式的設計(chapter 2,3)
重構—改善既有程式的設計(chapter 2,3)Chris Huang
 
重構—改善既有程式的設計(chapter 12,13)
重構—改善既有程式的設計(chapter 12,13)重構—改善既有程式的設計(chapter 12,13)
重構—改善既有程式的設計(chapter 12,13)Chris Huang
 
Approaching real-time-hadoop
Approaching real-time-hadoopApproaching real-time-hadoop
Approaching real-time-hadoopChris Huang
 
重構—改善既有程式的設計(chapter 6)
重構—改善既有程式的設計(chapter 6)重構—改善既有程式的設計(chapter 6)
重構—改善既有程式的設計(chapter 6)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 ecosystemChris Huang
 
重構—改善既有程式的設計(chapter 1)
重構—改善既有程式的設計(chapter 1)重構—改善既有程式的設計(chapter 1)
重構—改善既有程式的設計(chapter 1)Chris 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
 

Viewers also liked (9)

重構—改善既有程式的設計(chapter 4,5)
重構—改善既有程式的設計(chapter 4,5)重構—改善既有程式的設計(chapter 4,5)
重構—改善既有程式的設計(chapter 4,5)
 
重構—改善既有程式的設計(chapter 7)
重構—改善既有程式的設計(chapter 7)重構—改善既有程式的設計(chapter 7)
重構—改善既有程式的設計(chapter 7)
 
重構—改善既有程式的設計(chapter 2,3)
重構—改善既有程式的設計(chapter 2,3)重構—改善既有程式的設計(chapter 2,3)
重構—改善既有程式的設計(chapter 2,3)
 
重構—改善既有程式的設計(chapter 12,13)
重構—改善既有程式的設計(chapter 12,13)重構—改善既有程式的設計(chapter 12,13)
重構—改善既有程式的設計(chapter 12,13)
 
Approaching real-time-hadoop
Approaching real-time-hadoopApproaching real-time-hadoop
Approaching real-time-hadoop
 
重構—改善既有程式的設計(chapter 6)
重構—改善既有程式的設計(chapter 6)重構—改善既有程式的設計(chapter 6)
重構—改善既有程式的設計(chapter 6)
 
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
 
重構—改善既有程式的設計(chapter 1)
重構—改善既有程式的設計(chapter 1)重構—改善既有程式的設計(chapter 1)
重構—改善既有程式的設計(chapter 1)
 
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...
 

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

$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS a_sharif
 
Dutch php a short tale about state machine
Dutch php   a short tale about state machineDutch php   a short tale about state machine
Dutch php a short tale about state machineŁukasz Chruściel
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2eugenio pombi
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsSam Hennessy
 
package employeeType.employee;public class Employee {    private.pdf
package employeeType.employee;public class Employee {    private.pdfpackage employeeType.employee;public class Employee {    private.pdf
package employeeType.employee;public class Employee {    private.pdfsharnapiyush773
 
Command Bus To Awesome Town
Command Bus To Awesome TownCommand Bus To Awesome Town
Command Bus To Awesome TownRoss Tuck
 
Simple Commsion Calculationbuild.xmlBuilds, tests, and runs t.docx
Simple Commsion Calculationbuild.xmlBuilds, tests, and runs t.docxSimple Commsion Calculationbuild.xmlBuilds, tests, and runs t.docx
Simple Commsion Calculationbuild.xmlBuilds, tests, and runs t.docxbudabrooks46239
 
Topic12Conditional if else Execution.ppt
Topic12Conditional if else Execution.pptTopic12Conditional if else Execution.ppt
Topic12Conditional if else Execution.pptMagesh Raj
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceSeung-Bum Lee
 
Oracle PL/SQL - Creative Conditional Compilation
Oracle PL/SQL - Creative Conditional CompilationOracle PL/SQL - Creative Conditional Compilation
Oracle PL/SQL - Creative Conditional CompilationScott Wesley
 
package employeeType.employee;public class Employee {   private .pdf
package employeeType.employee;public class Employee {   private .pdfpackage employeeType.employee;public class Employee {   private .pdf
package employeeType.employee;public class Employee {   private .pdfanwarsadath111
 
Recompacting your react application
Recompacting your react applicationRecompacting your react application
Recompacting your react applicationGreg Bergé
 
I need help creating a basic and simple Java program. Here is the ex.pdf
I need help creating a basic and simple Java program. Here is the ex.pdfI need help creating a basic and simple Java program. Here is the ex.pdf
I need help creating a basic and simple Java program. Here is the ex.pdfrajeshjangid1865
 
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docx
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docxassignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docx
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docxssuser562afc1
 
Higher-Order Components — Ilya Gelman
Higher-Order Components — Ilya GelmanHigher-Order Components — Ilya Gelman
Higher-Order Components — Ilya Gelman500Tech
 
Et si on en finissait avec CRUD ?
Et si on en finissait avec CRUD ?Et si on en finissait avec CRUD ?
Et si on en finissait avec CRUD ?Julien Vinber
 

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

$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS
 
Dutch php a short tale about state machine
Dutch php   a short tale about state machineDutch php   a short tale about state machine
Dutch php a short tale about state machine
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
 
package employeeType.employee;public class Employee {    private.pdf
package employeeType.employee;public class Employee {    private.pdfpackage employeeType.employee;public class Employee {    private.pdf
package employeeType.employee;public class Employee {    private.pdf
 
Command Bus To Awesome Town
Command Bus To Awesome TownCommand Bus To Awesome Town
Command Bus To Awesome Town
 
Simple Commsion Calculationbuild.xmlBuilds, tests, and runs t.docx
Simple Commsion Calculationbuild.xmlBuilds, tests, and runs t.docxSimple Commsion Calculationbuild.xmlBuilds, tests, and runs t.docx
Simple Commsion Calculationbuild.xmlBuilds, tests, and runs t.docx
 
Topic12Conditional if else Execution.ppt
Topic12Conditional if else Execution.pptTopic12Conditional if else Execution.ppt
Topic12Conditional if else Execution.ppt
 
Topic12ConditionalExecution.ppt
Topic12ConditionalExecution.pptTopic12ConditionalExecution.ppt
Topic12ConditionalExecution.ppt
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick Reference
 
Oracle PL/SQL - Creative Conditional Compilation
Oracle PL/SQL - Creative Conditional CompilationOracle PL/SQL - Creative Conditional Compilation
Oracle PL/SQL - Creative Conditional Compilation
 
package employeeType.employee;public class Employee {   private .pdf
package employeeType.employee;public class Employee {   private .pdfpackage employeeType.employee;public class Employee {   private .pdf
package employeeType.employee;public class Employee {   private .pdf
 
Refactoring Example
Refactoring ExampleRefactoring Example
Refactoring Example
 
Ngrx slides
Ngrx slidesNgrx slides
Ngrx slides
 
Recompacting your react application
Recompacting your react applicationRecompacting your react application
Recompacting your react application
 
PHPSpec BDD for PHP
PHPSpec BDD for PHPPHPSpec BDD for PHP
PHPSpec BDD for PHP
 
I need help creating a basic and simple Java program. Here is the ex.pdf
I need help creating a basic and simple Java program. Here is the ex.pdfI need help creating a basic and simple Java program. Here is the ex.pdf
I need help creating a basic and simple Java program. Here is the ex.pdf
 
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docx
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docxassignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docx
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docx
 
Higher-Order Components — Ilya Gelman
Higher-Order Components — Ilya GelmanHigher-Order Components — Ilya Gelman
Higher-Order Components — Ilya Gelman
 
Et si on en finissait avec CRUD ?
Et si on en finissait avec CRUD ?Et si on en finissait avec CRUD ?
Et si on en finissait avec CRUD ?
 

More from 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
 
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 10)
重構—改善既有程式的設計(chapter 10)重構—改善既有程式的設計(chapter 10)
重構—改善既有程式的設計(chapter 10)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
 
Hw5 my house in yong he
Hw5 my house in yong heHw5 my house in yong he
Hw5 my house in yong heChris Huang
 
Social English Class HW4
Social English Class HW4Social English Class HW4
Social English Class HW4Chris Huang
 
Social English Class HW3
Social English Class HW3Social English Class HW3
Social English Class HW3Chris Huang
 
火柴人的故事
火柴人的故事火柴人的故事
火柴人的故事Chris Huang
 
中德文化比較
中德文化比較中德文化比較
中德文化比較Chris Huang
 
Sm Case4 Fuji Xerox
Sm Case4 Fuji XeroxSm Case4 Fuji Xerox
Sm Case4 Fuji XeroxChris Huang
 
Disney報告 最終版
Disney報告 最終版Disney報告 最終版
Disney報告 最終版Chris Huang
 

More from Chris Huang (19)

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
 
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 10)
重構—改善既有程式的設計(chapter 10)重構—改善既有程式的設計(chapter 10)
重構—改善既有程式的設計(chapter 10)
 
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
 
Hw5 my house in yong he
Hw5 my house in yong heHw5 my house in yong he
Hw5 my house in yong he
 
Social English Class HW4
Social English Class HW4Social English Class HW4
Social English Class HW4
 
Social English Class HW3
Social English Class HW3Social English Class HW3
Social English Class HW3
 
Sm Case1 Ikea
Sm Case1 IkeaSm Case1 Ikea
Sm Case1 Ikea
 
火柴人的故事
火柴人的故事火柴人的故事
火柴人的故事
 
中德文化比較
中德文化比較中德文化比較
中德文化比較
 
Sm Case4 Fuji Xerox
Sm Case4 Fuji XeroxSm Case4 Fuji Xerox
Sm Case4 Fuji Xerox
 
Disney報告 最終版
Disney報告 最終版Disney報告 最終版
Disney報告 最終版
 

Recently uploaded

Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
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
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
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
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
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
 
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
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
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
 

Recently uploaded (20)

Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
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...
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
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
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
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
 
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
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
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Ă...
 

重構—改善既有程式的設計(chapter 9)

  • 1. Refactoring Chapter 9 Simplifying Conditional Expressions
  • 2. Read this and then read this Decompose Conditional if (date.before (SUMMER_START) || date.after(SUMMER_END)) charge = quantity * _winterRate + _winterServiceCharge; else charge = quantity * _summerRate; if (notSummer(date)) charge = winterCharge(quantity); else charge = summerCharge (quantity);
  • 3. Consolidate Conditional Expression Before: After: double disabilityAmount() { if (_seniority < 2) return 0; if (_monthsDisabled > 12) return 0; if (_isPartTime) return 0; // ... } double disabilityAmount() { if (isNotEligableForDisability()) return 0; // ... }
  • 4. Before if (isSpecialDeal()) { doSomePreparation(); doNonRelatedWork(); total = price * 0.95; send(); doSomeCleanUp(); } else { doSomePreparation(); total = price * 0.98; send(); doNonRelatedWork(); doSomeCleanUp(); } Consolidate Duplicate Conditional Fragments
  • 5. Consolidate Duplicate Conditional Fragments After doNonRelatedWork(); doSomePreparation(); if (isSpecialDeal()) total = price * 0.95; else total = price * 0.98; send(); doSomeCleanUp();
  • 6. Remove Control Flag Trace this void checkSecurity(String[] people) { boolean found = false; for (int i = 0; i < people.length; i++) { if (! found) { if (people[i].equals ("Don")){ sendAlert(); found = true; } if (people[i].equals ("John")){ sendAlert(); found = true; } } } }
  • 7. Remove Control Flag ○use return, break, continue … ✕set a flag and check somewhere later
  • 8. Alternative 1: Remove Control Flag void checkSecurity(String[] people) { for (int i = 0; i < people.length; i++) { if (people[i].equals ("Don")){ sendAlert(); break; } if (people[i].equals ("John")){ sendAlert(); break; } } }
  • 9. Alternative 2: Remove Control Flag void checkSecurity(String[] people) { String found = foundMiscreant(people); someLaterCode(found); } String foundMiscreant(String[] people) { for (int i = 0; i < people.length; i++) { if (people[i].equals ("Don")){ sendAlert(); return "Don"; } if (people[i].equals ("John")){ sendAlert(); return "John"; } } return ""; }
  • 10. Before Replace Nested Conditional with Guard Clauses double getPayAmount() { double result; if (_isDead) { result = deadAmount(); } else { if (_isSeparated) { result = separatedAmount(); } else { if (_isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; }
  • 11. After Replace Nested Conditional with Guard Clauses double getPayAmount() { if (_isDead) return deadAmount(); if (_isSeparated) return separatedAmount(); if (_isRetired) return retiredAmount(); return normalPayAmount(); };
  • 12.
  • 13. Replace Nested Conditional with Guard Clauses However, you might have seen this … if (aquireResource1()) { if (aquireResource2()) { if (aquireResource3()){ if (aquireResource4()) { doRealWork(); releaseResource4(); } releaseResource3(); } releaseResource2(); } releaseResource1(); }
  • 14. Replace Nested Conditional with Guard Clauses or this … if (false == aquireResource1()) return; if (false == aquireResource2()) { releaseResource1(); return; } if (false == aquireResource3()){ releaseResource2(); releaseResource1(); return; } doRealWork(); releaseResource3(); releaseResource2(); releaseResource1(); return;
  • 15. Before Replace Conditional with Polymorphism class Employee... int payAmount(Employee) { switch (getType()) { case EmployeeType.ENGINEER: return _monthlySalary; case EmployeeType.SALESMAN: return _monthlySalary + _commission; case EmployeeType.MANAGER: return _monthlySalary + _bonus; default: throw new RuntimeException("Incorrect Employee"); } }
  • 16. ! ○Polymorphism might be better, usually Replace Conditional with Polymorphism switch case clauses
  • 17. class Employee... intpayAmount() { return _type.payAmount(this); } class Salesman... intpayAmount(Employee emp) { return emp.getMonthlySalary() + emp.getCommission(); } class Manager... intpayAmount(Employee emp) { return emp.getMonthlySalary() + emp.getBonus(); } After Replace Conditional with Polymorphism
  • 18.
  • 19. deal with special cases extensively checked
  • 20. check type -> check NULL
  • 21. Before:Introduce Null Object class Customer... public String getName() {...} public BillingPlangetPlan() {...} public PaymentHistorygetHistory() {...} if (customer == null) plan = BillingPlan.basic(); else plan = customer.getPlan();
  • 22. After Introduce Null Object plan = customer.getPlan(); class NullCustomer... public BillingPlangetPlan(){ return BillingPlan.basic(); }
  • 23. Write your assumption explicitly and clearly Introduce Assertion double getExpenseLimit() { // should have either expense limit or a primary project return (_expenseLimit != NULL_EXPENSE) ? _expenseLimit: _primaryProject.getMemberExpenseLimit(); } double getExpenseLimit() { Assert.isTrue (_expenseLimit != NULL_EXPENSE || _primaryProject != null); return (_expenseLimit != NULL_EXPENSE) ? _expenseLimit: _primaryProject.getMemberExpenseLimit(); }
  • 24. Do NOT overuse If code does work without the assertion, remove it. Introduce Assertion
  • 25. Notes Save brain power Break/prune eye-tracing as early as possible Don’t Repeat Yourself