views:

165

answers:

2

Hi all,

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

+2  A: 

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".

Thr4wn
+1  A: 

Have a read of Chapter 5 of Code Complete 2 book available for preview here: http://www.cc2e.com/ It puts coupling into perspective that is applicable for this question.

Igor Zevaka