tags:

views:

answers:

I see a lot of lip service and talk about the most "elegant" way to do this or that. I think if you spend enough time programming you begin to obtain a sort of intuitive feel for what it is we call "elegance". But I'm curious. Even if we can look at a bit of code, and say instinctively "That's elegant", or "That's messy", I wonder if any of us really understands what that means. Is there a precise definition for this "elegance" we keep referring to? If there is, what is it?

Now, what I mean by a precise definition, is a series of statements which can be used to derive questions about a peice of code, or a program as a whole, and determine objectively, or as objectively as possible, whether that code is "elegant" or not.

May I assert, that perhaps no such definition exists, and it's all just personal preference. In this case, I ask you a slightly different question: Is there a better word for "elegance", or a better set of attributes to use for judging code quality that is perhaps more objective than merely appealing to individual intuition and taste?

Perhaps code quality is a matter of taste, and the answer to both of my questions is "no". But I can't help but feel that we could be doing better than just expressing wishy washy feelings about our code quality. For example, user interface design is something that to a broad range of people looks for all the world like a field of study that oughtta be 100% subjective matter of taste. But this is shockingly and brutally not the case, and there are in fact many objective measures that can be applied to a user interface to determine its quality. A series of tests could be written to give a definitive and repeatable score to user interface quality. (See GOMS, for instance).

Now, okay. is Elegance simply "code quality" or is it something more? Is it something that can be measured? Or is it a matter of taste? Does our profession have room for taste? Maybe I'm asking the wrong questions altogether. Help me out here.

Bonus Round

If there is such a thing as elegance in code, and that concept is useful, do you think that justifies classifying the field of programming as an "Art" capital A, or merely a "craft". Or is it just an engineering field populated by a bunch of wishful thinking humans? Consider this question in the light of your thoughts about the elegance question.

Please note that there is a distinction between code which is considered "art" in itself, and code that was written merely in the service of creating an artful program. When I ask this question, I ask if the code itself justifies calling programming an art.

Bounty Note

I liked the answers to this question so much, I think I'd like to make a photographic essay book from it. Released as a free PDF, and published on some kind of on demand printing service of course, such as "zazz" or "tiggle" or "printley" or something . I'd like some more answers, please!

Is there a better word for "elegance" <-- I don't think I'm answering your question exactly but I'll go with "Readable and Maintainable". If code can be read and understood then I won't have to ask people what the code is doing and then making it more maintainable.

No, there almost certainly isn't a definable definition of 'elegant' code, and more than there is of 'good' code or 'understandable' code. However that doesn't mean that the concept is useless or 'just a matter of personal preference'.

