Imperative and interrogative methods

When injecting a class, is it better to return a value for methods (interrogative) or just manipulate the class attributes directly in the method (imperative).

For example, I have a class that builds a string to output to a CSV file. I could do it like this:

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 can do it like this:

void extract()
  output += extractHeader()
  output += extractRecords()


string extractHeader()
  // return header string


string extractRecords()
  // return records as string

      

Is this just a matter of personal preference or is there a generally accepted best practice guideline?

Greetings,

Andrew

+2


source to share


2 answers


Separation of concerns is my metric (and it's not hard and fast). This is indeed often associated with saving DRY programs .

Here are two problems I see: logic and usage. The main logic extractRecords

is to start the for loop. If you've ever wanted to use this logic again, your first option now has very logical logic (as opposed to loosly-coupled ) with very specific application / use of this logic.



This is the mindset then why I always lean towards functional programming by default rather than anything stateful or object-oriented if I can.

Also related and possibly there may be another wording of the same thing: "tell, not ask" .

+2


source


Read Code Complete 2 chapter 5 of the book for a preview here: http://www.cc2e.com/ This puts the link in perspective that is applicable to this question.



+1


source







All Articles