CS-Notes/notes/重构.md
2018-02-22 14:47:22 +08:00

31 KiB
Raw Blame History

????? ?????????

?????????????????????????????????????????????????????????????????????

???????????????????????????????????????????

????????§³?????????????????????????????????????

????????

?????????¨®????????????Movie??Rental ?? Customer??Rental ????????? Movie ?????????

??????????????§Ö?????????? Customer ???§µ???<3F>£?????????????????????§Ú???????????§á????????<3F>£?§µ??????????????????????????????????????????????????????????????????????????§Þ????????????

???????? Movie ????????????????????? Movie ?????????????????????????§³?

???? Price ???????????????????????? Movie ?§Þ??? Price ?????????????????????????????? Price ?????§µ????? Movie ?????????????????????????????????????????<3F>£??

?????????????????

????? ??????

??????????????????????????????????????????????????????????????????????????????

??????????????????????????????????????? bug???????????

???¦Ç????????????????????????????????????????????????????????????????????????????

????????????????????§Ö?????????????????????????????????????????????????????????????????????????????<3F>£????????????????????????????????¦Ë?¨°???????????????????????

???????????????????????????????????????? Java ???? @deprecation ????????????¨¢????????§Ò????????????????????????¾ˆ??????

?????§Õ?????????????????§Õ?????????????????§Ö???????????????????????????????????????§Õ??????????????

?????????????????????????????§Ü??<3F>£????????????????????????????????????????????????????????????????????????????<3F>£??????????????????????<3F>£???????????????????

?????????????????????????????????????§Õ?????????????????????????????????????????????????????????????????????????????????§³????????????????

?????? ??????¦Æ??

1. Duplicated Code?????????

?????????????????????????????? Extract Method ????????????

???????????????????????????????? Extract Method?????????????????? Pull Up Method ??????

???????????????? Extract Method ????????????????????????? Form Template Method ??????Ùã?????????

???????????????????????????????? Extract Class ????????????????????????????§³?

2. Long Method????????????

??????????????????????????????????????

??????????????????????????¦Ä????????????????????§Õ???????????????§³?

Extract Method ??????????????????????????????????? Replace Temp with Query ?????????????Introduce Parameter Object ?? Preserve Whole Object ???????????????§Ò??????

?????????????????????????????§³?

3. Large Class?????????

?????????????????ï…?????? Extract Class ?? Extract Subclass??

???????????????????????????? Extract Interface ???????¡Â??????????????

4. Long Parameter List????????????§µ?

5. Divergent Change???????<3F>£??

????????????<3F>£?????

??????????<3F>£????? Extract Class ????????????????§³?

6. Shotgun Surgery??????????

????<3F>£????????????

??? Move Method ?? Move Field ?????????????????????????§³?

7. Feature Envy?????????

?????????????????????????????????????????????????????????????

??? Move Method ??????????????????????????? Feature Envy?????? Extract Method ??????????????

8. Data Clumps???????????

??§»??????????????????????????????????¦±????????????????????? Extract Class ????????????

9. Primitive Obsession??????????????

???????????????????????????? Replace Data Value with Object ????????<3F>I?????

10. Switch Statements??switch ???????

11. Parallel Inheritance Hierarchies????§Þ???????

???????????????????????????????????????????????

????????????§»?????????????????????????????????????????????????????????????

12. Lazy Class????????

?????????????????????????????????

13. Speculative Generality????????¦Ä?????

??§»??????????????¦Ä???????????<3F>£?????????????????????????????????????¦Ä?????????????????????????????????????????????????????????

14. Temporary Field???????????????¦²?

?????¦Í??????????????Ñk?????????????????????????????????????????????????¦±?

????????¦Ê?????????????????? Extract Class ????????????????§³?

15. Message Chains?????????????????

??????????????????????????????????????????????...????????????????????????????¦Æ?????????????????????????

???¨²????????¨²?????????????????????

16. Middle Man???§Þ????

?§Þ??????????§Ú?????????????????????§Û???????????§Ú?????????????????????§µ???? Remove Middle Man?????????????????

17. Inappropriate Intimacy??????????

??????????????????????????????? private ????

18. Alernative Classes with Different Interfaces?????????????

19. Incomplete Library Class?????????????

?????????????????????????????????????????????§»????????????????????????????????????????????????? Introduce Foreign Method???????????????????????? Introduce Local Extension??

20. Data Class?????????????

???????§»??????¦±?

????????????????????????????? Data Class ?§³?

21. Refused Bequest???????????????

?????§Ô???????§Ü??????????????????????????

??????????????????????????????????? Push Down Method ?? Push Down Field ????????????

22. Comments???????????

??? Extract Method ?????????????????????¨²?????????????????????