There may be no precise definition of 'good' music - whether Beethoven is better than Mozart is a matter of preference. However Beethoven and Mozart are both better than a kid beating a tin drum (unless you are the parents - we'll consider that an outlier).

So while the concept isn't definable, most people do actually agree on it, to a great extent. Maybe you should be looking for helps with the concept rather than a definition.

BONUS ANSWER

No programming is not an art just because there are some incompletely-defined concepts in it. Art also has some defined concepts, such as colour, but that doesn't make it a science. You might also like to think about just how well-defined the concept of a mathematical 'proof' is.

Elegant \El"e*gant\, a. 1. Very
choice, and hence, pleasing to good
taste; characterized by grace,
propriety, and refinement, and the
absence of every thing offensive;
exciting admiration and approbation by
symmetry, completeness, freedom from
blemish, and the like; graceful;
tasteful and highly attractive; as,
elegant manners; elegant style of
composition; an elegant speaker; an
elegant structure.

Of course this is, to some extent, subjective. Taste and preference surely come into play, but I think that "elegant" is a very appropriate word to describe good code, and elegance certainly is a virtue in programming.

"Elegant" is a good word choice because it implies a sense of aesthetics. Deciding what is elegant and what isn't is an aesthetic judgement in code just as in other fields. It is subjective. What's elegant to one programmer might not be to another.

To expand the definition a little, you could say elegant code is code that gets something non-trivial done in a way that is simple. I don't think anyone disagrees on the non-trivial part, it's the simplicity that is the bugbear. Some people think simple means "as terse as possible", other people think it is "as easy to understand as possible", and many opt for some intersection of the two.

EDIT: In response to the "bonus" question about whether code, in itself, justifies calling programming an art as opposed to "merely" a craft. This, too, is subjective, and my short answer is "no."

Programming-as-art involves the entire process. Architecture, design, construction, even testing. That doesn't mean that code in itself can't possess beauty, but the means of execution and expression of that beauty are what make it artful. Asking whether code in itself makes programming an art is like asking whether prints of the great masters in themselves make offset printing an art. The result may be beautiful, but if the process by which it is achieved is mechanical and lifeless, devoid of expression, that process is not art.

On the other hand, tough requirements handled by a great architects and programmers who design and implement a system that not only gets the job done, but gets it done with elegance and a sense of self-expression, with all the geeky passion of a Picard vs. Kirk debate, I would call that art. Not the code in itself, the entire effort. The code could be said to be a work of art, but taken alone it does not make programming an art.

I'm fascinated by the concept of elegance. My particular view is that elegant code is not only simple, but well suited to its language. I think that an elegant program keeps to its languages paradigm completely.

For example, there is no way to write quicksort elegantly in Scheme (or lisp, or haskell, etc) while it can be done quite elegantly in C.

No. First of all, most languages are multi-paradigm. Second, I heartily disagree with your second statement. Especially Lisp, which is a "programmable programming language", can be seamlessly extended to express anything you might want in any way imaginable.

most languages are "impure" this is true. I find programming in pure languages to be more elegant. For this reason, I prefer Scheme to Lisp, Java to C++, Smalltalk to Java, and just about everything to Perl...

Quicksort in Haskell: `qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)` -- the result is the sorted list of all elements in the list xs less than the element x followed by the element x followed by the sorted list of all elements in the list xs larger than the element x. Does it get much more crystal clear than that?

Elegant code is beautiful, like a good haiku or a powerful poem. It's clever, without being arrogant or amused with itself. It's clear, without being obvious. There's nothing to take away and there's nothing to add. Elegant code is truth in the most Keatsean sense of the word.

Elegant code is like reading a good book that it is easy to read and well organized. Main sub-routines read like a table of contents to other functions and classes. Functional areas are broken into logical partitions like chapters. In elegant code, you will not find multi-page sub-routines or logic that is repeated in many places.

Elegant code is obviously correct (as opposed to code which is not obviously incorrect). It's clear where and how to change elegant code if the requirements change. It generally is short, and always to the point.

Of exceptionally high quality and
distinction, harmoniously balanced and
with all virtues intact; possessing a
certain lightness and flair.

It implies that elegant code is perceived as a simple clear concise solution that does more than expected.

Characteristic property is the "Aha!" moment when you grok the solution. A lack of experience in the concrete techniques used in the solution could prevent the "Aha!" moment from happening thus the solution won't be perceived as elegant.

Essentially, you strive first for absolute simplicity while still getting whatever it is you're trying to do done. You then make it nice and readable while preserving simplicity as much as possible. At the risk of sounding cliché, remember that programmer time is much more expensive than computer time, and besides, a smart compiler should come up with the most efficient way to implement your code anyway; keeping this in mind, write code for humans to read, and let the compiler worry about extra optimization.

An example of this is using bit shifts to perform multiplication with powers of 2. It will only serve to confuse people, not impress them with your leethaxxor skills.

Re the bit-shift example, it also fails to be versatile and reusable, since it only works for powers of 2. Try explaining to your boss why you have to rearchitect the code the day he wants to multiply by 3.

Writing code can definitely be an art in the same way building furniture can be. Of course, it can also be fully functional with no consideration of the aesthetic. Elegant code is both pleasing to the reader and functional. (And the same is true of an elegant chair.)

And of course, you can have an aesthetically pleasing chair that doesn't work and that would be purely art. There isn't usually an analog to pure art in code, because nonfunctional is not aesthetically pleasing to a programmer. (Though if you see code on a TV show or in a movie, it is purely "art" in some sense.)

What about code that does something, but it just isn't useful? Such as, for instance, a program that draws a turtle on the screen that says "Hi there!". It's functional, in the sense that it's a valid program that causes a percievable effect. On the other hand it's not useful. Is that pure "Art"?

Every time I hear the word Elegant these days, I cringe. I understand the concept and all, but the applications I've seen almost always trade obvious, explicit code for short, tricky patterns that aren't as well known.

I'm not disagreeing with the concept, but as used it's an excuse to write small snips of "Fun" code that are harder to decrypt than their more verbose counterparts.

Also I have no problem with fun, but if it's harder for the next guy to pick up--even slightly harder, I'd have a problem with it.

Everything we do as engineers should be targeted at making the thing you do once (writing the code) contain all the difficulty and complexity--that should be the part that takes the most time in other words. The things that are done repeatedly (read, analyze, debug, rewrite) should be the things you try to optimize.

Often brevity is extremely advantageous, but to change:

if(done) return true;

to

return true if done

isn't shorter, it doesn't add to the functionality--it SEEMS better when you write it because it lets you express yourself differently...

But it's different it's a new syntax--something that, regardless of coolness has to be learned and understood as a secondary syntax by all who want to understand that language. (Also, you don't see that it's a branch by scanning the left side of your code, something you can always do in C-like languages formatted in a traditional manner)

When you accept the solid fact of additional syntax being a minus, this just doesn't have any justification--so people that like the "Fun" of it call it elegant.

Just for an example, I went and googled elegant code and grabbed the first example I found:

skanky code:

if(0 == x) {
y = 0;
} else {
y = 1;
}

Elegant Code

y = (0 <x);

Again, I totally get it, I use this construct all the time. It IS more elegant (not my example, if you want to congratulate/complaint to the author, Google it yourself).

Also, I guarantee that someone down the line, someone you may be relying on to get his task done on time, will pause 20 seconds on the second where nobody would ever question the first.

I know everyone wants to argue this, they always do, but be serious. NOBODY will have a problem with that first example, SOMEBODY will stumble on the second that would not on the first. (I know because I've described the second construct to people before).

Also the argument that they should know what they are doing is irrelevant, they don't. I've talked to them and I know they don't, and no amount of "should" fixes that--yet I have no direct control over their employment or my working with them. (and the "You should quit" argument is not a good one either, they are everywhere--except my current company, but we work on their code)

The second example is definitely worse and *unnecessarily* compressed. It's not easy to read and therefore not elegant. Adding complexity to a simple problem is not elegant.

2009-02-23 03:43:41

Not to mention the fact that the "elegant" solution changes the condition being tested. "Elegant" code of the sort in this example is a really good way to introduce subtle logic bugs into the codebase ;-)

Yeah, I noticed that the result was different, I figured it relied on an assumption that x and y are both 0 or 1, or something along those lines, but looking at it I guess he meant (0 != x) which would work fine. Still--this is the crap done in the name of elegance.. gakk

@MarkJ: Malarky. Elegant code is a good thing, by definition. The question is "what is elegant?" I would agree with pfunk that the "skanky code", while not "elegant", perhaps, is better than the alternative. Sounds like we just need good definitions...which is what the point of the question is.

@andrea As I said, some people will, but I bet the difference for you was a matter of seconds. When it comes to someone who doesn't get the second, the difference will be minutes of his time, and possibly minutes of yours to explain it to him. Worth it?

This example demonstrates that "cute" and "elegant" are often orthogonal. The second example can't be elegant outside of the framework of the language because it relies on some non-obvious language idiosynchrasies (some of them not even necessarily right).

I guess that's a good way to put it. "Elegant" is in the eye of the beholder; everyone has a different meaning for it. What you think is elegant may cost everyone time--so avoid using "elegant" as a justification for reformatting 2 explicit lines of code into 1 "elegant" line.

dunno, maybe it's just me but from a clarity point of view I even find the ternary operator more obvious than either of the two examples provided: y=(0==x)?0:1 - it leaves no room for guessing and is still fairly compact.

@none Me too. Now take it to the 5 co-workers that you have to spend the most time coaxing along and ask them which is more obvious. Now, the question is, which will take longer, you figuring out the if() form or someone else figuring out the ternary form? For that matter, which is going to take more of YOUR time, writing out the if() or explaining the ternary?

@bobobobo That's my point, the samples were chosen because I googled "Elegant Code". The code I put up there is what people think of (in general) when they think of elegant code, they think of terse, cryptic tricks--not truly elegant, readable code (Which by the "readability" definition would be long and descriptive)--this is EXACTLY why I started my post with "Every time I hear the word Elegant these days, I cringe."

I see elegant as in beautiful in the sens that everyone can have different definitions of what is beautiful. Some find elegant code when there're really few lines, some other might find elegant code when a problem is resolved in a non-orthodox way.

I personally find code/design elegant when you just have to read it and it becomes perfectly clear in your mind. You don't need to "think", neither to read comments.. I don't care if it's 5, 10, 100, 1000 lines.. It can be anything, from a DB request to some fancy algorithm, for me elegant = clean and easy to understand.

I might look as "noob who can't think", however, it's when everything is simple that you can accomplish the most complex things.

Last note, scheme is elegant.. even if it is an old language, every time I look at it I've got the feeling I'm reading futurist code :p No []{}*^&#%^$.. Only simple words with a simple syntax.

This is a definition which assumes there is a ( coding ) problem that is to be solved by the code. Elegant code is code, that once a person is able to understand the problem, and understands the abstract part of the solution, which is written in such a way that once understood is obvious, but which the average programmer could not have written unless be had seen something similar before.

Quality is a characteristic of thought
and statement that is recognized by a
nonthinking process. Because
definitions are a product of rigid,
formal thinking, quality cannot be
defined. But even though Quality
cannot be defined, you know what
Quality is!

Quality (or elegance or aesthetics) is something that is recognized without applying formal analysis. It seems part of what we are (i.e. a product of Darwinian evolution) rather than something that we consciously think about. You'd have to reverse-engineer a human brain to automate the evaluation of quality. If you are looking for a metric, you are not going to find one here.

Good answer, apart from where you say these properties are not measurable in practice. Yes they are and that's a good thing - create/modify/maintainenance time is totally measurable and so is run-time performance.

I see what you mean. Yes, total time is measurable *in retrospect*. Mathematically speaking, what you want to minimise is the *expected* total time, given probability distributions on future change requests and coder competence levels, and I don't know how to estimate that in advance.

The same way you estimate anything - based on past experience, past measurements and your own judgement. And you could go back later and check how accurate the estimates were against your subsequent measurements. (BTW I will +1 this answer now!)

Because it's different in different languages doesn't make it subjective. Clarity is testable and therefore objective - give the code to some programmers and then test them on their understanding. For instance see Code Complete. Effective is testable too if the requirements are done right.

It might make you happy, but even experienced C programmers have to think a bit harder when side-effects are used. The legendary Code Complete advises against using them because they harm readability. IMHO this sort of elegance is harmful and should be avoided.

It might make you happy for the time being. But it won't make a lot of other people happy. And it won't make you happy when you have to fix a bug that was created by someone that had to modify the code, but who couldn't really parse through it.

I think elegant code is code that is written in such a way that it's a breeze to maintain.

Elegant code shouldn't rely on comments to explain what "int a,b,c,d;" do. It should have self-documenting names, and comments in the tricky code parts. So elegant code should be code that you can glance at and understand, and another programmer should be able to understand exactly what happens within minutes... Also, elegant code should be very quick to extend(no one likes typing "doThisOneFunctionAFewTimesAndDoSomethingElse()" )

Mathematicians describe an especially
pleasing method of proof as elegant.
Depending on context, this may mean:

A proof that uses a minimum of additional assumptions or previous
results.

A proof that is unusually succinct.

A proof that derives a result in a surprising way (e.g., from an
apparently unrelated theorem or collection of theorems.)

A proof that is based on new and original insights.

A method of proof that can be easily generalized to solve a
family of similar problems.

I think all these points can equally be applied to elegant code.

Bertrand Russell described mathematical beauty thus:

Mathematics, rightly viewed, possesses
not only truth, but supreme beauty — a
beauty cold and austere, like that of
sculpture, without appeal to any part
of our weaker nature, without the
gorgeous trappings of painting or
music, yet sublimely pure, and capable
of a stern perfection such as only the
greatest art can show. The true spirit
of delight, the exaltation, the sense
of being more than Man, which is the
touchstone of the highest excellence,
is to be found in mathematics as
surely as poetry.

And again, in a somewhat hifalutin way, I believe this can also be applied to elegant code.

Elegant solutions are simple, clear, easy to communicate. They may not be efficient or simple under the hood, but the key is that they outwardly present both the problem and solution in a simple manner.

My favorite example of an elegant solution for a rather complex problem that's absolutely terrifying under the hood is ScopeGuard.

StackOverflow says everyone should read Code Complete. A theme throughout the book is managing complexity by making programs as easy to understand as possible.

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. Brian Kernighan

Elegance is a dangerous word, because it can encourage overly clever, brief, and incomprehensible code. This will make the code harder to understand and modify in the future. In my humble opinion some of the other answers to this question demonstrate this rather nicely - sorry guys!

You should take pride in the appearance of your code. But I think words like clarity and simplicity are better touchstones than elegance. These are not subjective. You can measure clarity - ask programmers to read code, and then test their understanding by asking questions. Cyclomatic measurements give a handle on simplicity. See Code Complete for more.

Finally I would say programming is engineering, not art, because we are trying to solve problems by a mixture of science and creativity. (I hope everyone here is trying to solve problems?)

Elegant code is clear, correct, and performant. All three of these are difficult marks to hit, and it's important to realize that "not elegant" is not the same as "wrong".

Clear

Self-documentation is (correctly) held up as an ideal to which all code should aspire, and so is an important part of elegance. Importantly, clear is not the same as simple, though code which is one is often both.

This is also a very subjective property, which highlights the fact that elegance is in the eye of the beholder. An experienced Python programmer may see a complicated list comprehension and see elegance. A beginner, on the other hand, may well fail to "comprehend" entirely.

Correct

Obviously, code which does not do that which is was designed to cannot be elegant. More subtly, however, elegance often implies an absence of "surprising behavior", such as bugs. In this sense, code can change from elegant to non-elegant without being altered if bugs are discovered or requirements change. Again, elegance is revealed to be subjective.

Performant

If a task is not completed in a reasonable amount of time, using a reasonable amount of resources, the code which performs that task is not elegant. This is the most-often forgotten aspect of elegance, as "clever" code can often appear to be both clear and correct. If it is not also performant, however, it is not elegant.

A perfect example is the bubble sort. Is it clear? Yes, it's simple enough that even most beginning programmers grasp it easily. Is it correct? Well, yes, it unarguably gets the job done. But is it elegant? I doubt anyone would call it that. The reason, whether consciously understood or not, is that it isn't performant.

As many have shown, elegance is not that hard to define as a term, but I think it is at least partly subjective. Most people can agree that indenting your code makes it more readable, which is a factor in its elegance, but not everyone can agree how code should be indented. Elegance is full of trade-offs.

I think programming is more of a craft than an art, but it has art-like aspects. That's where programming gets it subjectiveness from. Not everyone has the same taste in artistic styles. I think it's because of the art-like aspect of programming that it is somewhat possible to discuss code elegance as opposed to other crafts where there is no (or little) art aspect.

Elegant code for me is all about how it translates into language. The most elegant code reads more or less like a novel, it expresses complex relationships with the correct level of detail without exposing the reader to more detail than they need to understand the current portion.

Encapsulation and naming are key to this process. If one is looking at the above code they probably have no interest in the mechanism for storing the letters or obtaining the unique identity for the address. If theyare interested this code they can open the mailbag code and example the .ForAddress() function, but they don't have to read it if they're not interested in that.

To me this is elegance, you only see what is relevant. I want to see the postman deliver letters, I don't want to read about how he walks down the road or organizes his mailbag. The important part is to keep the short term load on the mind small. You don't want to have to take a deep breath halfway through the code to double check what is still in scope or have to trace a long line through a method to see what occurs when a particular variable has a particular value.
The hope is that you can convert the code into a story which easier to comprehend and requires less translation from the requirements document.

As a footnote I do have to back track a little to state that elegance can take on many different forms. Readability is just one of these and you have to strike a balance with other forms of elegance. Other forms can include things like delivering on schedule. I'm sure we've all experienced a scenario where a cute little hack prevents us from having to completely re-organize the entire API for the sake of elegance to accommodate a rarely encountered error condition.

As for the bonus about "Art" I'm unsure if this is a relevant side-note in regards to just programming. Any action that a human performs can be considered art. From the precision and order that an experienced brick layer achieves in their brickwork from a dancer interpreting the slight gait that a disabled person has when they walk down the street. All can be interpreted as art.

I like to think as programming as a mechanism of story telling, which I guess some might consider as an art form. Software is created from a story from a client about a problem. This is then translated into requirements which is then translated into code. The fascinating thing about code is the level of detail that is added from the original requirements and the elegance is expressing that level of detail without overwhelming the reader. A book that slowly unfolds.

Perhaps a good analogy would be the experience one gets when reading Wikipedia due the nature of hyperlinks. The anathema of this would be the content of the hyperlinks presented inside the article being read (spaghetti-pedia!).

Googling for "elegant code" I found here a very nice description of it, which I'd like to share:

"Elegance is a combination of power and simplicity. Elegant code does much with little. Elegant code is not only correct but visibly, transparently correct. It does not merely communicate an algorithm to a computer, but also conveys insight and assurance to the mind of a human that reads it. By seeking elegance in our code, we build better code. Learning to write transparent code is a first, long step toward learning how to write elegant code — and taking care to make code discoverable helps us learn how to make it transparent. Elegant code is both transparent and discoverable."

You will know elegant code when you see it, but not always at first glance.

Bonus round: Of course there is code that qualifies as Art, but (as usual) its merit is highly subjective. If I've understood this correctly, Art in general is defined by the intent to be Art - that is why Emin's bed is a piece of capital-A Art, but my own bed is just a mess. For code, the intent is rarely to provoke or stir emotions, but rather to get the job done and do it well. By this definition, a thing like Duff's Device would not be classified as art when used as an optimization, but when used to obfuscate a program it would, since that qualifies it as intentionally thought-provoking.

Simply put, engineers are not artists by definition. We are more elegant :)

