views:

61

answers:

2

Hi,

I'm wondering when private/protected methods should work on the class it's variables (like $this->_results) and when such methods should be used as if they were functions (like $this->_method($results)). Examples below:

Work on class properties

<?php

class TestA
{
    protected $_results;

    public function getResults()
    {
        $this->_results = getFromWebservice();
        $this->_filterResults();
    }

    protected function _filterResults()
    {
        $this->_results = doMagic($this->_results);
    }
}

Work "as function"

<?php

class TestB
{
    protected $_results;

    public function getResults()
    {
        $results = getFromWebservice();
        $this->_results = $this->_filterResults($results);
    }

    protected function _filterResults($results)
    {
        return doMagic($results);
    }
}

Any help would be greatly appreciated.

Adriaan

+3  A: 

As long as you are sure, that you need to maintain only one results variable per instance always use the first version (which works on the class property). That's one of the purposes of using classes: to have shared variables.

You may actually consider the class properties as arguments to your methods, which are implicitly specified. (If you're programming in C++ you know that at least there it really is that way. For example you can specify that you are not going to change a class property by putting a const after the method arguments.)

nikic
+1  A: 

Using exclusively the example you've given there is no difference whatsoever between the two methodologies. You could extrapolate to find differences, but they are not actually present.

My guess is that you are trying to implement a class without designing it first. Because the picture is not complete, there are no obvious reasons to choose one methodology over the other.

When you start to flesh out exactly what you want to do, you will likely discover that method one binds the filtering routine to the class, whereas method two encourages the routine to be separated from the class.

Method one

  • Works on side-effects
  • Overwrites original data
  • Cannot be reused on other data

Method two

  • Whereas method one could be easily modified to remember that it has already done the filtering, method two will struggle especially when trying to keep it abstracted
  • Because of its abstraction, filterResults is no longer a logical name but rather something like applyXyzFilter, which is hard to justify keeping in the class
erisco