PHP Tutorial: PHP Design Patterns programming Idioms _php Tutorial

Source: Internet
Author: User
Please read the previous article first

Refactoring

Even the most thoughtful and skilled programmers cannot foresee any nuance in a software project. The problem is always unexpected, the demand may be changing, and the result is that the code is optimized, shared, and replaced.

Refactoring is a common approach: check all your code to find the similarities and the similarities in which you can unify and simplify, making your code easier to maintain and extend. Refactoring also involves exploring whether a design pattern can be applied to this specific problem-and simplifying the solution.

refactoring, simply to rename a property or method, is to compress an existing class in a more complex way. Changing your code so that it fits one or more design patterns is another refactoring--after reading this book, you may be able to achieve it.

There's nothing better than an example to explain refactoring!

Let's consider two simple classes: Cartline and cart. Cartline records the price and quantity of each item in the shopping cart. For example, Cartline may record "Four red polo shirts, each piece of 19.99$". A cart is a container for loading one or more Cartline objects and performing some related calculations, such as the total cost of all items in a shopping cart.

Here's a simple implementation of cartline and cart:

PHP5
Class Cartline {
Public $price = 0;
Public $qty = 0;
}
Class Cart {
Protected $lines = Array ();
Public Function AddLine ($line) {
$this->lines[] = $line;
}
Public Function Calctotal () {
$total = 0;
Add totals for each line
foreach ($this->lines as $line) {
$total + = $line->price * $line->qty;
}
Add sales tax
$total *= 1.07;
return $total;
}
}

The first step in refactoring must have enough tests to cover all of your code. This will ensure that the code you modify does not produce a different result from your original code. By the way, your test code is immutable unless you change the requirements (the results you expect from your code) or if you find an error in your test instance.

Here is an example of testing the cartline and cart, which will not change during refactoring.

function Testcart () {
$line 1 = new Cartline;
$line 1->price = 12; $line 1->qty = 2;
$line 2 = new Cartline;
$line 2->price = 7.5; $line 2->qty = 3;
$line 3 = new Cartline;
$line 3->price = 8.25; $line 3->qty = 1;
$cart = new Cart;
$cart->addline ($line 1);
$cart->addline ($line 2);
$cart->addline ($line 3);
$this->assertequal (
(12*2 + 7.5*3 + 8.25) * 1.07,
$cart->calctotal ());
}

Looking at the code above, you might find that they have some "code smells"--a weird look and look like problematic code--they're like refactoring candidates. (For more information on code smells, see Http://c2.com/cgi/wiki?codesmell). The two most straightforward refactoring candidates are comments and calculations (calculations related to sales tax, etc.). A form of refactoring: the Disjunction function (Extract method) extracts the ugly code from the Cart::calctotal () and replaces it with an appropriate method, which makes the code more concise.

For example, you can add two methods of calculation: LineTotal () and Calcsalestax ():

protected function LineTotal ($line) {
return $line->price * $line->qty;
}
protected function Calcsalestax ($amount) {
return $amount * 0.07;
}

Now you can rewrite the Calctotal () function:


Public Function Calctotal () {
$total = 0;
foreach ($this->lines as $line) {
$total + = $this->linetotal ($line);
}
$total + = $this->calcsalestax ($total);
return $total;
}

The changes so far have been meaningful (at least in the context of this example), and it is helpful to pause and run the code again to verify the results are still correct. Remember, a green success bar shows up! (Translator Note: At the beginning of this chapter, the author mentions that green bars mean that tests are passed.) )

However, the current code still has some place to be picky. One is to access public properties in the new Method LineTotal (). It is obvious that the responsibility for calculating the sum of each line should not belong to the cart class, but should be implemented in the class Cartline.

Re-refactor, adding a new method to the Cartline total () is used to calculate the long-term price of each item in the order.

Public Function Total () {
return $this->price * $this->qty;
}

Then remove the method LineTotal () from the class cart and change the Calctotal () method to use the new Cartline::total () method. Rerun this test and you will still find the result is a green bar.

The new refactoring code is like this:

Class Cartline {
Public $price = 0;
Public $qty = 0;
Public Function Total () {
return $this->price * $this->qty;
}
}
Class Cart {
Protected $lines = Array ();
Public Function AddLine ($line) {
$this->lines[] = $line;
}
Public Function Calctotal () {
$total = 0;
foreach ($this->lines as $line) {
$total + = $line->total ();
}
$total + = $this->calcsalestax ($total);
return $total;
}
protected function Calcsalestax ($amount) {
return $amount * 0.07;
}
}

Now this code no longer needs to comment on each line, because the code itself better describes the functionality of each line. These new methods are better packaged to compute this function and more easily adapt to future changes. (for example, consider a different big sales tax rate). In addition, these classes are more balanced and easier to maintain.

This example is obviously trivial, but hopefully you can infer and envision how to refactor your own code.

When coding, you should have one of two modes: Add new features or refactor code. When adding features, you have to write tests and add code. At the time of refactoring, you have to change your original code and make sure that all the relevant tests are still working correctly.
The main references to refactoring are the refactoring of Martin Fowler's work: improving the design of the original code (refactoring:improving, the "Existing"). To summarize Fowler's book with some concise points, the steps for refactoring are as follows:

Define code that needs refactoring
There are tests that cover all the code
Small steps of work
Run your tests after each step. Coding and testing are fairly repetitive--interpreted languages, such as PHP, are much easier to understand than compiled languages.
Use refactoring to make your code more readable and modifiable.

    • Total 2 Pages:
    • Previous page
    • 1
    • 2
    • Next page

http://www.bkjia.com/PHPjc/363970.html www.bkjia.com true http://www.bkjia.com/PHPjc/363970.html techarticle Please read the previous article refactoring even the most thoughtful and skilled programmers cannot foresee any nuance in a software project. The problem is always unexpected, demand ...

  • Related Article

    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.