码迷,mamicode.com
首页 > 其他好文 > 详细

extract method - 提取方法

时间:2016-03-19 11:23:29      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

以获取一个商品的价格为例:如果用户已登录并且是vip,得到vip价,否则正常价;

处理前:

    public function getPrice()
    {
        if (Auth::user()) {
            $userId = Auth::user()->UserID;
            $customerIds = $this->supplier->customers->map(function ($item) {
                return $item->format([‘customer_id‘]);
            })->toArray();
            $customerIds = array_column($customerIds, ‘customer_id‘);
            if (in_array($userId, $customerIds))//如果是vip,获得优惠价
                return self::getVIPPrice();
        }
        return self::getNormalPrice();
    }

处理后:

    public function getPrice()
    {
        if (self::isVIP()) 
                return self::getPartnerPrice();
        return self::getNormalPrice();
    }

    public function isVIP()
    {
        if (Auth::user()) {
            $userId = Auth::user()->UserID;
            $customerIds = $this->supplier->customers->map(function ($item) {
                return $item->format([‘customer_id‘]);
            })->toArray();
            $customerIds = array_column($customerIds, ‘customer_id‘);
            if (in_array($userId, $customerIds))
                return true;
        }
        return false; 

当然,getNormalPrice 和 getPartnerPrice 也是使用了同样的处理

通过这种手法,代码不仅变得易读,而且更容易复用;

 

ps:这种做法很简单,但以前很少用,因为觉得不需要复用;其实主要目的是代码易读,复用倒是其次

extract method - 提取方法

标签:

原文地址:http://www.cnblogs.com/xiaoyaxiaopingguo/p/5294564.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!