以查询取代临时变量

将表达式提炼到一个函数中,并将这个临时变量的所有应用点替换为对新函数的调用。

    public class Class1
    {
        private int _quantity = 12;
        private int _itemPrice = 8;

        public double GetPrice()
        {
            int basePrice = _quantity * _itemPrice;
            double discountFactor;
            if (basePrice > 1000) discountFactor = 0.95;
            else discountFactor = 0.98;
            return basePrice * discountFactor;
        }
    }
View Code
    public class Class2
    {
        private int _quantity = 12;
        private int _itemPrice = 8;

        public double GetPrice()
        {
            return GetBasePrice() * GetDisCountFactor();
        }

        /// <summary>
        /// 提取基础价格
        /// </summary>
        /// <returns></returns>
        private int GetBasePrice()
        {
            return _quantity * _itemPrice;
        }

        /// <summary>
        /// 提取折扣
        /// </summary>
        /// <returns></returns>
        private double GetDisCountFactor()
        {
            if (GetBasePrice() > 1000) return 0.95;
            else return 0.98;
        }
    }
View Code

 

posted @ 2015-07-16 11:23  江境纣州  阅读(103)  评论(0编辑  收藏  举报