SlideShare a Scribd company logo
1 of 37
Hubert Chan Refactoring – chap 8-2
8.9 Replace Magic Number with Symbolic Constant Magic Number 特性 具有特殊意義,卻又不能明確表現出其意義。 可讀性差 / 不明確 / 牽一髮動全身 解決方案 以 Constant 取代Magic Number double potentialEngery(double mass, double height) {     return mass * 9.81 * height } double potentialEngery(double mass, double height) {     return mass * GRAVITATIONAL_CONSTANT * height } static final double GRAVITATIONAL_CONTSTANT = 9.81;
8.9 Replace Magic Number with Symbolic Constant Refactoring 時機 Magic Number 是 Type Code Replace Type Code With Class 陣列長度 使用 Array.length() 關鍵字 const static final
8.10 Encapsulate Field class A {   public String _name; } class A { private String _name;  public String getName() {return _name;}  public void setName(String arg) {_name = arg;} }
8.10 Encapsulate Field 動機 封裝 Encapsulation 資料隱藏 Data Hiding public 欄位:資料可以被修改、存取,但是擁有的物件卻無法控制其行為 改變存取資料為(Objective-C 2.0 property) readonly readwrite assign copy
8.11 Encapsulate Collection 目的 傳回 Collection 的一個 readonly view 提供 add/remove 元素的 function
8.11 Encapsulate Collection 動機 Getter 不該傳回 collection 本身 暴露過多實作細節 使用者可以存取 getter 拿到的 collection 使用 add/remove 函式添加元素 使用者不用管底層使用哪種 Collection(List, Array, Vector)
8.11 Encapsulate Collection class Course {   public Course (String name, booleanisAdvanced) {}   public booleanisAdvanced() {} } Class Person {  public Set getCourses() {    return _courses;  }  public void setCourses(Set arg) {    _courses = arg;  }  private Set _courses; } //使用者直接操作 data //直接 assign,非複製
8.11 Encapsulate Collection Person kent = new Person(); Set s = new HashSet(); s.add(new Course("Smalltalk Programming", false)); s.add(new Course("Appreciating Single Malts", true)); kent.setCourses(s); Course refact = new Course("Refactoring", true); kent.getCourses().add(refact); kent.getCourses().remove(refact); //直接 assign,非複製 //使用者直接操作 data //使用者直接操作 data
8.11 Encapsulate Collection Refactoring for JAVA 1.2 –  使用 add/remove 函式 Class Person {  public void addCourse(Course arg) {    _courses.add(arg);  }  public void removeCourse(Course arg)    _courses.remove(arg);  }  public void initializeCourses(Set arg) { Assert.isTrue(_courses.isEmpty()); _courses.addAll(arg);  } } //內部的 _courses != arg
8.11 Encapsulate Collection Refactoring for JAVA 1.2 –  使用 add/remove 函式 Person kent = new Person(); Set s = new HashSet(); s.add(new Course("Smalltalk Programming", false)); s.add(new Course("Appreciating Single Malts", true)); kent.setCourses(s); Person kent = new Person(); kent.addCourse(new Course("Smalltalk Programming", false)); kent.addCourse(new Course("Appreciating Single Malts", true));
8.11 Encapsulate Collection Refactoring for JAVA 1.2 –  不該讓使用者透過 getter 修改物件內的 collection Getter 回傳 unmodified set kent.getCourses().add(new Course("C Programming", false)); Class Person {   public Set getCourse() { return Collections.unmodifiableSet(_courses);} } //回傳 unmodifiable的 Set
8.11 Encapsulate Collection 將行為移至 class 內 Move Method 更好維護 class Person { intnumberOfAdvancedCourses(Person person) {    Iterator iter = person.getCourses().iterator(); int count = 0;    while (iter.hasNext()) {      Course each = (Course) iter.next();      if (each.isAdvanced()) count++;    }    return count;   } }
8.12 Replace Record with Data Class 手法 把傳統的 record structure 轉為 data class 使用 getter/setter class Person {   String getName() {    return _name;  }   String setName(String arg) {    _name = arg;  }  private String _name; } class PersonRecord {   public char[] name; }
8.13 Replace Type Code with Class 目的 Type Code 沒有型別檢驗 Type Code => Class,factory class 可以做型別檢驗
8.13 Replace Type Code with Class 目標是 Person 中的 Type Code  class Person {     public static final int O = 0;     public static final int A = 1;     public static final int B = 2;     public static final int AB = 3;     private int _bloodGroup;     public Person (intbloodGroup) {         _bloodGroup = bloodGroup;     }     public void setBloodGroup(intarg) {         _bloodGroup = arg;     }     public intgetBloodGroup() {         return _bloodGroup;     }   } //型別是 int,不是特別的型別
8.13 Replace Type Code with Class 把 Person 中 Type Code 換成 BloodGroup Class  class BloodGroup {     public static final BloodGroup O = new BloodGroup(0);     public static final BloodGroup A = new BloodGroup(1);     public static final BloodGroup B = new BloodGroup(2);     public static final BloodGroup AB = new BloodGroup(3);     private static final BloodGroup[] _values = {O, A, B, AB};     private finalint _code; privateBloodGroup (int code ) {         _code = code;     }     public intgetCode() {         return _code;     }     public static BloodGroup code(intarg) {         return _values[arg];     }   } //class instance 而非 Type Code //constructor 是 private
8.13 Replace Type Code with Class 使用 Class 並維持原本的對外介面  class Person {     public static final int O = BloodGroup.O.getCode();     public static final int A = BloodGroup.A.getCode();     public static final int B = BloodGroup.B.getCode();     public static final int AB = BloodGroup.AB.getCode(); private BloodGroup _bloodGroup;     public Person (intbloodGroup) {         _bloodGroup = BloodGroup.code(bloodGroup);     }     public intgetBloodGroup() {         return _bloodGroup.getCode();     }     public void setBloodGroup(intarg) {         _bloodGroup = BloodGroup.code (arg);     }   }
8.13 Replace Type Code with Class 在 Constructor 使用 Class 做參數 為新的介面加入 setter/getter  class Person {      public Person (BloodGroupbloodGroup) {         _bloodGroup = bloodGroup;     }     public void setBloodGroup(BloodGrouparg) {         _bloodGroup = arg; }    public BloodGroupgetBloodGroup() {         return _bloodGroup;     }   } //使用 BloodGroup // Setter // Getter
8.13 Replace Type Code with Class 使用者端的改變 Person thePerson = new Person(PersonA); thePerson.getBloodGroupCode(); thePerson.setBloodGroup(Person.AB); Person thePerson = new Person(BloodGroup.A); thePerson.getBloodGroup(); thePerson.setBloodGroup(BloodGroup.AB);
8.14 Replace Type Code with Subclasses 使用時機 有一個 type code 會影響 class 的行為 為了 Replace Conditional with Polymorphism 鋪路 彰顯「特定類別的行為」
8.14 Replace Type Code with Subclasses 目標 class 具有會影響行為的 type code  class Employee{     private int _type;     static final int ENGINEER = 0;     static final int SALESMAN = 1;     static final int MANAGER = 2;     Employee (int type) {         _type = type; } } //Type Code
8.14 Replace Type Code with Subclasses 在 Base Class 將行為的 function 抽出來 getType()  class Employee{ abstractintgetType(); }  class Engineer extends Employee { intgetType() {     return Employee.ENGINEER;   } } //abstract 強制 subclass 需要 implement // implement
8.14 Replace Type Code with Subclasses 修改 factory class  class Employee {     static Employee create(int type) { switch (type) {             case ENGINEER:                return new Engineer();             case SALESMAN:                return new Salesman();             case MANAGER:                return new Manager();            default:               ...     }  } //getType邏輯在各類別中
8.14 Replace Type Code with Subclasses Refactoring 之後 把只與各個類別相關的函式放在類別中 Push Down Method Push Down Field
8.15 Replace Type Code with State/Strategy 使用時機 有一個 type code 他會影響 class 行為 無法使用 subclassing,例如 type 可變 手法 以 state object 取代 type code 比較 Replace Type Code with Class
8.15 Replace Type Code with State/Strategy 目標:將 type code 以 state object 取代  class Employee{     private int _type;     static final int ENGINEER = 0;     static final int SALESMAN = 1;     static final int MANAGER = 2;     Employee (int type) {         _type = type; } } //Type Code
8.15 Replace Type Code with State/Strategy 觀察:如何使用 type code  class Employee{ intpayAmount() {         switch (_type) {             case ENGINEER:                return _monthlySalary;             case SALESMAN:                return _monthlySalary + _commission;             case MANAGER:                return _monthlySalary + _bonus;             default:                throw new RuntimeException("Incorrect Employee");         } } } //依照 Type Code 進行運算
8.15 Replace Type Code with State/Strategy 設計 state object / 共有 state 的部份 使用 abstract class / abstract function  abstract class EmployeeType {     abstract intgetTypeCode();   }   class Engineer extends EmployeeType { intgetTypeCode () {         return Employee.ENGINEER;     }   } //abstract function //subclass implementation
8.15 Replace Type Code with State/Strategy 改變 state 時,改變 state object 的 class  class Employee...     private EmployeeType _type;     void setType(intarg) {         switch (arg) {             case ENGINEER:                _type = new Engineer();                break;             case SALESMAN:                _type = new Salesman();                break;             case MANAGER:                _type = new Manager();                break;             default:               ...         }     } //很像 factory pattern //搬出去?
8.15 Replace Type Code with State/Strategy 將 factory method 放到 state object  class Employee...     void setType(intarg) {         _type = EmployeeType.newType(arg);     } class EmployeeType...     static EmployeeTypenewType(int code) {         switch (code) {             case ENGINEER:                return new Engineer();             case SALESMAN:                return new Salesman();             case MANAGER:                return new Manager();             default:               ...         }     }     static final int ENGINEER = 0;     static final int SALESMAN = 1;     static final int MANAGER = 2; //setter 使用 state class 的 factory method // state class 的 factory method
8.15 Replace Type Code with State/Strategy 以 state object 的 state 進行運算 接著可以用 Replace Conditional with Polymorphism  class Employee... intpayAmount() {         switch (getType()) {             case EmployeeType.ENGINEER:                return _monthlySalary;             case EmployeeType.SALESMAN:                return _monthlySalary + _commission;             case EmployeeType.MANAGER:                return _monthlySalary + _bonus;             default: ...         }     }
8.16 Replace Subclass with Fields 使用時機 Subclass 的 function 是 constant method 可以透過回傳一個 field 來取代 constant method
8.16 Replace Subclass with Fields 觀察 abstract method 都只是回傳 hard-code 資料  abstract class Person {     abstract booleanisMale();     abstract char getCode();   ...   class Male extends Person { booleanisMale() {         return true;     }     char getCode() {         return 'M';     }   } //return hard-code //return hard-code
8.16 Replace Subclass with Fields 以 Factory Method 隱藏 subclass 類別 設定 subclass 的 constructor 為 private 未來可以移除 subclass  class Person...     static Person createMale(){         return new Male();     }     static Person createFemale() {         return new Female();     }
8.16 Replace Subclass with Fields 為 superclass 加上想要取代的 field  class Person...     protected Person (booleanisMale, char code) {         _isMale = isMale;         _code = code; } booleanisMale() {         return _isMale; } class Male...     Male() {         super (true, 'M'); } //以 Field 取代 subclass 的 function
8.16 Replace Subclass with Fields 移除無用的 subclass  class Person     static Person createMale(){         return new Person(true, 'M');     } //以 factory pattern 抽換類別

More Related Content

What's hot

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
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1Teksify
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy
 
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
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 

What's hot (20)

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

Viewers also liked

Sm Case4 Fuji Xerox
Sm Case4 Fuji XeroxSm Case4 Fuji Xerox
Sm Case4 Fuji XeroxChris Huang
 
Sm Case2 Walmart
Sm Case2 WalmartSm Case2 Walmart
Sm Case2 WalmartChris 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
 
Disney報告 最終版
Disney報告 最終版Disney報告 最終版
Disney報告 最終版Chris Huang
 
重構—改善既有程式的設計(chapter 1)
重構—改善既有程式的設計(chapter 1)重構—改善既有程式的設計(chapter 1)
重構—改善既有程式的設計(chapter 1)Chris Huang
 
重構三兩事
重構三兩事重構三兩事
重構三兩事teddysoft
 

Viewers also liked (7)

Sm Case4 Fuji Xerox
Sm Case4 Fuji XeroxSm Case4 Fuji Xerox
Sm Case4 Fuji Xerox
 
Sm Case1 Ikea
Sm Case1 IkeaSm Case1 Ikea
Sm Case1 Ikea
 
Sm Case2 Walmart
Sm Case2 WalmartSm Case2 Walmart
Sm Case2 Walmart
 
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
 
Disney報告 最終版
Disney報告 最終版Disney報告 最終版
Disney報告 最終版
 
重構—改善既有程式的設計(chapter 1)
重構—改善既有程式的設計(chapter 1)重構—改善既有程式的設計(chapter 1)
重構—改善既有程式的設計(chapter 1)
 
重構三兩事
重構三兩事重構三兩事
重構三兩事
 

Similar to Replace Magic Number with Symbolic Constant in Java Code

Generic Programming seminar
Generic Programming seminarGeneric Programming seminar
Generic Programming seminarGautam Roy
 
Cambio de bases
Cambio de basesCambio de bases
Cambio de basesalcon2015
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEDarwin Durand
 
The Ring programming language version 1.7 book - Part 87 of 196
The Ring programming language version 1.7 book - Part 87 of 196The Ring programming language version 1.7 book - Part 87 of 196
The Ring programming language version 1.7 book - Part 87 of 196Mahmoud Samir Fayed
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java DevelopersYakov Fain
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014First Tuesday Bergen
 
李建忠、侯捷设计模式讲义
李建忠、侯捷设计模式讲义李建忠、侯捷设计模式讲义
李建忠、侯捷设计模式讲义yiditushe
 
Function Procedure Trigger Partition.pdf
Function Procedure Trigger Partition.pdfFunction Procedure Trigger Partition.pdf
Function Procedure Trigger Partition.pdfSanam Maharjan
 
The Ring programming language version 1.8 book - Part 90 of 202
The Ring programming language version 1.8 book - Part 90 of 202The Ring programming language version 1.8 book - Part 90 of 202
The Ring programming language version 1.8 book - Part 90 of 202Mahmoud Samir Fayed
 
Should be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdfShould be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdffashionscollect
 
Presentacion clean code
Presentacion clean codePresentacion clean code
Presentacion clean codeIBM
 
The Ring programming language version 1.5.3 book - Part 91 of 184
The Ring programming language version 1.5.3 book - Part 91 of 184The Ring programming language version 1.5.3 book - Part 91 of 184
The Ring programming language version 1.5.3 book - Part 91 of 184Mahmoud Samir Fayed
 
I want a java program that can convert a number of base 10 into its .pdf
I want a java program that can convert a number of base 10 into its .pdfI want a java program that can convert a number of base 10 into its .pdf
I want a java program that can convert a number of base 10 into its .pdffashiongallery1
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2Warui Maina
 
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
 

Similar to Replace Magic Number with Symbolic Constant in Java Code (20)

Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 
Generic Programming seminar
Generic Programming seminarGeneric Programming seminar
Generic Programming seminar
 
Cambio de bases
Cambio de basesCambio de bases
Cambio de bases
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
The Ring programming language version 1.7 book - Part 87 of 196
The Ring programming language version 1.7 book - Part 87 of 196The Ring programming language version 1.7 book - Part 87 of 196
The Ring programming language version 1.7 book - Part 87 of 196
 
Functions
FunctionsFunctions
Functions
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java Developers
 
Dependency Injection for Android
Dependency Injection for AndroidDependency Injection for Android
Dependency Injection for Android
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
 
李建忠、侯捷设计模式讲义
李建忠、侯捷设计模式讲义李建忠、侯捷设计模式讲义
李建忠、侯捷设计模式讲义
 
Function Procedure Trigger Partition.pdf
Function Procedure Trigger Partition.pdfFunction Procedure Trigger Partition.pdf
Function Procedure Trigger Partition.pdf
 
The Ring programming language version 1.8 book - Part 90 of 202
The Ring programming language version 1.8 book - Part 90 of 202The Ring programming language version 1.8 book - Part 90 of 202
The Ring programming language version 1.8 book - Part 90 of 202
 
Should be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdfShould be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdf
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
Presentacion clean code
Presentacion clean codePresentacion clean code
Presentacion clean code
 
The Ring programming language version 1.5.3 book - Part 91 of 184
The Ring programming language version 1.5.3 book - Part 91 of 184The Ring programming language version 1.5.3 book - Part 91 of 184
The Ring programming language version 1.5.3 book - Part 91 of 184
 
I want a java program that can convert a number of base 10 into its .pdf
I want a java program that can convert a number of base 10 into its .pdfI want a java program that can convert a number of base 10 into its .pdf
I want a java program that can convert a number of base 10 into its .pdf
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 
JPA 2.0
JPA 2.0JPA 2.0
JPA 2.0
 
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
 

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

More from Chris Huang (20)

Data compression, data security, and machine learning
Data compression, data security, and machine learningData compression, data security, and machine learning
Data compression, data security, and machine learning
 
Kks sre book_ch10
Kks sre book_ch10Kks sre book_ch10
Kks sre book_ch10
 
Kks sre book_ch1,2
Kks sre book_ch1,2Kks sre book_ch1,2
Kks sre book_ch1,2
 
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)
 
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
 

Recently uploaded

ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
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
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
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
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.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
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
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
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 

Replace Magic Number with Symbolic Constant in Java Code

  • 1. Hubert Chan Refactoring – chap 8-2
  • 2. 8.9 Replace Magic Number with Symbolic Constant Magic Number 特性 具有特殊意義,卻又不能明確表現出其意義。 可讀性差 / 不明確 / 牽一髮動全身 解決方案 以 Constant 取代Magic Number double potentialEngery(double mass, double height) { return mass * 9.81 * height } double potentialEngery(double mass, double height) { return mass * GRAVITATIONAL_CONSTANT * height } static final double GRAVITATIONAL_CONTSTANT = 9.81;
  • 3. 8.9 Replace Magic Number with Symbolic Constant Refactoring 時機 Magic Number 是 Type Code Replace Type Code With Class 陣列長度 使用 Array.length() 關鍵字 const static final
  • 4. 8.10 Encapsulate Field class A { public String _name; } class A { private String _name; public String getName() {return _name;} public void setName(String arg) {_name = arg;} }
  • 5. 8.10 Encapsulate Field 動機 封裝 Encapsulation 資料隱藏 Data Hiding public 欄位:資料可以被修改、存取,但是擁有的物件卻無法控制其行為 改變存取資料為(Objective-C 2.0 property) readonly readwrite assign copy
  • 6. 8.11 Encapsulate Collection 目的 傳回 Collection 的一個 readonly view 提供 add/remove 元素的 function
  • 7. 8.11 Encapsulate Collection 動機 Getter 不該傳回 collection 本身 暴露過多實作細節 使用者可以存取 getter 拿到的 collection 使用 add/remove 函式添加元素 使用者不用管底層使用哪種 Collection(List, Array, Vector)
  • 8. 8.11 Encapsulate Collection class Course { public Course (String name, booleanisAdvanced) {} public booleanisAdvanced() {} } Class Person { public Set getCourses() { return _courses; } public void setCourses(Set arg) { _courses = arg; } private Set _courses; } //使用者直接操作 data //直接 assign,非複製
  • 9. 8.11 Encapsulate Collection Person kent = new Person(); Set s = new HashSet(); s.add(new Course("Smalltalk Programming", false)); s.add(new Course("Appreciating Single Malts", true)); kent.setCourses(s); Course refact = new Course("Refactoring", true); kent.getCourses().add(refact); kent.getCourses().remove(refact); //直接 assign,非複製 //使用者直接操作 data //使用者直接操作 data
  • 10. 8.11 Encapsulate Collection Refactoring for JAVA 1.2 – 使用 add/remove 函式 Class Person { public void addCourse(Course arg) { _courses.add(arg); } public void removeCourse(Course arg) _courses.remove(arg); } public void initializeCourses(Set arg) { Assert.isTrue(_courses.isEmpty()); _courses.addAll(arg); } } //內部的 _courses != arg
  • 11. 8.11 Encapsulate Collection Refactoring for JAVA 1.2 – 使用 add/remove 函式 Person kent = new Person(); Set s = new HashSet(); s.add(new Course("Smalltalk Programming", false)); s.add(new Course("Appreciating Single Malts", true)); kent.setCourses(s); Person kent = new Person(); kent.addCourse(new Course("Smalltalk Programming", false)); kent.addCourse(new Course("Appreciating Single Malts", true));
  • 12. 8.11 Encapsulate Collection Refactoring for JAVA 1.2 – 不該讓使用者透過 getter 修改物件內的 collection Getter 回傳 unmodified set kent.getCourses().add(new Course("C Programming", false)); Class Person { public Set getCourse() { return Collections.unmodifiableSet(_courses);} } //回傳 unmodifiable的 Set
  • 13. 8.11 Encapsulate Collection 將行為移至 class 內 Move Method 更好維護 class Person { intnumberOfAdvancedCourses(Person person) { Iterator iter = person.getCourses().iterator(); int count = 0; while (iter.hasNext()) { Course each = (Course) iter.next(); if (each.isAdvanced()) count++; } return count; } }
  • 14. 8.12 Replace Record with Data Class 手法 把傳統的 record structure 轉為 data class 使用 getter/setter class Person { String getName() { return _name; } String setName(String arg) { _name = arg; } private String _name; } class PersonRecord { public char[] name; }
  • 15. 8.13 Replace Type Code with Class 目的 Type Code 沒有型別檢驗 Type Code => Class,factory class 可以做型別檢驗
  • 16. 8.13 Replace Type Code with Class 目標是 Person 中的 Type Code class Person { public static final int O = 0; public static final int A = 1; public static final int B = 2; public static final int AB = 3; private int _bloodGroup; public Person (intbloodGroup) { _bloodGroup = bloodGroup; } public void setBloodGroup(intarg) { _bloodGroup = arg; } public intgetBloodGroup() { return _bloodGroup; } } //型別是 int,不是特別的型別
  • 17. 8.13 Replace Type Code with Class 把 Person 中 Type Code 換成 BloodGroup Class class BloodGroup { public static final BloodGroup O = new BloodGroup(0); public static final BloodGroup A = new BloodGroup(1); public static final BloodGroup B = new BloodGroup(2); public static final BloodGroup AB = new BloodGroup(3); private static final BloodGroup[] _values = {O, A, B, AB}; private finalint _code; privateBloodGroup (int code ) { _code = code; } public intgetCode() { return _code; } public static BloodGroup code(intarg) { return _values[arg]; } } //class instance 而非 Type Code //constructor 是 private
  • 18. 8.13 Replace Type Code with Class 使用 Class 並維持原本的對外介面 class Person { public static final int O = BloodGroup.O.getCode(); public static final int A = BloodGroup.A.getCode(); public static final int B = BloodGroup.B.getCode(); public static final int AB = BloodGroup.AB.getCode(); private BloodGroup _bloodGroup; public Person (intbloodGroup) { _bloodGroup = BloodGroup.code(bloodGroup); } public intgetBloodGroup() { return _bloodGroup.getCode(); } public void setBloodGroup(intarg) { _bloodGroup = BloodGroup.code (arg); } }
  • 19. 8.13 Replace Type Code with Class 在 Constructor 使用 Class 做參數 為新的介面加入 setter/getter class Person { public Person (BloodGroupbloodGroup) { _bloodGroup = bloodGroup; } public void setBloodGroup(BloodGrouparg) { _bloodGroup = arg; } public BloodGroupgetBloodGroup() { return _bloodGroup; } } //使用 BloodGroup // Setter // Getter
  • 20. 8.13 Replace Type Code with Class 使用者端的改變 Person thePerson = new Person(PersonA); thePerson.getBloodGroupCode(); thePerson.setBloodGroup(Person.AB); Person thePerson = new Person(BloodGroup.A); thePerson.getBloodGroup(); thePerson.setBloodGroup(BloodGroup.AB);
  • 21. 8.14 Replace Type Code with Subclasses 使用時機 有一個 type code 會影響 class 的行為 為了 Replace Conditional with Polymorphism 鋪路 彰顯「特定類別的行為」
  • 22. 8.14 Replace Type Code with Subclasses 目標 class 具有會影響行為的 type code class Employee{ private int _type; static final int ENGINEER = 0; static final int SALESMAN = 1; static final int MANAGER = 2; Employee (int type) { _type = type; } } //Type Code
  • 23. 8.14 Replace Type Code with Subclasses 在 Base Class 將行為的 function 抽出來 getType() class Employee{ abstractintgetType(); } class Engineer extends Employee { intgetType() { return Employee.ENGINEER; } } //abstract 強制 subclass 需要 implement // implement
  • 24. 8.14 Replace Type Code with Subclasses 修改 factory class class Employee { static Employee create(int type) { switch (type) { case ENGINEER: return new Engineer(); case SALESMAN: return new Salesman(); case MANAGER: return new Manager(); default: ... } } //getType邏輯在各類別中
  • 25. 8.14 Replace Type Code with Subclasses Refactoring 之後 把只與各個類別相關的函式放在類別中 Push Down Method Push Down Field
  • 26. 8.15 Replace Type Code with State/Strategy 使用時機 有一個 type code 他會影響 class 行為 無法使用 subclassing,例如 type 可變 手法 以 state object 取代 type code 比較 Replace Type Code with Class
  • 27. 8.15 Replace Type Code with State/Strategy 目標:將 type code 以 state object 取代 class Employee{ private int _type; static final int ENGINEER = 0; static final int SALESMAN = 1; static final int MANAGER = 2; Employee (int type) { _type = type; } } //Type Code
  • 28. 8.15 Replace Type Code with State/Strategy 觀察:如何使用 type code class Employee{ intpayAmount() { switch (_type) { case ENGINEER: return _monthlySalary; case SALESMAN: return _monthlySalary + _commission; case MANAGER: return _monthlySalary + _bonus; default: throw new RuntimeException("Incorrect Employee"); } } } //依照 Type Code 進行運算
  • 29. 8.15 Replace Type Code with State/Strategy 設計 state object / 共有 state 的部份 使用 abstract class / abstract function abstract class EmployeeType { abstract intgetTypeCode(); } class Engineer extends EmployeeType { intgetTypeCode () { return Employee.ENGINEER; } } //abstract function //subclass implementation
  • 30. 8.15 Replace Type Code with State/Strategy 改變 state 時,改變 state object 的 class class Employee... private EmployeeType _type; void setType(intarg) { switch (arg) { case ENGINEER: _type = new Engineer(); break; case SALESMAN: _type = new Salesman(); break; case MANAGER: _type = new Manager(); break; default: ... } } //很像 factory pattern //搬出去?
  • 31. 8.15 Replace Type Code with State/Strategy 將 factory method 放到 state object class Employee... void setType(intarg) { _type = EmployeeType.newType(arg); } class EmployeeType... static EmployeeTypenewType(int code) { switch (code) { case ENGINEER: return new Engineer(); case SALESMAN: return new Salesman(); case MANAGER: return new Manager(); default: ... } } static final int ENGINEER = 0; static final int SALESMAN = 1; static final int MANAGER = 2; //setter 使用 state class 的 factory method // state class 的 factory method
  • 32. 8.15 Replace Type Code with State/Strategy 以 state object 的 state 進行運算 接著可以用 Replace Conditional with Polymorphism class Employee... intpayAmount() { switch (getType()) { case EmployeeType.ENGINEER: return _monthlySalary; case EmployeeType.SALESMAN: return _monthlySalary + _commission; case EmployeeType.MANAGER: return _monthlySalary + _bonus; default: ... } }
  • 33. 8.16 Replace Subclass with Fields 使用時機 Subclass 的 function 是 constant method 可以透過回傳一個 field 來取代 constant method
  • 34. 8.16 Replace Subclass with Fields 觀察 abstract method 都只是回傳 hard-code 資料 abstract class Person { abstract booleanisMale(); abstract char getCode(); ... class Male extends Person { booleanisMale() { return true; } char getCode() { return 'M'; } } //return hard-code //return hard-code
  • 35. 8.16 Replace Subclass with Fields 以 Factory Method 隱藏 subclass 類別 設定 subclass 的 constructor 為 private 未來可以移除 subclass class Person... static Person createMale(){ return new Male(); } static Person createFemale() { return new Female(); }
  • 36. 8.16 Replace Subclass with Fields 為 superclass 加上想要取代的 field class Person... protected Person (booleanisMale, char code) { _isMale = isMale; _code = code; } booleanisMale() { return _isMale; } class Male... Male() { super (true, 'M'); } //以 Field 取代 subclass 的 function
  • 37. 8.16 Replace Subclass with Fields 移除無用的 subclass class Person static Person createMale(){ return new Person(true, 'M'); } //以 factory pattern 抽換類別