Bogdan Burym
Bogdan Burym

Reputation: 5512

Should I use public setter to set private attribute value inside class?

Lets assume I have a class Test, which has got a private attribute called $_list, and a public setter.
Public setter is used to set the attribute value from the outside.

class Test {
    private $_list;

    public function getList() {
        return $this->_list;
    }

    public function setList($list) {
        $this->_list = $list;
    }

    public function initialize() {
        $list = array();

        /* ... Some code that fills the $list with values etc. ... */

        // 1) Set value directly
        $this->_list = $list;

        // 2) Use public setter
        $this->setList($list);
    }
}

The question is - do I need to use public setter to set private attribute value inside class?
Which way is are better - #1 or #2? And why?
Which way do you prefer? I would like to see a complete answer with the explaination of advantages and disadvantages of each way.

Thanks.

Upvotes: 3

Views: 668

Answers (1)

gaborsch
gaborsch

Reputation: 15758

As it was written above, both are acceptable, but the correct answer is: Rather use the direct attribute access, but sometimes you better use the setters.

Number 1, (property access) Pros:

  • Easily readable and slighty faster
  • Gives you the approach that this is an simple attribute of the object

Number 2, (setter) Pros:

  • You can do custom action on setting the attribute (e.g. initialize other attributes, caches, or call a method on the parameter object)
  • You treat the attribute as a sub-element of the class, which may have own logic implemented.

I think that proposing that there is no logic behind using a variable is more important. If it is simple, make it look simple. If it's not, you can still use setters.

You could also ask the same about getters versus property access, the above applies as well.

Upvotes: 1

Related Questions