Hacker News new | ask | show | jobs
by z5h 3562 days ago
I believe an important quality is that code should TELL A STORY.

Consider a biography: you could simply collect facts about a person and write them in an arbitrary order and call it a biography. It could be a complete and accurate account, and still be impossible to read or follow.

Well written code is not only complete, but it also guides the reader through the logic.

Consider the difference between:

  statuses = []
  reporter = Reporter.new
  jobs.each do |job|
    statuses << job.complete && !job.error
  end
and

  job_statuses = jobs.map do |job|
    job.complete && !job.error
  end
  job_status_reporter = Reporter.new
In the first case, we see statuses declared. Statuses of what? Not yet clear. And the code that updates it is separated by unrelated code. Also, what will reporter be reporting? In the second case, map and better naming are used making it clear that we are getting a status for every job. Aha! I don't even need to look at the implementation of the do block to understand what's happening.
1 comments

Personally, I would rather see the first version with better variable names.

I always find that map() methods tend to obscure the purpose of the values whereas a simple appears more explicit.

"map", "select", "reduce", "flat_map" and the like make your intention visible upfront. "each" just tells me you're doing "something" with each item.

Not sure how giving less information is preferred over being explicit, but hey, whatever works for you.