PHP Design Patterns Introduction of programming Idioms 1th/3 page _php Tutorial

Source: Internet
Author: User

Many of the programming idioms summarized here are well worth doing for a single chapter, or even a book. You should use this chapter as an Introduction to PHP pattern design using idioms, and look at some of the listed reference books for more in-depth learning.

Test your code

There may be no code idioms that are more important than test code. Good testing can improve the speed of development.

Perhaps at the outset, this maxim will contradict your intuition. You may assert that the test is free of obstructions. In fact, on the contrary, if you run those tests very thoroughly to check the public interface of your software, you may change the execution within your system without changing (or worse, destroying) the original application. Test and verify the accuracy and correctness of your public interface, and let yourself change some of the code's internal work to make sure your software is correct and free of bugs (errors).

Before we talk more about the benefits of testing, let's look at an example. All the test examples in this book use the PHP test framework--simpletest. This test framework can be obtained in http://simpletest.org.

Consider the following code

PHP4
The subject Code
Define (' Tax_rate ', 0.07);
function Calculate_sales_tax ($amount) {
Round ($amount * tax_rate,2);
}
Include Test library
Require_once ' simpletest/unit_tester.php ';
Require_once ' simpletest/reporter.php ';
The test
Class Testingtestcase extends Unittestcase {
function testingtestcase ($name = ") {
$this->unittestcase ($name);
}
function Testsalestax () {
$this->assertequal (7, Calculate_sales_tax (100));
}
}
Run the test
$test = new Testingtestcase (' Testing Unit test ');
$test->run (New Htmlreporter ());

The above code first defines a constant--tax_rate, and a function to calculate the sales tax. The code then contains the prerequisites for using the SimpleTest framework: the monomer test itself and a "reporter" module to display the test results.

The class Testingtestcase inherits from the Unittestcase class of the simpletest framework. By extending Unittestcase, all the methods in class testingtestcase that begin with test will be considered test instances-creating conditions to debug your code and assert the results.

Testingtestcase defines a test, testsalestax (), which contains an assertion function assertequal (). If its first two input parameters are equal, it returns true, otherwise false is returned. (If you want to display assertequal () failure information, you can pass in three parameters like this $this->assertequal (7,calculate_sales_tax), "the sales tax Calculation failed ")).

The last two lines of the code create the entity for this test instance and run it with a htmlreporter. You can access this web page to run this simple test.

Running this test will show the test name, the details of the failure assertion, and a summary bar. (green means success (all assertions are passed), and red implies failure (at least one assertion does not pass))

(Assertion (assertion) is a common debugging method in software development, which is supported in many development languages.) In the implementation, assertion is a statement in the program, which checks a Boolean expression, a correct program must ensure that the value of the Boolean expression is true, if the value is False, the program is already in an incorrect state, The system will give a warning or exit. In general, assertion is used to ensure the most basic and critical correctness of the program. Assertion inspection is usually turned on during development and testing. To improve performance, the assertion check is usually turned off after the software is released. )

Note: (Assertion (assertion) is a common debugging method in software development, which is supported in many development languages. In the implementation, assertion is a statement in the program, which checks a Boolean expression, a correct program must ensure that the value of the Boolean expression is true, if the value is False, the program is already in an incorrect state, The system will give a warning or exit. In general, assertion is used to ensure the most basic and critical correctness of the program. Assertion inspection is usually turned on during development and testing. To improve performance, the assertion check is usually turned off after the software is released. )

The above code has a (intentional) error, so the operation is not passed, the result is as follows:

Calculate_sales_tax () What's wrong with a simple one-line function? You may have noticed that this function does not return a result. The following are the correct functions:

function Calculate_sales_tax ($amount) {
Return round ($amount * tax_rate,2);
}

After modification, run, test pass.

But a simple test does not guarantee that the code is stable. For example, if you change calculate_sales_tax () to function Calculate_sales_tax ($amount) {return 7;}, the code will pass the test, but only if $1 equals 100 is correct. You can add additional test methods to test other static values yourself.

