PHPBuilder - Test Driven Development in PHP Page 7



RSS Twitter
Articles Application Architecture

Test Driven Development in PHP - Page 7

by: Marcus Baker
|
February 3, 2004

Now look what has happened to the code...

<?php
class ConfigurationParser {
    function 
parse($lines) {
        
$values = array();
        foreach (
$lines as $line) {
            if (
preg_match('/^\s*#/'$line)) {
                continue;
            }
            if (
preg_match('/^(\w+)\s+(.*)/'$line$matches)) {
                
$values[$matches[1]] = trim($matches[2]);
            }
        }
        return 
$values;
    }
}
?>
That crucial regular expression has gone through several refinements. Even though I was able to code the first version without breaking the tests, I found plenty of bugs when I added blank lines and comments into the mix. Just goes to show what happens if you don't test.
Test then Code then Design
I am happy with the code now. It works. I could improve the clarity a little by placing the regular expression tests into their own named functions, but it doesn't seem worth it. Note that I am still trying to design even at this stage. If the main method were to get longer, I would certainly break it down for the sake of clarity.
Conventional wisdom is on it's head here. By using tests locally we get all the benefits of testing, but get them immediately while we are actually working on the problem. Why wait until you have made loads of mistakes before correcting them? Fix them while they are fresh. Why try to come up with grand designs only to find that they are impractical? If you cannot get there from a working solution, chances are you cannot get there at all.
After two years of coding this way, if I am ever in that interview I will give a different answer now. "Test, code then design" If they ask me what happened to the debug phase I have only one answer...
"What's debugging?"

« Previous Page
1
|
2
|
3
|
4
|
5
|
6
|
7

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Marcus Baker

Comment:



Comment:

(Maximum characters: 1200). You have characters left.