Hacker News new | ask | show | jobs
by mmastrac 3752 days ago
I'd suggest an alternate approach: add enough commentary to your one-liners so that a reader can parse that instead of the statement. Bugs can hide in the expanded versions of code just as easily. By offering the reader of the code a clear summary of the next one-liner, they can quickly scan it if they are trying to find a bug nearby and decide if it is potentially the culprit.

On top of that, consider making every bit of clever code a reusable library snippet instead. If it becomes part of the vocabulary of your codebase it'll be easier for others to understand it by looking at call sites.

eg:

  # Capitalize the first letter of every word
  @sentence = @sentence.split(' ').map!{|x| x = x[0..0].upcase << x[1..-1]}.join(' ')
4 comments

I agree. Someone's "darling" code might be a truly innovative or unique way of solving a problem, and providing enough commentary should help avoid the problems the author warns about.
It's amazing, their whole complaint is solved by proper software development practices - Comment your code.
Code that's clear enough not to need a comment is better than code that has a comment. Comments can be outdated or mistaken and they consume screen real estate.
You still need to document intent. No code is self documenting.
In some cases, naming may be sufficient to communicate intent.
To be fair: What is proper practice, is far from what is common practice
Not to mention it may be a performance optimization.
Which is a good reason, if that optimization is needed.
I'd wrap it in a function called capitalizeWords and be done for the day. I also had 0 problem understanding the meaning of this line. If your code base is consistently made of small functions that look like this I actually don't see a major readability issue. (The article remains very valid)
Why use "map!"? you're already working on a disposable copy of your data, there's no need to mandate "in place".

Could this be done with one gsub regex?

why use "x = x[0..0].upcase << x[1..-1]", instead of "x[0]=x[0].upcase; x" ?

And why not use the already-written "titleize" function, which capitalizes the first letter of each word?

Frankly, I think your darling needs to be put out of its misery. :-)

> already-written "titleize" function

Which is a function provided by ActiveSupport. It's not part of Ruby itself.

I haven't written a single line of Ruby in my life and I guessed that it would do that. While I 100% agree to make code readable, maybe this darling was a bad example. And yes, a comment would help with the problem of not understanding it.