?????? ???????????

Java ??????? Junit ???§Ö???????

????????????????????????????????????????????????§³?

??????§Ó??????????????????

?????? ????§Ò?

§³???????????????

?????? ???????????

1. Extract Method????????????

????¦Ä?????????????????§µ????¨²??????????¨²??????????

2. Inline Method????????????

?????????????????????????????

??????????????????ÈÉ???????¨²?????

3. Inline Temp???????????????

?????????????????????????¦²???????????????????????

?????§Ø????????????<3F>I?????????????????????

double basePrice = anOrder.basePrice();
return basePrice > 1000;
return anOrder.basePrice() > 1000;

4. Replace Temp with Query??????????????????

????????????????????????????????????????????????????????§µ??????§Ø????????????????<3F>I????????????¨¢?Replace Temp with Query ?????? Extract Method ????????????????Ñk???????????????????????????

double basePrice = quantity * itemPrice;
if(basePrice > 1000)
    return basePrice * 0.95;
else
    return basePrice * 0.98;
if(basePrice() > 1000)
    return basePrice() * 0.95;
else
    return basePrice() * 0.98;

// ...
double basePrice(){
    return quantity * itemPrice;
}

5. Introduce Explaining Variable??????????????

??????????????????????????????????????????????????????????????????

if((platform.toUpperCase().indexOf("MAC") > -1) &&
  (browser.toUpperCase().indexOf("IE") > -1) &&
  wasInitialized() && resize > 0) {
    // do something
}
final boolean isMacOS = platform.toUpperCase().indexOf("MAC") > -1;
final boolean isIEBrower = browser.toUpperCase().indexOf("IE") > -1;
final boolean wasResized = resize > 0;

if(isMacOS && isIEBrower && wasInitialized() && wasResized) {
    // do something
}

6. Split Temporary Variable??????????????

?????????????????????¦²?????????????????????????????????????

?????¦È???????????????????????????????????????????§Ö???????¦±?

7. Remove Assigments to Parameters????????????????

?????????????????¨°?????????