Assuming that two programs solve the same set of problems correctly, the simpler one is more elegant. Note that if the set of problems is badly chosen, they might represent a subset of the problem-space for which there exists a very elegant solution - but it isn't the one you meant to solve (this is the "oracle" or "genii" problem, of taking care with questions and wishes).

There is a formal approach to elegance in terms of occam's razor: you can measure the complexity of a solution in terms of its information content. For example, the abstract syntax tree of "i+1+1" is more complex than the AST of "i+1", which is more complex than the AST for "i++".

Formally, you assign a probability for each choice of interior node in the tree (for a +, -, * etc), and for the leaf nodes (eg. a uniform probability distribution for 8 bit integers would give each value a probability of 1/256). If you think of the number of bits needed to specify each decision in the tree, you sum them to get the information content for the code (you can use fractional bits).

This gives a formal bayesian measure of "simplicity", in terms of how likely or expected it is.

While formal, it's not objective, because you get to weigh the probabilities of choices. However, you can try to be objective about this, by counting occurrences in a large corpus (eg all the Apache open source code). It's harder to capture typical patterns of usage, that is groups of choices in idioms, design patterns and so on, but one could make a fair attempt. Formally, one might use a simple markov model to represent this (eg in text, the character following "q" is very likely "u").

I think patterns of usage should be included in measuring simplicity, because elegance in code is not about using tricky clever shortcuts or hacks, but in grasping what the problem truly is, and just solving that in a straightforward way.

