Drink Remodeling Series [2]--extraction method, extraction Method Object

Source: Internet
Author: User

Objective

"Art comes from Life"-code also comes from life, and some of your habits in life may well be reflected in the code.
When implementing more complex functions, because it contains a series of logic, we tend to write a "big method" to achieve.
In order to make the project easier to maintain, and to enhance the readability of the code, it is necessary to organize the logic of "big method" and extract the Scattered "small method".
This is the two kinds of refactoring strategy to be discussed in this paper: Extracting method and extracting method object.

How to quickly find the book you want to read?

In life, I am a more casual person, usually also bought a lot of books to see.
My bookcase is not big enough, and it is full of books, whenever I read a book, I am too lazy to spend some time to tidy up, thinking about the future to organize these books, so I usually put these books into a large box inside.
Every time I have to reread some books, I would like to turn this box upside down, after spending "Dickens", I finally found the book to read.
Then I put back the other books that I had turned out.

Every time I find a book, I always go through hardships, make the floor of the house is a mess, still have to be daughter-in-law son scold a meal.

The box is so big, all the books are put in a box, a whole box of books are not classified, some books are hidden deep, it is really inconvenient to find books.

Later, I thought of a method-recently express small brother delivery packaging carton is still at home, these boxes will not be very large, but the book should be more than enough, why not put these boxes used up?
So I picked up a few small cartons of the right size and made a mark for each carton with a signature pen.

1th Carton, the book related to ASP.
2nd Carton, the Book of Architecture design related
3rd carton, installation Management related books
...
n Carton, travel-related books

Since the classification of the books into the various small cartons, through the mark I can always quickly find the book I want to read, daughter-in-law son no longer for this matter don't scold me.

In life, many readers may have encountered such problems, why is it so difficult to find a thing?

The habits of life are reflected in the programming. When writing a method, sometimes due to lazy psychology and procrastination habits, we may say to ourselves: "This method has time to organize it, the first to complete the next function."
The result is to hold this mentality, this method has been to the project on-line has not been collated.
During the maintenance of the project, the need to modify this method, read again to this method, we cannot help complaining: "I rub, this method how so long, this is who wrote, I give him 666!" Oh, no, it's like I wrote it myself! ”
Extraction method

When a method contains all the logic to implement a function, not only will the method look bloated (poor readability), it will also cause future maintenance problems, and each change will keep you on the ice, and the larger may bring new bugs. This does not meet our "future interests", and we can use the refactoring strategy of the extraction method to circumvent this problem.

Here is my definition of the extraction method:

If a method contains multiple logic, we should extract each logic and make sure that each method does only one thing.

Represents the refactoring strategy (blue is refactored before red is refactored).

Example before refactoring

The following code defines a receipt class that describes the revenue information and calculates the total revenue.

Using System.collections.generic;namespace extractmethod.before{public    class Receipt    {        private IList <decimal> discounts {get; set;}        Private ilist<decimal> itemtotals {get; set;}        Public decimal calculategrandtotal ()        {            decimal subTotal = 0m;            Calculate SubTotal            foreach (decimal itemtotal in itemtotals)                subTotal + = itemtotal;            Calculate Discount            if (Discounts.count > 0)            {                foreach (decimal discount in discounts)                {                    SubTotal-= discount;                }            }            Calculates the tax amount of            decimal taxation = subtotal*0.065m;            SubTotal + = tax;            return subTotal;}}    }

The Calculategrandtotal () method contains multiple logic: Calculates the subtotal, calculates the discount, calculates the tax amount.
The logic is relatively independent, and we can extract it and refactor it into 3 methods.

After refactoring

After refactoring, the Calculategrandtotal () method contains only the logic to invoke the individual sub-methods, which has been streamlined and improved in readability.

Using system.collections.generic;using system.linq;namespace extractmethod.after{public class Receipt {Priv        Ate ilist<decimal> discounts {get; set;}        Private ilist<decimal> itemtotals {get; set;}            Public decimal calculategrandtotal () {//calculate subTotal decimal subTotal = Calculatesubtotal ();            Calculate Discount subTotal = calculatediscounts (subTotal);            Calculated Tax SubTotal = Calculatetax (subTotal);        return subTotal;        }//Calculates subtotal private decimal calculatesubtotal () {return itemtotals.sum (); }//Calculate Discount Private decimal calculatediscounts (decimal subTotal) {if (Discounts.count >            0) {subTotal = Discounts.aggregate (SubTotal, (current, discount) = Current-discount);        } return subTotal; }//Calculate Tax Amount Private decimal calculatetax (decimalsubTotal) {Decimal tax = subTotal * 0.065m;            SubTotal + = tax;        return subTotal; }    }}
Two-time refactoring

I think that's still not enough. The "semantics" of the Calculategrandtotal () method is to calculate the total revenue.
But the above code does not allow us to quickly know this semantics, we need 3 sub-methods to understand this semantics.

"Total calculated income" essentially has a formula, namely "total revenue = (sum of each sub-total-discount sum) * (1 + tax rate)", the right side of the formula is a simple three-item.
This method does not reflect the concept of "formula", in order to make this code oo taste more intense.
We refactor it again, extracting each item on the right side of the formula as a property, and the calculation logic for each item is represented by a get property.

using System.Collections.Generic; Using System.linq;namespace extractmethod.after{public class Receipt2 {private ilist<decimal> Discoun        TS {get; set;}        Private ilist<decimal> itemtotals {get; set;} Public decimal calculategrandtotal () {//Total revenue = (sum of each sub-income-discount sum) * (1 + tax rate) Decimal Grandtot            Al = (subtotal-totaldiscounts) * (1 + taxrate);        return grandtotal;        }//Get SubTotal private decimal SubTotal {get {return itemtotals.sum ();}        }//Get totaldiscounts private decimal totaldiscounts {get {return discounts.sum ();}        }//Get TaxRate Private decimal TaxRate {get {return 0.065m;} }    }}

Re-refactoring the code after that is not at a glance?
Some people here may be puzzled, this article is not about the extraction method? Now how to extract attributes?
In C #, the nature of a property is the get, set method of a field, so it is still considered an extraction method.

Note that in all cases, it is appropriate to use the Extract property instead of the extraction method. My suggestion is that when the extracted method is less logical, you can use the Extract attribute instead. When the extraction method is more logical, it can be confusing to use the extraction attribute instead. Because the property is to describe the characteristics of the object, the process of describing the feature is more complex, it is difficult to understand, we should keep it simple!

Drink Remodeling Series [2]--extraction method, extraction Method Object

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.