int discount (int inputVal, int quentity, int yearToDate){
    if (inputVal > 50) inputVal -= 2;
int discount (int inputVal, int quentity, int yearToDate){
    int result = inputVal;
    if (inputVal > 50) result -= 2;

8. Replace Method with Method Object????????????????????

?????????????????? Extract Method ????????????????????¨²?????§Ú¨°?????

????????????????????????§µ???????????????????????????¦±??????????????????§ß??????????????????§³???????

9. Subsititute Algorithn???<3F>I????

?????? ???????????????

1. Move Method???????????

???§Ö???????????????????§Ú??????????¨²?????????????¨¢?

??????????????????????§³?

2. Move Field????????¦²?

???§Ö??????¦Á???????????????????????????????????????????????????????????????§³?

3. Extract Class????????

???????????????????????????

??????????????????????¦Ê?????????????????

4. Inline Class??????????????

?? Extract Class ????

5. Hide Delegate?????????§Û??????

????????????????????§Û????

class Person{
    Department department;

    public Department getDepartment(){
        return department;
    }
}

class Department{
    private Person manager;

    public Person getManager(){
        return manager;
    }
}

?????????????????????????????? Department ?????????????????? Department ????????

Person manager = john.getDepartment().getManager();

???? Peron ???????????????????????§Û????

public Person getManager(){
    return department.getManager();
}

6. Remove Middle Man??????§Þ????

?? Hide Delegate ??????????????????§Ü????????????????????

Hide Delegate ?§Ü???????????????????????????????????????????????????????????????????????§Ü?????????????§Ö?????????????????????????????????§Þ??????

7. Introduce Foreign Method??????????????

????????????????????????????????????????

???????????§ß???????????????????????????????????????????????????????????????

8. Introduce Local Extension?????????????

?? Introduce Foreign Method ???????????? Introduce Local Extension ??????????????????????????????????????????????????????????????????????????

????? ???????????

1. Self Encapsulate Field????????¦²?

???¦Í?????/???????????????§»????????????¦±???§Ö???????????????????¦²????????????§ß????????¦Ç??????????????????????????????????????????¦Å???????????

2. Replace Data Value with Object?????????????????

?????????????????¨¹?????????????????????????????????§µ??§»?????????????§»????????????????????´Â??????????????????????´Â?????????????????????????????????????????

3. Change Value to Reference??????????????????

?????????????<3F>I????????????????????????????????¦·???????????????????????????????????§Ò???????????????????????????§Ò?????????????????????????????§Ò??§Ö??????????????????????????§Ò??§µ???????????

4. Change Reference to value??????????????????

?? Change Value to Reference ??????????§Ú??????????????????????????????????????????????????????????????<3F>I?????????????????

???????????? equals() ?? hashCode() ????

5. Replace Array with Object?????????????ï‚

????????ï…???§Ö??????????????????

??????<3F>I???ï…?????????§Ö??????????????????????????????????????????????

6. Duplicate Observed Data????????????????????

?§»?????????????? GUI ????§µ??????????????????§»?????

???????????????????????§µ???????? Oberver ??????????????????? GUI ???????????????

7. Change Unidirectional Association to Bidirectional??????????????????????

??????????????????????????????????????

???????????????? Order ???? Customer??Order ?????? Customer??Customer ???????? Order ?????????§Ø??????î•

class Order{
    private Customer customer;
    public void setCustomer(Customer customer){
        if(this.customer != null)
            this.customer.removeOrder(this);
        this.customer = customer;
        this.customer.add(this);
    }
}
class Curstomer{
    private Set<Order> orders = new HashSet<>();
    public void removeOrder(Order order){
        orders.remove(order);
    }
    public void addOrder(Order order){
        orders.add(order);
    }
}

??????????? Curstomer ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

8. Change Bidirectional Association to Unidirectional??????????????????????

?? Change Unidirectional Association to Bidirectiona ?????????

?????????????????????????????????????????????????¨À??????????????????????????????????????§µ???????????????????????????

9. Replace Magic Number with Symbolic Constant???????Æü????????????

???????????????????????????????????????Æü????¦Ë?????????

10. Encapsulate Field???????¦²?

public ????????? private???????????????????

11. Encapsulate Collection??????????

????????????????????????????????????????/??????????????????????????????????????????????????????????????????????????

12. Replace Record with Data Class??????????????????

13. Replace Type Code with Class???????????????

?????????????????????????????????????????????????<3F>I????????????????????????? switch ????§µ??????? Replace Conditional with Polymorphism ??? switch????????????? Replace Type Code with Subcalss ?? Replace Type Code with State/Strategy ?????????

14. Replace Type Code with Subcalsses?????????????????

??????????????????????????????????????????????????

15. Replace Type Code with State/Strategy ???? State/Strategy ?????????

???????????????????????????????????????????????

?? Replace Type Code with Subcalsses ???????? Replace Type Code with State/Strategy ?????????????????????????§Ö???????????????????????????????????????????????§Ö????????????????????????????????????????????????????????????????????????????????????????????????????????

16. Replace Subclass with Fields??????????????

?????????¦·????????????????????????????

????? ??????????

1. Decompose Conditional???????????????

???????????????????????? if??then??else ?????????§Ù??????????????????

if(data.befor(SUMMER_START) || data.after(SUMMER_END))
    charge = quantity * winterRate + winterServiceCharge;
else charge = quantity * summerRate;
if(notSummer(date))
    charge = winterCharge(quantity);
else charge = summerCharge(quantity);

2. Consolidate Conditional Expression???????????????

????????????????????????????

????§»???????????????????????????????????????????????????????

double disabilityAmount(){
    if (seniority < 2) return 0;
    if (monthsDisabled > 12 ) return 0;
    if (isPartTime) return 0;
    // ...
}
double disabilityAmount(){
    if (isNotEligibleForDisability()) return 0;
    // ...
}

3. Consolidate Duplicate Conditional Fragments ????????????????¦²?

???????????????????????????????¦Ä???

???????????????????????????

if (isSpecialDeal()){
    total = price * 0.95;
    send();
} else {
    total = price * 0.98;
    send();
}
if (isSpecialDeal()) {
    total = price * 0.95;
} else {
    total = price * 0.98;
}
send();

4. Remove Control Flag????????????

?????§Ó????????§µ???????????§³?????????????¨¢?

?? break?? ??? return ???????????????

5. Replace Nested Conditional with Guard Clauses ?????????????????????????

?????????????<3F>????????????????????????????????????????????§Ù???????????????ø@????????????????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;
};
double getPayAmount() {
    if (isDead) return deadAmount();
    if (isSeparated) return separatedAmount();
    if (isRetired) return retiredAmount();
    return normalPayAmount();
};

6. Replace Conditional with Polymorphism ???????????????????

???????????????????????????????????§Õ?????§µ??????????????????????????????? Replace Type Code with Subclass ?? Replace Type Code with State/Strategy ????????§ß????

double getSpeed() {
    switch (type) {
        case EUROPEAN:
            return getBaseSpeed();
        case AFRICAN:
            return getBaseSpeed()- getLoadFactor()* numberOfCoconuts;
        case NORWEGIAN_BLUE:
            return isNailed ? 0 : getBaseSpeed(voltage);
    }
    throw new RuntimeException("Should be unreachable");
}

7. Introduce Null Object??????Null????

?? null ??<3F>I? null ?????????????????????????????????????????????§³?

if (customer == null) plan = BillingPlan.basic();
else plan = customer.getPlan();

8. 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();
}