The code that just reads naturally. You look at it and know what it does without knowing all the language details. Actually you may not even know the language, if the code is well-written you will be able to understand most of it.

The code that speaks in problem language not implementation / CS language.

The code that is designed/thought through before being written - you can see it when you want to make changes or extend it. With elegant code it will be obvious how to do it in elegant way without doing dirty tricks.

In one of the Stack Overflow podcasts, Joel said elegant code has fewer moving parts than you intuitively think are necessary. It's so simple that it doesn't seem like it could possibly work at first glance, but it does.

Elegance is achieved when code does exactly what it should, and looks effortless. Effortlessness is achieved by using tools perfectly suited to the problem in an appropriate way.

An example is expressing the algorithm of a "join" function. This function should take a delimiter and a list of strings, combine them with the delimiter between each item, and return the joint string.

In C#, it seems that the use of a "string builder" object is idiomatic, but anyway, you'd use some sort of loop, and you have to make sure to add the delimiter only between the items, not at the beginning or end.

This makes a temporary StringBuilder object, then puts alternatingly a delimiter and an item inside. To make sure that there is no delimiter at the start, the delimiter is set to "" initially and to its real value after each iteration. Finally, the StringBuilder object is told to give back its contents as a string; the StringBuilder object is then destroyed when the scope is left. By the way, this code was given by Jon Skeet, so I have to assume that it is pretty idiomatic for C#.

