How Do You Define Elegant Code?
programmers.stackexchange.com
programmers.stackexchange.com
So how do we define "simple" and "readable" and what tools do we use, other than years of experience, to achieve simple and readable code. I think that's the more fruitful debate.
Languages differ in their general elegance by virtue of their ability to separate essential complexity from accidental complexity. For instance, C is hobbled in the contest to create truly elegant code, because in its capacity as "portable assembler" you can't ever really ignore memory management, which is in the accidental complexity domain for the vast bulk of problems.
It always makes me think of Hemingway and his ability to never use more words than necessary to say something, and at that, always the words that say it best.
Someone else picked up on the similarity between the Hemingway rules for writing well and parts of the UNIX philosophy: http://unix-simple.blogspot.com/2011/03/unix-and-hemingway.h...
It should be noted that Hemingway's fifth rule "5. Write one page of masterpiece vs. 91 pages of garbage." doesn't infer writing complex sentences, but emphasises not using 10 words when 1 will do.
That said, since true elegance is kind of exceptional, it probably shouldn't be the criteria for acceptable code - "clear, readable and reasonably" is a better standard to have.
> Code I wrote yesterday. (As opposed to "six months ago," which is how I'd define "crap code.")
2. Well-factored at all levels.
For example, "i" is great name for a loop variable. It keeps it from distracting you and it saves space so you can see more of the variables whose names matter.
Compare the number of identifiers in
sum :: [Integer] -> Integer
sum = foldr (+) 0
to int sum (int size, int* array) {
int res;
for (int i = 0, res = 0; i++; i<size)
res += array[i];
return res; }
(Those are not exactly the same function, but I hope you can see them as idiomatic expressions of the same idea.)The key thing to realize is that elegance is necessarily a property of the medium. An elegant solution to a problem written communicated through text will be different than one communicated audibly, as there are different mental facilities available for understanding said code.
[1] I realize Apple's design is not everyone's taste, it's just an example.
If code is written that satisfies these properties AND solves a problem efficiently, then it is elegant for being useful and easy to work with at the same time.