Sunday, 6 March 2011

Why I hate setters and getters (especially in PHP).

Whatever you think about object oriented programming (and the phrase ‘Emperors New Clothes’ has been known to pass my lips, although I’m not so dogmatic now.) there’s a point where the syntactic sugar turns to syntactic saccharine -and that point is accessor methods.

Whilst I acknowledge the usefulness of encapsulation and limited visibility I loathe having to write reams of setThis() and getThat() for every blasted variable I want to use. I was going through the Zend Framework tutorial and there’s a simple four field model in there, which generates eight methods, life is too short. The model already exploits __set and __get which allow controlled access to hidden properties, so why not go the whole hog? Here’s a version that calls an accessor method if there is one (you might need to do some extra processing or formatting in it) but otherwise returns the protected variable.

class SomeClass {
    protected $_comment;
    protected $_created;
    protected $_email;
    protected $_id;

    public function __get($name)
       $method = 'get' . $name;
       if (('mapper' == $name)) {
           throw new Exception('Invalid guestbook property');
       if(method_exists($this, $method)) {
           return $this->$method();

       $attr = "_$name";
       if(property_exists($this,$attr)) {
           return $this->$attr;
       throw new Exception('Invalid guestbook property');

Instead of defining a setId method and calling a $someObj->setId(3), you don’t define the method and use $someObj->id = 3.

Personally I’d probably turn this into an abstract base class to support the model classes, leaving the individual classes to supply specific accessor methods if needed -thus getting rid of reams of code that I’d need to maintain. There are times when you wouldn’t use this approach, but for the database mapping example given it’s a bit of a no brainer.

Why especially in PHP? Because it’s not an O.O. language, it’s a scripting language, I like the ability to use O.O. syntax when I think it adds clarity to the program and I like the fact that I don’t have to if I think it makes life harder. Additionally libraries like Zend Framework should make life quicker and easier, it is the point of them after all, and not slower, harder and more verbose.

BTW don’t let this put you off Zend Framework, it’s a good piece of work and I’ve built a few systems using it.

No comments:

Post a Comment