function Testsomemoresalestax () {
$this->assertequal (3.5, Calculate_sales_tax (50));
}

or change the function testsalestax () to verify the second (and third, and so on) values, as shown below

function Testsalestax () {
$this->assertequal (7, Calculate_sales_tax (100));
$this->assertequal (3.5, Calculate_sales_tax (50));
}

A better approach so far is to add a new test: Choose the value to test your code. Specific as follows:

function Testrandomvaluessalestax () {
$amount = rand (500,1000);
$this->asserttrue (defined (' tax_rate '));
$tax = round ($amount *tax_rate*100)/100;
$this->assertequal ($tax, Calculate_sales_tax ($amount));
}

Testrandomvaluessalestax () introduces Method Asserttrue (), if the first variable passed in is equal to Boolean true then Asserttrue () passes. (As with Method Assertequal (), the method Asserttrue () returns a failed message after accepting an optional, additional one). So Testrandomvaluessalestax () first thinks that the constant tax_rate has been defined, and then uses this constant to calculate the randomly selected amount of the tax.

But Testrandomvaluessalestax () also has a problem: it relies heavily on method Calculate_sales_tax (). The test should be independent of the specific implementation details. A better test should only establish a reasonable dividing line. The next test assumes that the sales tax will never exceed 20%.

function Testrandomvaluessalestax () {
$amount = rand (500,1000);
$this->asserttrue (Calculate_sales_tax ($amount) < $amount *0.20);
}

Making sure your code works is the primary purpose of testing, but when testing your code, you should realize that there are additional, relatively minor purposes:

    1. Testing allows you to write code that is easy to test. This makes the code loosely coupled, complex in design, and has good modularity.
    2. Testing gives you a clear understanding of the expected results of running code, allowing you to focus on module design and analysis from the start. Passing the test will also allow you to consider all possible inputs and the corresponding output results.
    3. Testing can quickly understand the purpose of coding. In other words, the test case acts as an "instance" and a "document" function, showing exactly how to construct a class, method, and so on. In this book, I sometimes use a test case to demonstrate the expected functionality of the code. By reading the declaration of a test method, you can clearly understand how the code works. A test instance defines the operation of the code under explicit usage.

Finally, if your test set-the collection of test instances-is very thorough, and when all the tests are passed, you can say that your code is complete. Interestingly, this view also happens to be one of the characteristics of test driven development (testing-driven development).

Test Driven Development (TDD) is also considered to be testing first Coding (pre-coding). Test first coding is a way to take your tests one step ahead: Write your tests before you write any code. You can download it from http://xprogramming.com/xpmag/testFirstGuidelines.htm to a nice, concise summary of TDD, and download it to a good introductory book on strategy--kent Beck's book, "Test Driven development:by Example" (examples of which are all developed in Java, but the readability of the code is good, and the introduction and description of the topic are very good).

Note: Agile Development (Agile development)
Recently, monomer testing-especially mapping-driven development-has been closely linked to agile development methodologies, such as extreme Programming (XP). The focus of extreme programming focuses on rapid, iterative, and functional code to customers, and changes in customer requirements as a necessary part of the development process. Here are some online resources for learning Agile Programming:
Functional Testing
Most of the test examples in this book are used to test the object-facing code, but all forms of programming can be harvested from it. Monolithic test frameworks, such as phpunits and SimpleTest, can also be easily tested for functional functions. For example, the simpletest example above is used to test the Calculate_sales_tax () function. All over the world: put the monomer test case in your library!

I hope that after the discussion above, you will also be driven up-"test infected"! (This term, original in Erich Gamma, please see article for details http://junit.sourceforge.net/doc/testinfected/ Testing.htm, as Gamma writes, you may feel that testing is cumbersome at first, but when you build a vast test set for your program, you will be more confident in your code!

http://www.bkjia.com/PHPjc/318879.html www.bkjia.com true http://www.bkjia.com/PHPjc/318879.html techarticle many of the programming idioms summarized here are well worth doing for a single chapter, or even a book. You should use this chapter as a description of the PHP pattern design using idioms, and ...

  • 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.