Extract Method-Extraction methods

Source: Internet
Author: User

Take the price of a commodity as an example: if the user is logged in and is VIP, get VIP price, otherwise the normal price;

Before processing:

     Public functionGetPrice () {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))//if it is VIP, get preferential price                returnSelf::Getvipprice (); }        returnSelf::Getnormalprice (); }

After processing:

     Public functionGetPrice () {if(Self::ISVIP ())returnSelf::Getpartnerprice (); returnSelf::Getnormalprice (); }     Public functionIsvip () {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;

Of course,Getnormalprice and Getpartnerprice also use the same treatment ;

In this way, the code is not only easy to read, but also easier to reuse;

PS: This is very simple, but seldom used before, because it is not necessary to reuse, in fact, the main purpose of the code is easy to read, reuse is the second

Extract Method-Extraction methods

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.