Saturday, October 4, 2008

singleton, static, defensive programming

below quoted from PHP 5 CMS Framkwork Development.
"The singleton appears repeatedly, especially for the handler objects described later. In theory, handlers could be implemented as class methods, but in PHP5 a class is not itself a first class object and it is more effective to use singleton objects. Other objects are naturally singletons, such as the session object, since PHP5 handles only a single request at a time.

They(signleton classes) arise naturally in designing systems where a range of related services is needed. Sometimes, this is done by creating a class that consists only of static methods. But that is both inefficient, and inflexible. Dealing with an instance of a class is generally more efficient than dealing with static methods, and in many cases a singleton object will know quite a lot of potentially complex information. Since a class of this kind is a manager or handler, there should never be a need for more than a single instance of the class, hence the name singleton. "

Friday when i was looking into the codes of our system, i found piece of codes like below:

public function f($keyword, $country)
{
if ($keyword === 'a') {
$keyarray = $config[$country]['a'];
} elseif ($keyword == 'b') {
$keyarray = $config[$country]['b'];
}

foreach($keyarray as $key) {
......
}
}

What is the problem of the above code? First, $keyarray is not initialised! if $keyword is neither 'a' nor 'b', the program will still try to run the next codes and throw a notice: Undefined variable and a warning 'Warning: Invalid argument supplied for foreach()'.

In the above case, at lease we should put one more 'else{$keyarray = array()}' at the end to ensure $keyarray is initialised. It is better to check with isset to make sure $config is set up correctly. However, since many php programmers don't do this in practice.

My friend who was working in GE told me that none of PHP programmers are professionals, or all PHP programmers are amateur because PHP is designed for amateur to develop simple database driven website quickly. However, since PHP plays increasingly important role in web app development, enterprises tends to employ PHP developers for their web applications. As usual, they define the criteria like 3-5 years experiences, etc, etc. They never thought that PHP programmers with 3,5 years experiences means they don't have any formal, scientific software development methodology. Probably they know more detail of PHP language. They know more functions in PHP manual. But they don't have OOP in mind. They don't have design patterns in mind. They don't have refactoring in mind.

No comments: