vendredi 24 juillet 2015

Using property vs getter/setter in object's own class

Say I have a class A that has another class B as its property.

When class A needs to do modifications to class B, is it better to use the getter method to do modifications or access the property directly to access?

So as an example.

public class Car() {
    private $engine;

    public function __constructor() {
        $this->$engine = new Engine();
    }

    public function getEngine() {
        return $this->engine;
    }

    public function replaceEngine() {
        // Should I use
        $this->engine->change();

        // Or should I use
        $this->getEngine()->change();
    }
}

I am thinking using the getter method so that if I had to stub Class Engine methods, I can mock what getEngine() returns and remove the dependency.

But I'd like to see more opinions on this.

Thank you!

Aucun commentaire:

Enregistrer un commentaire