To contrast: in Common Lisp, you first express the singular operation of combining two strings, a and b, with a delimiter between them: (lambda (a b) (concatenate 'string a delimiter b)). You use this in some sort of loop to combine two elements of the input list until only one element is left. This kind of combination loop is so common when dealing with lists that it has its own looping construct in the language: reduce. reduce takes two arguments: a function of two arguments to combine two elements, and a list. The whole thing is then:

(reduce (lambda (a b)
(concatenate 'string a delimiter b))
strings)

Notice how you don't have to put any extra effort into making sure that the delimiter doesn't appear at the beginning or end. This is due to that the lambda expresses exactly what you mean: "put the delimiter between each two items", not "put the delimiter after each item except the last", and not "put the delimiter before each item except the first".

Usually when you want to measure code quality, you look at qualities like robustness, maintainability and scalability. You want to measure how good the code works, and even clumsy, inefficient code works well enough in most situations. Code elegance comes in as an abstract part of the maintainability, but it's not very easy to measure.

I have done some assembly language size programming competitions, where the goal is to write the shortest possible program to perform a task. Eventhough the final code is often over complicated and tricky, it still needs a great measure of elegance to use the best method to do as little extra work as possible. Size is not a good measure of elegance, but the elegant code is often shorter.

Code tends to need fixing and changing, and it also tends to be copied and reused. So, what you usually want is easily managed code rather than elegant code. They are often the same, but not always. Say for example that you have written some elegant code that handles responses on a questionaire, where there are four alternatives for each question. Now the customer says that they need five alternatives instead, and your elegant code is worthless. In this case a less streamlined approach would be more flexible and perhaps require only changing a single digit.

Great Question, love it :)
We can define two aspect of elegance in programing.

Code design

Algorithm

The code design elegance is mostly used for readability of code, it easy to reuse and make modification. That's mean that code is elegant, if other programmers can fast understand what your program do when they just look at your code.

The algorithm implementation, when the algorithm use all tricks to make program run faster. Sometimes you need to break the code elegance for making things faster, and the art is, how can you make things really fast.

About programing as Art.
Programing in our day, its easy way to create a worlds of beauty of performance and elegance.

I'm posting an answer because I'd like to respond to Bill K's post comments thread, but I've got too many characters ;), so here I am.

Well I think the topic is very subjective, so the global discussion sure will be wide.

@Bill K: I know exactly what you mean. But, even if we were just talking about philosophy, not merely "efficiency" of code, one could observe that also classic human languages like Greek or Latin are considered "elegant" and studying them can really let your analysis capabilities benefit from the effort; thus knowing them makes you better.

I think it is the same thing here. What Google showed up to be "elegant code" in your example, could be a few seconds harder to understand to inexperienced programmers, but it is a good synthesis, nevertheless.

Nothing wrong with the "shanky" code in your example: it is clear and unconfusing at all, but if one is new as a programmer to the expression you show in the "elegant" (let me use this term to barely identify the example) code snippet, well that snippet can let grow his perception and synthesis and let him project himself towards a new form of expression.

Synthesis is good, after all, as far as it is significant and useful.

There's nothing wrong btw in programming expressing concepts in a "shanky" way, as long as efficiency and functionality are not concerned.

And I think that what we programmers call "elegance" is a blend (or intersection, if you prefer) of functionality, clarity, efficiency, synthesis and - last but not least - aesthetic.

Finally, in a programming world which tends to standardize everything from abstract concepts to material approach is so much delightful to notice how many different people have different opinions on what should be elegant code. It shows that diversity is not evil. It is just a way to better understand yourself and the world around and challenge yourself to be honest and promote a change in your points of view, if you honestly feel the urgency to.

I agree with you (Enough for a +1), and am a "Code Artist" at heart, but part of the art is coming up with a clear understandable code because the people paying you need that. Your example makes the PERFECT point by itself. How many business documents today are written in Greek or Latin?

I'll pay one more rep point to say (Did you know comments cost rep?) that in educational and open-source environments I'm 100% for fun, concise, elegant and possibly even Cryptic code! Just like Latin makes sense in the classroom!

By that what I mean is that, you do not have to decipher code to figure out what a code does at a glance.

For Bonus Round:
* Everyone has different opinion on what an "Art" is. If you consider an Art as a creative process, yes, programming is an Art.
* If "craft"ing is a way of constructing a model or a product by putting many different part, then programming is also a Craft. You are basically putting your code or components together to build a product, a program.

I believe that elegant code or "girl code" as some like to call it can be measured, to some extent, with cyclomatic complexity - besides good naming conventions, identation, etc elegant code is usually just plain simple - only a few paths can be followed during the execution leading to even less exit points.

Background; I've been writing code since I was 9 and writing C for over 20 years. (Dad worked at AT&T)

You can't choose the difficulty of the problem, so elegance has little to do with "solving a hard problem with a unintuitive solution". Elegance is a result of the choices you make while solving a problem. Often, an unintuitive solution may present itself, but that is fortuitous. Making good choices results in beautiful software - easy to use, easy to understand, easy to modify. That is elegance.

The most basic part of elegant code is Correctness. If a solution does not solve the problem, it is not elegant.

Simplicity is definitely the major hallmark of elegance. Getting more done with less is almost always a good choice. This can be fewer operations (e.g, the 1-branch binary search) or with fewer dependencies on the underlying libraries or fewer requirements on the inputs. Less code means less to understand, less to screw up, and fewer indirect interactions.

Obviousness is another hallmark. If someone needs a month to decypher your code, it is not elegant. If someone needs to work out a proof to see that your code is correct, it is not elegant. (My doctoral work resulted in a 6 line distributed program that required 20 pages to prove it was correct.) One can help obviousness by adding a good comment, but the best way is having well-structured code and using the proper data structures. Another is following conventions and using good names, which make the code easy for strangers to digest.

Separation of Concerns is a hallmark: if each requirement is clearly traceable to a particular piece of code, this is elegant. If a requirement changes, only that code should have to change. Also, those who care only about certain requirements of the code need only to look at individual pieces rather than understand the whole. Similarly, your solution should be independent of the rest of the program.

I think these aspects are the big ones. I can recommend Dijkstra's "A discipline of programming" where he tries to show that if code and proof of correctness are developed together, you get good solutions. I can also recommend reading lots of code, especially different solutions to the same problem. E.g., I find the 1-branch binary search on Wikipedia very elegant on a common problem. For sorting, I found my friend's "shuffle than quicksort" a very fast elegant solution that, with high probability, avoids the worst cases. I find the cuckoo hashtable an interesting contrast to the usual hashtable.

Elegance is about beautiful code. And people will debate what is beautiful. This list is enough for me to work on perfecting in a lifetime and I think it captures a lot of what "gw" has in his page long list of adjectives.

The code that does not bleed your eyes when you look at it.

Elegance is a clear, direct mapping to the problem being solved. This may give the appearance of simplicity because the solution is no more complex than the problem itself. But it may not actually be simple if the problem is not simple. Elegant code makes it look simple. When reading elegant code, you get an "aha!" moment--a little epiphany that makes you feel like you discovered something or reached a deeper level of understanding.

Elegant code doesn't have special cases. The "special" cases are handled naturally by the same computation that handles the "normal" cases.

Elegant code has all the redundancy factored out.

There are elegant algorithms and elegant implementations of algorithms. These are separate. Just the other day, I saw an inelegant implementation of an elegant algorithm. I suppose an elegant implementation of an inelegant algorithm is possible.