PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 6 ■ OBJECTS AND DESIGN

key1:val1
key2:val2


key3:val3


Then I'm told that the tool should support a simple XML format that looks like this:




my key
my val


The parameter file should be read in XML mode if the parameter file ends in .xml. Although this is
not difficult to accommodate, it threatens to make my code much harder to maintain. I really have two
options at this stage. I can check the file extension in the controlling code, or I can test inside my read
and write functions. Here I go for the latter approach:


function readParams( $source ) {
$params = array();
if ( preg_match( "/.xml$/i", $source )) {
// read XML parameters from $source
} else {
// read text parameters from $source
}
return $params;
}


function writeParams( $params, $source ) {
if ( preg_match( "/.xml$/i", $source )) {
// write XML parameters to $source
} else {
// write text parameters to $source
}
}


■Note Illustrative code always involves a difficult balancing act. It needs to be clear enough to make its point,


which often means sacrificing error checking and fitness for its ostensible purpose. In other words, the example


here is really intended to illustrate issues of design and duplication rather than the best way to parse and write file


data. For this reason, I omit implementation where it is not relevant to the issue at hand.


As you can see, I have had to use the test for the XML extension in each of the functions. It is this
repetition that might cause us problems down the line. If I were to be asked to include yet another
parameter format, I would need to remember to keep the readParams() and writeParams() functions in
line with one another.

Free download pdf