????? ?????????

1. Rename Method????????????

??????????????????????

2. Add Parameter??????????

???????????????????????????

3. Remove Parameter???????????

?? Add Parameter ???????????????????????????

4. Separate Query from Modifier???????????????????????

?????????????????????????????????

??????????????????????????????????????????????????¦Ê??§Ù???????????????????§á??????????¨¢?

getTotalOutstandingAndSetReadyForSummaries();
getTotalOutstanding();
setReadyForSummaries();

5. Parameterize Method??????§Á????????

????????????????????????????????????????????????

???????????????????????§»????????

fivePercentRaise();
tenPercentRaise();
raise(percentage);

6. Replace Parameter with Explicit Methods????????????????????

????????????????????????????????????

???¨°?????????????????????????????????

void setValue(String name, int value){
    if (name.equals("height")){
        height = value;
        return;
    }
    if (name.equals("width")){
        width = value;
        return;
    }
    Assert.shouldNeverReachHere();
}
void setHeight(int arg){
    height = arg;
}
void setWidth(int arg){
    width = arg;
}

7. Preserve Whole Object???????????????

?????????????????????????????????¦Ê???????????????

???????????????

int low = daysTempRange().getLow();
int high = daysTempRange().getHigh();
withinPlan = plan.withinRange(low,high);
withinPlan = plan.withinRange(daysTempRange());

8. Replace Parameter with Methods????????????????

?????????????????????????????????????????????????????????¨°??????????????????????????????

?¨°?????????????????????????????????????????

int basePrice = _quantity * _itemPrice;
discountLevel = getDiscountLevel();
double finalPrice = discountedPrice (basePrice, discountLevel);
int basePrice = _quantity * _itemPrice;
double finalPrice = discountedPrice (basePrice);

9. Introduce Parameter Object?????????????

?§»???????????????????????§»???????? Data Clumps??

??????????????§»??????

10. Remove Setting Method??????????????

???§Ö?????????????????????????????????

???????¦Å?????????????????????????? final??

11. Hide Method???????????

?????????????????§Ò??????¦Ê????????

????????????? private??

12. Replace Constructor with Factory Method ??????????????????????

???????????????????????????????????

?????????<3F>I???????????

13. Encapsulate Downcast?????????????

????????????????????????????????????????downcast????

????????????????????§³?

Object lastReading(){
    return readings.lastElement();
}
Reading lastReading(){
    return (Reading)readings.lastElement();
}

14. Replace Error Code with Exception ???????????????

???????????????????????????????????????

??????????????????????????????????????????

15. Replace Exception with Test??????????????

?????????????????????????????????????????

????????????????¨²???????????î•

double getValueForPeriod(int periodNumber) {
    try {
        return values[periodNumber];
    } catch (ArrayIndexOutOfBoundsException e) {
        return 0;
    }
}
double getValueForPeriod(int periodNumber) {
    if (periodNumber >= values.length) return 0;
    return values[periodNumber];

?????? ??????????

1. Pull Up Field??????????

??????????????????¦±?

???????????????

2. Pull Up Method???????????

??§»????????????????§Ó???????????????

???¨²???????????

3. Pull Up Constructor Body?????????????????

?????????????????§»???????????????<3F>?????????

??????????????????????????????????§Ö???????

class Manager extends Employee...

public Manager(String name, String id, int grade) {
    this.name = name;
    this.id = id;
    this.grade = grade;
}
public Manager(String name, String id, int grade) {
    super(name, id);
    this.grade = grade;
}

4. Push Down Method???????????

?????§Ö??????????????????§Û??

??????????????????§»???????

5. Push Down Field??????????

?????§Ö???????????????????????

????????????????????§»???????

6. Extract Subclass??????????

???§Ö??§»????????§»????????

????????????????????????????????????????§³?

7. Extract Superclass??????????

?????????????????

???????????????????????????????????

8. Extract Interface??????????

??????????????§Ö??????????????????????§Ó????????

???????????????????????????§³?

9. Collapse Hierarchy?????????????

?????????????????????

??????????‰^

10. Form Template Method????????Žï????

?????§»??????????????§»???????????????????????????????????????????????????

????§»??????????????????§µ??????????????????????????????????????????????????????????????(??Ùã????)

11. Replace Inheritance with Delegation ????????????§µ?

??????????¨®??????§Ö?????????????????????§Ø??????????

???????????????????????›‰???????????????????????§Ô??????????????????§Û????

12. Replace Delegation with Inheritance ???????????§µ?

??????????????????§Û???????????????????§Õ????????§Ü?????

???????????????