Friday, September 30, 2011

Zend Studio Potential Programmer Problems settings For Refactoring

Zend Studio is the best PHP IDE i've ever seen so far. It can warn us for some 'Potential Programmer Problems'. For example, it can warn us if we are using some undefined local variables in our code.  This feature is so valuable when we are refactoring large, long procedure legacy code to smaller functions and OO code. One of the worst coding practice is the large and heavy dependency on global variables. One purpose of refactoring is to break the dependency, so we must be very careful to find out all the dependency and pass them as parameters. Without IDE's help, it is hard for developer himself to find out these dependency from a mess of large long procedure code.

But i find one issue that Zend Studio would not warm me, and it is also very common in code: if we are using a field/property of an undefined object, Zend Studio would not warn us! Check this procedure code example, assuming all the variables/objects/functions are in another file:

echo $name;
echo $information->getEmail();
echo $car->brand;

We have three dependency here, $name, $information, $car. If we want to change the procedure code into a function:

function render()
{
echo $name;
echo $information->getEmail();
echo $car->brand;
}

After we create the function, we ask Zend Studio to check for any Potential Programmer Problems, but Zend Studio would only warn us for 'undefined variable $name' and 'undefined variable $information'. It would not give any warning even $car is also an undefined variable. So to remove the warning, we change our function to

function render($name, $information)
{
echo $name;
echo $information->getEmail();
echo $car->brand;
}

Now we think everything is fine, but actually we still miss one dependency! I've been through this a few times and I feel it is ridiculous that Zend Studio ignores undefined object field. So i check Zend Studios Potential Programmer Problems settings and find this: Undefined field(slow check) : Ignore(default). If i change it to Warning, and ask Zend Studio to check again, this time it can give me a warning for undefined $car->brand as well. However, it is far from perfect yet, cause Zend Studio would give warning for every accessing to object properties, even the properties are really defined in the object.

I think this lesson also tells us one thing: directly accessing an object's fields without using getter methods probably is not a good idea, although this really depends.

No comments: