I occasionally find myself with several methods in a class that all require the same data (for example, a query object). Typically, there will be one public method with a generic name like parseReport() which in turn delegates work out to several private methods and finally returns the finished product:
public function parseReport( queryObject ) {
queryObject = correctDatesAndTimes( queryObject );
queryObject = sortByCusomter( queryObject );
queryObject = buildHierarchy( queryObject );
return queryObject;
}
private function correctDatesAndTimes( queryObject ) {
// do some stuff
return queryObject;
}
private function sortByCusomter( queryObject ) {
// do some stuff
return queryObject;
}
private function buildHierarchy( queryObject ) {
// do some stuff
return queryObject;
}
So my question is, should my queryObject be a class-level property that all of my methods will reference rather than passing it through as an argument to the method each time it is called?
In a case like this, queryObject should not be a class property. If you look at it, you actually have one big function that is split in several smaller functions. If it was one big function, you wouldn’t make a class property of it.
Data belongs in a class property, when the data is actually a part of the class. Remember that
a class definition is the encapsulating of both data and behavior.