When implementing a class, is it better practice to return a value for methods (interrogative) or to simply manipulate class attributes directly within the method (imperative).
For example, I have a class which builds a string to be output to a CSV file. I might do it this way:
String output = ""
String records[] = //list of record strings
void extract()
extractHeader()
extractRecords()
void extractHeader()
output += "FirstName,LastName,PhoneNumber"
void extractRecords()
For Each record In Records
output += records.toString()
Or, I might do it this way:
void extract()
output += extractHeader()
output += extractRecords()
string extractHeader()
// return header string
string extractRecords()
// return records as string
Is it simply a matter of personal preference, or is there a generally accepted best practice guideline?
Cheers,
Andrew
Separation of Concerns is my metric (and it's not a hard-and-fast one either). This really is often directly related to keeping programs DRY.
Here are the two concerns that I see: logic and usage. The core logic of extractRecords
is to run a for loop. If you ever wanted to re-use that logic again, your first option now has that logic very much coupled (as opposed to loosly-coupled) with a very specific application/usage of that logic.
This thinking is then why I will by default always lean toward functional programing and not anything requiring state or Object-Oriented-ness if I can.
Also related and perhaps maybe just a different wording of the same thing is this article: "tell, don't ask".