Let Your Properties be Properties

There is a coding pattern that I see (and have used) in PHP code that defines generic methods on a class for setting and getting properties.

?
function set($name, $value);
function get($name);
?

Google code search for examples

Some times there are some ancillary methods to deal with unsetting, checking for existence, setting via an array, or dealing with references in PHP 4. They can really clutter up the definition of a class. That’s not good. All this code is fairly standard, too, but it gets duplicated on every class that does this. That’s not good, either.

Oh, I’ll solve this problem by making a base class, some may say. Wrong. This a very feeble reason to spend your one shot at inheritance. Trust me, I know, I’ve done it.

I think the idea is to make the class extensible. But PHP is really ok with just setting new properties on a class.

?
$obj->foo = 'bar';
?

So why not just do this?

Another variation of this pattern is to use setXXX($name, $value) or setYYY($name, $value) methods. This happens alot with “options” or “vars” or “properties.” It also happens on request wrapper classes. To me this looks like there is an object here just begging to get out for each XXX and YYY.

?
$obj->xxx->prop = 'foo';
$obj->yyy->prop = 'foo';
$obj->zzz->prop = 'foo';
?

This eliminates a slew of property manipulation methods and leaves the original class free to implement its true purpose. Methods of the form getXXX($name) and setXXX($name, $value) should be the solution of last resort.

Since I’ve started eliminating these in my own code in favor of direct properties, intermediate objects or __set and __get, I feel I’ve seen nothing but positive results. Try it. You may like it, too. Let your properties be properties.

UPDATE:
From reading the comments, I think there was some confusion about what I meant in this post. I am not talking about using naked properties instead of accessor methods. I’m not talking about accessor methods at all in this post. A specific accessor method, such as

$obj->getFoo()

where the name of the property is part of the method name is very different than

$obj->get('foo');

Where you pass the name of the property as a string parameter. Its only the latter pattern, where the property name is an actual parameter to the method, that I am talking about in this post and that I think should generally be refactored.

Speak Your Mind