zoukankan      html  css  js  c++  java
  • 重构22-Break Method(重构方法)

    这个重构是一种元重构(meta-refactoring),它只是不停地使用提取方法重构,直到将一个大的方法分解成若干个小的方法。下面的例子有点做作,AcceptPayment方法没有丰富的功能。因此为了使其更接近真实场景,我们只能假设该方法中包含了其他大量的辅助代码。 下面的AcceptPayment方法可以被划分为多个单独的方法。

    public class CashRegister {
    public CashRegister() {
    Tax = 0.06d;
    }
    private Double Tax;
    public void AcceptPayment(Customer customer, List<Product> products,Double payment) {
    Double subTotal = 0d;
    for(Product product : products) {
    subTotal += product.Price;
    }
    for(Product product : products) {
    subTotal -= product.AvailableDiscounts;
    }
    Double grandTotal = subTotal * Tax;
    customer.DeductFromAccountBalance(grandTotal);
    }
    }
    public class Customer {
    public void DeductFromAccountBalance(Double amount) {
    // deduct from balance
    }
    }
    public class Product {
    public Double Price;
    public Double AvailableDiscounts;
    }
    如您所见,AcceptPayment方法包含多个功能,可以被分解为多个子方法。因此我们
    多次使用提取方法重构,结果如下: 
    public class CashRegister {
    public CashRegister() {
    Tax = 0.06d;
    }
    private Double Tax;
    private List<Product> Products;
    public void AcceptPayment(Customer customer, List<Product> products, Double payment) {
    Double subTotal = CalculateSubtotal();
    subTotal = SubtractDiscounts(subTotal);
    Double grandTotal = AddTax(subTotal);
    SubtractFromCustomerBalance(customer, grandTotal);
    }
    private void SubtractFromCustomerBalance(Customer customer, Double grandTotal) {
    customer.DeductFromAccountBalance(grandTotal);
    }
    private Double AddTax(Double subTotal) {
    return subTotal * Tax;
    }
    private Double SubtractDiscounts(Double subTotal) {
    for(Product product : Products){
    subTotal -= product.AvailableDiscounts;
    }
    return subTotal;
    }
    private Double CalculateSubtotal() {
    Double subTotal = 0d;
    for(Product product : Products){
    subTotal += product.Price;
    }
    return subTotal;
    }
    }
    public class Customer {
    public void DeductFromAccountBalance(Double amount) {
    // deduct from balance
    }
    }
    public class Product {
    public Double Price;
    public Double AvailableDiscounts;
    }
     
     





  • 相关阅读:
    poj 2533 (LIS 最长递增子序列)
    zoj 2432(最长递增上升子序列)
    hdu 1159(最长公共子序列)
    2013 腾讯马拉松初赛 第1场
    poj 1458(最长公共子序列)
    hdu 4524(水题)
    hdu 4514(自己添加栈—— #pragma comment(linker, "/STACK:102400000,102400000" ))
    MVC3安装报错解决方案
    C# 用7Z 压缩 ZIP
    获得字符串中开始和结束字符串中间得值
  • 原文地址:https://www.cnblogs.com/jgig11/p/5786361.html
Copyright © 2011-2022 走看看