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

Linq Sanjay Vyas
Linq   Sanjay VyasLinq   Sanjay Vyas
Linq Sanjay Vyas
rsnarayanan
 
Csharp In Detail Part1
Csharp In Detail Part1Csharp In Detail Part1
Csharp In Detail Part1
Mohamed Krar
 

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-hadoop
Chris 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 ecosystem
Chris Huang
 
重構—改善既有程式的設計(chapter 1)
重構—改善既有程式的設計(chapter 1)重構—改善既有程式的設計(chapter 1)
重構—改善既有程式的設計(chapter 1)
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)

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
sharnapiyush773
 
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
anwarsadath111
 
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
rajeshjangid1865
 
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docx
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docxassignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docx
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docx
ssuser562afc1
 

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

20130310 solr tuorial
20130310 solr tuorial20130310 solr tuorial
20130310 solr tuorial
Chris Huang
 
Scaling big-data-mining-infra2
Scaling big-data-mining-infra2Scaling big-data-mining-infra2
Scaling big-data-mining-infra2
Chris Huang
 
Hbase status quo apache-con europe - nov 2012
Hbase status quo   apache-con europe - nov 2012Hbase status quo   apache-con europe - nov 2012
Hbase status quo apache-con europe - nov 2012
Chris Huang
 
Hbase schema design and sizing apache-con europe - nov 2012
Hbase schema design and sizing   apache-con europe - nov 2012Hbase schema design and sizing   apache-con europe - nov 2012
Hbase schema design and sizing apache-con europe - nov 2012
Chris Huang
 
重構—改善既有程式的設計(chapter 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 Systems
Chris Huang
 
Hw5 my house in yong he
Hw5 my house in yong heHw5 my house in yong he
Hw5 my house in yong he
Chris Huang
 
Social English Class HW3
Social English Class HW3Social English Class HW3
Social English Class HW3
Chris Huang
 
火柴人的故事
火柴人的故事火柴人的故事
火柴人的故事
Chris Huang
 
中德文化比較
中德文化比較中德文化比較
中德文化比較
Chris Huang
 
Sm Case4 Fuji Xerox
Sm Case4 Fuji XeroxSm Case4 Fuji Xerox
Sm Case4 Fuji Xerox
Chris 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

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Recently uploaded (20)

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
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
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.
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
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
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.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
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 

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