Today I had a dicussion with a colleague.
I tend to believe that a value in a property should be a meaningful part of the state of an object at any given time. This automatically almost always makes the constructor fully responsible for the initial assignment of all the properties in a class. Other methods may subsequently change the state to another valid state, but it is usually not their task to initialize values on class properties.
My colleague believes that class properties may also be useful to increase readability by decreasing the parameter count of internal private functions. Class properties are then used as temporary variables, potentially used by multiple private functions.
My way (php code example - I left out the private method declarations):
class Example {
private $valueFromConstructor;
public function __construct($valueFromConstructor) {
$this->valueFromConstructor = $valueFromConstructor;
}
public function doSomething() {
$value1 = $this->computeValue1();
$value2 = $this->computeValue2();
$value3 = $this->computeValue3WithValue1AndValue2($value1, $value2);
$value4 = $this->computeValue4WithValue1AndValue3($value1, $value3);
return $this->doSomethingWithValue4($value4);
}
}
Colleague's way
class Example {
private $valueFromConstructor;
private $value1;
private $value2;
private $value3;
private $value4;
public function __construct($valueFromConstructor) {
$this->valueFromConstructor = $valueFromConstructor;
}
public function doSomething() {
$this->computeValue1();
$this->computeValue2();
$this->computeValue3WithValue1AndValue2();
$this->computeValue4WithValue1AndValue3();
$this->doSomethingWithValue4();
return $this->value4;
}
}
To me, there is a pretty clear distinction as to when one should assign a value to a class property and when values should be parameterized. I do not see them as immediate alternatives to each other. It is confusing to me to see variables that live longer than the execution of the method to which they belong. The necessity for these variables to exist as class properties when they are used in private methods seems to create a temporal coupling.
Do any guidelines exist on this matter? Or is it a matter of style? And does it matter if the object does not live very long and has only few public methods? To clarify: as seen from the outside, the class works correctly.