In celebration of my achieving 10,000 “reputation” on Stack Overflow, I’m re-posting one of my questions from there that was (as I had expected) deleted after being live for about 5 hours. In that time, I never really got a satisfactory answer, so if anyone wants to offer one in the comments, that would be great!
Here is the post:
What exactly is “elegant” code in R?
I almost exclusively follow the R tag—it’s my current “playground”—and I have been noticing many questions phrased along the way of “what is an elegant way to do XYZ” or answers in the form of “this may not be the most elegant solution, but it does what you want.” (I know many is subjective, but search the R tag for elegant, and you will find at least one question every other day or so with the word in it.)
My “question” is, what exactly is elegant code?
- Code that is easily readable?
- Code that does everything in one line (I see a lot of congratulations for these so-called “one-liners”)?
- Code that is faster?
- Something totally different?
I’ve seen in some documents (for example A (Not So) Short Introduction to S4, Section 1.6) what I feel are much more understandable terms for describing code: good, clean, bad, dangerous, dirty…. As I write this, @Andrie is schooling (politely–“Summer of Love” fashion) a new user on how to “clean your code and make life easier in the long term” (emphasis added). And, what comes to mind when I try to write code are things like consistency, readability, efficiency, not producing unexpected output, not breaking other functions. These descriptions for code seem to fit with such terms, but not necessarily with what I would call elegant.
I’m also often confused when an answerer posts what I consider an excellent answer, perhaps incrementally building towards the desired output, but modestly states it is not elegant. If the answer does exactly what is expected to do, isn’t that the whole point of the code?
Some further background
It is a truth universally acknowledged that R’s base reshape command is speedy and powerful but has miserable syntax.
The word elegant was not used here, but this is an example of where I might use it. Ari was trying to make an incredibly useful function easier to use by making the user input more consistent, much like some of Hadley Wickham’s packages are wrappers around base R functions, often combining common steps that a user might go through. The result of these new functions is not always more efficient, but the code that is written is often more easy to decipher, and thus provide what I might call a more elegant approach.
(Note: I fully expect that this question would be closed as “off topic”, “not a real question”, or “not constructive”, since it is not directly programming related; but while it stays open, hopefully there are some helpful answers.)