views:

6636

answers:

83

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!

+176  A: 

It's the intersection of simplicity and functionality.

brian
What an elegant response. +1
Matt Briggs
Define "simplicity" and "functionality"
Breton
Define "define"
brian
simplicity = its readable and easily grokedfunctionality = it works
Doug T.
@Doug T...Brian's answer leaves me somewhat cold, but combined with your definitions, I would consider it perfect.
Beska
See this answer for a good point on 'simplicity': http://stackoverflow.com/questions/563036/what-is-elegant-code/563085#563085
Jonik
It depends on what your definition of "is" is.
Chuck
I hate you...I spend all day trolling around and you just hit it up once...ugh
Jason Punyon
http://en.wikipedia.org/wiki/Ockham_razor - I think Einstein said something like: as little as possible, but nothing less
meade
nice formulated. i love this
Johannes Schaub - litb
Nice answer, and totally definable. Readability is even measurable: get programmers to read code, then test them on their comprehension.
MarkJ
@meade: Make everything as simple as possible, but not simpler.---Albert Einstein
Jason
Nice succint way of saying what I was thinking
Dave Costa
Usually the result of correctly utilizing the correct language for the correct job.
Jonathan Park
Can I add "readability" in somewhere?
bobobobo
+4  A: 

Is it something that can be measured?

NO.

Or is it a matter of taste?

YES.

SumoRunner
+59  A: 

Elegant code is code that does in a few crystal clear lines what you would think would take heaps of complex code to achieve.

mezoid
and this is why this is an elegant answer :)
hasen j
+36  A: 

My rough definition of "elegant code":

Code which is written such that the number of lines/statements is minimized while the readability and functionality is maximized.

Or, to put it another way:

The ratios of readability to number of statements and functionality to number of statements are both high.

I've specifically included readability here. There are plenty of "one-liners" that get a lot done, but if no one can tell what they are doing, they aren't elegant.

SoapBox
How do you quantify readability and functionality?
Wim Coenen
A: 

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.

digiarnie
+10  A: 

To paraphrase Justice Stewart, you will know it when you see it.

EBGreen
Nice! I approve!
+2  A: 

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.

DJClayworth
+13  A: 

Forgive me for being silly, but I would have to say that elegant code is code that is elegant.

From Dictionary.net:

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.

Snarfblam
+20  A: 

"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.

Programmers make programming an art.

Adam Bellaire
This one is a good contender. Anyone thinking of adding a new answer, please try and build off this.
Breton
Yes, nicely put; especially the observation on the meaning of 'simple'
Jonik
Some people think that "as terse as possible" and "as easy to understand as possible" are the same THING. Which path leads to using one-character variable names so it'll all fit on the one line.
mjfgates
+1  A: 

It is code that is:

as simple as possible for the problem (which implies that it is readable and easy to maintain) AND as fast and efficient as possible (which implies that it works well)

pfunk
+1  A: 

Elegant code implies simplicity. Since there are ways to measure the complexity of code, elegance can be measured indirectly.

+6  A: 

The code cannot be elegant as a whole without an elegant design. I think design elegance can be roughly measured using the MIT or "worse is better" approach measured by degrees of:

  • Simplicity
  • Correctness
  • Consistency
  • Completeness
rick
+2  A: 

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.

Brian Postow
Jonik
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.
Svante
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...
Brian Postow
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?
Thorbjørn Ravn Andersen
+6  A: 

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.

jacobangel
+2  A: 

Not sure who said it first, but often a reasonable working definition of an elegant solution is one that can be implemented and understood with less effort than is required to document it.

Interesting contrast: remove the word understood, and the result is a reasonable working definition of an obfuscated solution.

Adam Liss
+6  A: 

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.

James
+6  A: 

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.

David Thornley
+1  A: 

Elegant:

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.

J.F. Sebastian
+1  A: 

Simple, clean, clear, effective, extensible.

Less code is almost always more.

Jas Panesar
+1  A: 

http://en.wikipedia.org/wiki/Metaphysics_of_Quality

I believe that any human endeavor where the ego is forgotten, for that period of creativity - Those 'In the zone' times, can be considered art.

Andy Johnston
+1...I recommended his book, didn't know wikipedia had a more detailed description of the books thema
epatel
+5  A: 

"Make everything as simple as possible, but not simpler." -Einstein

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.

mandaleeka
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.
Bill Karwin
+1  A: 

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.)

Jon Ericson
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"?
Breton
I'd say that's fully functionally. And if you are trying to pass a basic programming class, it's hard to say that it's not useful. It's just not generally useful.
Jon Ericson
+1  A: 

Elegant code does not multiply entities needlessly.

chaos
+15  A: 

May I offer a different viewpoint?

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)

Bill K
+1. This is why I asked the question, to get some back and fourth going, and get people really thinking about it, and hopefully learn something new.
Breton
see, I would actually say that the first "skanky" example is the elegant code. It's simple, efficient and readable.
pfunk
@pfunk exactly.. but when you google "Elegant", that's what comes up. My point is that when you hear the word "Elegant", it may not mean what you and I would like it to mean, so I cringe.
Bill K
Unfortunately, those who write "elegant" code also write code that's very difficult to read.
Jess
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.
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 ;-)
Mike Spross
Mike Sposs is *so* right. The elegant solution is different and no-one else noticed. Case closed, elegant code is harmful, lets all move on now. (I'm not joking)
MarkJ
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
Bill K
@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.
Beska
My point is that the way most people use the word is wrong. You can redefine the word if you like, but I suggest you still be wary of people using it (or of what they think you mean when you use it).
Bill K
I spent more time understanding the first example than the second. Is it normal?
Andrea Ambu
@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?
Bill K
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).
MadKeithV
"Elegant" is language- (and language-culture-) specific. To experienced C programmers, your "elegant" example is obvious. To beginners (or part-timers) in C, it's confusing. To Java programmers, it's wrong (it returns a boolean instead of an int).
joel.neely
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.
Bill K
I wish I could upvote the comments thread.
Breton
I wished to post a comment here, but there were too many characters. So I added an answer. +1 for me btw.
Scarlet
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
@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?
Bill K
But in some languages you'd need 'y' to be a boolean? In C, or C++ I guess this works, but not for Java/C#. Correct me if I'm wrong.
lb
mikerobi
The example shown here isn't truly elegant because it lacks in the readability department..
bobobobo
@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."
Bill K
+3  A: 

Elegant code is what you're left with when you can't take anything else away from it.

Sean
+1  A: 

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.

+13  A: 
epatel
Yes the question indeed sounds like the ramblings of the zen/motorcycle protagonist
sharkin
And 1+ for the Shakespeare analogy.
NoProblemBabe
+27  A: 

Simplicity is hard to build, easy to use, and hard to charge for. Complexity is easy to build, hard to use, and easy to charge for. — Chris Sacca

Gumbo
Thanks a great one! :)
epatel
+1  A: 

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.

BubbaT
+3  A: 

I found the best definition of elegance here: http://www.changethis.com/29.01.ElegantSolutions

Elegance is the simplicity found on the far side of complexity. An elegant solution is one in which the optimal outcome is achieved with the minimal expenditure of effort and expense.

So, an example I love to give is using sizeof with the C preprocessor to compile out vararg functions. Before C99, this was the best way to get rid of unused debug code for logging functions.

MSN
+1  A: 

Robert Pirsig (author of Zen and the Art of Motorcycle Maintenance) once taught a class on rhetorics and gave his students this (non-)definition for the concept of Quality:

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.

Wim Coenen
+18  A: 

A long time ago I thought about what attributes contribute to elegance. Here is the list that I came up with. Some of these apply to hardware as well, and there is some overlap, but anyway:

  • accurate, correct (operates exactly as instructed)
  • adaptable (easy to modify to suit other purposes)
  • attractive (aesthetically pleasing (but preferably not at the expense of functionality))
  • compact (small, lightweight, portable)
  • comprehensive (complete, thorough, solves for the general case)
  • consistent (predictable operation and user interface)
  • controllable (easy for operator to maintain complete control)
  • convenient (desirable to use)
  • customizable (tweakable)
  • durable (robust, rugged)
  • economical (inexpensive, cost-effective, low total cost of ownership)
  • effective (well-suited to intended purpose)
  • efficient (fast or otherwise resource-efficient)
  • environmentally-friendly (non-toxic; not wasteful)
  • ergonomic (comfortable; not harmful to operator)
  • extensible (easy to add new features)
  • failsafe (prevents undesired operation; discourages misuse; enforces proper operating sequences; capable of failing gracefully and safely (but preferably not silently))
  • functional (designed with function as a priority to form)
  • interoperable (compatible with other systems)
  • intuitive (user-friendly, unambiguous user interface)
  • maintainable (components are easy to access, repair, and replace)
  • modular (components are interchangeable, or system is interchangeable as a whole)
  • orthogonal (features operate independently of each other, or in any sequence, or all similar features are equally capable)
  • practical (economical; quickly and easily deployable)
  • precise (results are reproducible)
  • quiet (not contributing to noise pollution)
  • recyclable (components can be safely and easily recycled to reclaim materials)
  • reliable (stable, dependable, fault-tolerant)
  • reusable (components can be used for other purposes)
  • safe (non-toxic; alerts operator to potential problems)
  • scalable (suitable for use with larger-than-optimal workloads)
  • responsive (responds quickly to operator changes or changes in operating conditions)
  • secure or securable
  • self-correcting (automatically adjusts to improve precision)
  • self-tuning (automatically adjusts to improve efficiency based on current operating conditions)
  • side-effect-free (does nothing beyond the stated function)
  • simple (straightforward, no superfluous features)
  • standards-compliant (conforms to established standards)
  • sustainable (can operate continuously)
  • upgradeable (easy to replace components to increase speed or capacity)
  • verifiable (testable, provable)
  • versatile (multipurpose, flexible)
gw
Ironically, the list of properties here is anything but elegant. :-)
Jeffrey Hantin
Ah, but alphabetical order!
JXG
Why is it ironic that "elegant" is used to describe something that is at heart highly complex to define, yet easy to recognize when you see it?
MadKeithV
+3  A: 

I feel that elegance == high-quality design. And I will venture that elegance is an objective quality, albeit something that cannot be measured directly. Very simply:

A good software design minimizes the time required to create, modify, and maintain the software while achieving acceptable run-time performance.

This is from James Shore's piece, Quality With a Name. Reading this article was a truly enlightening experience for me.

Unfortunately, many of these quantities are not measurable in practice. But in my mind there is no question that this is the right way to define elegance.

j_random_hacker
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.
MarkJ
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.
j_random_hacker
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!)
MarkJ
Good point MarkJ. There's quite a large amount of judgment in these estimates though, and usually N (the number of previous experiences you are using to make the estimate) is small.
j_random_hacker
Good point. I believe that sometimes elegance can require more time in design.
lb
+1  A: 

Elegant code is what satisfies all three of:

  1. Succinct - no longer then necessary
  2. Transparent - straightforward to read and understand what it does
  3. Durable - handles exceptional and corner-cases (without too much checking for special cases)
Joe
A: 

Subjectively speaking, elegant code is at the same time:

Effective: It does what it should do and nothing more.

Clear: Code that humans can read not only machines.

This is totally subjective, and what is considered elegant in one platform ( or language ) may not be in other.

For instance, elegant code in Perl, may not be considered elegant by Smalltalk developers ( or it may, the point is to make clear the subjectivity of the term ).

And no, neither code or programming it self may ( or should ) be considered as Art.

In my opinion, the art should not have any other objective than "the human being recreation" Clearly software is created to satisfy other kind of needs.

A useful link: http://en.wikipedia.org/wiki/Elegance

OscarRyz
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.
MarkJ
A: 

Simply put, elegant code is never having to say "I'm sorry".

jonathan.cone
Nahh that would be "Ok" code or "Good" code. Elegant code would have other say "Thank you!!" :)
OscarRyz
A: 

Code that make you feel good when you write it.

Here's an example:

for (int i=0; i < temp_len; i++) {
 m_buffer[m_length++] = *other++;
}

It just makes me happy.

Jack BeNimble
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.
MarkJ
@MarkJ: See, subjective. :)
OscarRyz
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.
Beska
A: 

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()" )

Earlz
+9  A: 

I think the term 'elegant' for code was probably inherited from the use of the term in mathematics, and is directly analogous to it.

From wikipedia

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.

Does this justify calling good code 'art'?

Hell, yes!

But in reality most code is like http://en.wikipedia.org/wiki/My_Bed

DanSingerman
And all those properties of an elegant math proof should be *avoided* like the plague in production code. They will make it hard to read and prone to error. If you're a researcher they might be OK.
MarkJ
Sorry - we'll have to agree to disagree
DanSingerman
A: 

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.

Dan Olson
+1  A: 

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?)

MarkJ
+2  A: 

An elegant solution is one that grasps the essence of the problem: "oh, when you think of it like this, it's simple".

It's not that it's elegant, but that it's true. Beauty is truth, truth beauty, and with this aesthetic ye don't need to remember all those complex special cases.

13ren
+1 for the first sentence
Svante
+2  A: 

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.

Ben Blank
A: 

Beautiful Code has a number of examples of elegant code.

Joshua
A: 

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.

Scott
A: 

Code is to elegant code what prose is to poetry.

John at CashCommons
+1  A: 

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.

foreach(Letter letter in mailbag.ForAddress(currentLocation))
{
    currentLocation.Deliver(letter);
}

As opposed to:

foreach(Letter letter in mailbag.Items[currentLocation.GetKey()])
{
    currentLocation.DropBox.Add(letter);
}

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 they are 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.

One of my favourite examples of elegance is the state pattern. This:

if(direction == Direction.North)
{
    g.DrawTriangle(new Point(0, 10), new Point(5, 0), new Point(10, 10));
}
else if(direction == Direction.East)
{
    g.DrawTriangle(new Point(0, 0), new Point(10, 5), new Point(0, 10));
}
else if(direction == Direction.West)
{
    g.DrawTriangle(new Point(10, 0), new Point(0, 5), new Point(10, 10));
}
else if(direction == Direction.South)
{
    g.DrawTriangle(new Point(0, 0), new Point(5, 10), new Point(10, 0));
}
else
{
    throw new InvalidOperationException(String.Format("Unrecognised direction: {0}", direction));
}

Becomes this:

direction.Draw(g);

and that's beautiful.


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!).

Quibblesome
Wow! another excellent answer to the bonus round.
Breton
A: 

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."

MicSim
+1  A: 

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 :)

Christoffer
Yes! this is the most thoughtful answer to the bonus round I've seen yet.
Breton
A: 

A formalization of simplicity

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.

13ren
A: 

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.

ya23
A: 

Elegance is when beauty, brevity, cleverness and/or laziness take a back-seat to doing the simplest thing that works the right way.

MadKeithV
A: 

E = mc2 baby!

where,

E = Elegance
m = minimal
c = code
2 = to meet the requirements whilst maintaining readability.

Macka
+1  A: 

One of my college professors said "Genius is stating something which, once it has been stated, is obvious to everyone."

I believe the same thing is true of elegance in programming. Elegant code not only makes the task appear easy, it makes it obviously correct. It makes me smack my forehead and think,

Well, of course that's right, and it's so much simpler than what I was doing!

joel.neely
A: 

a code which as beautiful as poetry is "elegant".

Sharique
+4  A: 

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.

I can't find it in the transcripts, but I think it was around #40.

Patrick McElhaney
+1  A: 

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.

StringBuilder builder = new StringBuilder();
string delimiter = "";
foreach (string item in list)
{
    builder.Append(delimiter);
    builder.Append(item);
    delimiter = ",";       
}
return builder.ToString();

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".

Svante
A: 

From the illustration of a code review on the introduction page of Clean Code: "The only valid measurement of code quality: WTFs / minute"

I deem code elegant if it solves a complex problem via several simple solutions.

Aaron Daniels
A: 

Elegant solutions, workmanlike code.

13ren
+1  A: 

Elegant code is code you're never going to have to refactor.

VirtuosiMedia
A: 

{Speed, Size, Readability} Pick Three.

(not two)

Strilanc
+1  A: 

Elegance in code is obvious when you see it just as sloppiness is. But just to help us recognize when we see elegance staring in our face:

  1. Elegant code is organized (divided into proper code blocks, functions, classes).
  2. Elegant code is not repetitive (makes best use of every line written).
  3. Elegant code is crisp (no statements that buff up the line count).
  4. Elegant code is clear (You read it, you understand it if you're paying attention).
  5. Elegant code has a clear execution path (You can predict where the debugger will go next).
  6. Elegant code is maintainable (no variables named after your dog).

And you know what... Elegant code has no spelling mistakes in variable name, or in comments (though many programmers may not agree. And also :) capitalization rules!)

Basically elegant code is that looks elegant when you see it.

Cyril Gupta
A: 

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.

Guffa
A: 

I think of 'elegant' code as something that you might not have thought up at first, but once you see it done that way and understand it it's obvious that you'd never want to do it differently again.

Joel Coehoorn
A: 

Code that reads like a book, but might run like a pig.

(Not that pigs are slow - “You can't make a racehorse out of a pig, but you can make a very fast pig.”)

Ant P.
A: 

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

  1. Code design
  2. 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.

Avram
+1  A: 

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.

Code is not an exception to human thought, after all.

Scarlet
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?
Bill K
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!
Bill K
Ok, ok, your point is clear, and I completely agree with you ;).
Scarlet
+1  A: 

In short: Code that solves the problem so cleanly, so easily, so quickly and so grokably that there's scant room for improving it.

In long: Elegant code leverages either other code, built in language tools, or the data itself to accomplish its job quickly and easily while being short, and readable.

Trampas Kirk
A: 

Yawn...

Elegant code is refactoring a useless database (into a useful one) by changing one table.

leppie
A: 

For me an elegant code is code that appears like XML formatting ^_^

Omar Abid
A: 

In my opinion, an elegant code is a human-readable code.

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.

Sung Meister
I think elegant code has to be better than human-readable. It has to appeal to humans as well.
Adrian McCarthy
A: 

If you take elegant to be roughly the same as beautiful, then one answer is "proportionality, integrity, and clarity." I stole that from a video presentation you might find interesting.

Kev
A: 

"Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away." -- Antoine de Saint-Exupery

For me this describes elegant code perfectly: code that does exactly and only what you want (but also in a clear manner), without messy exceptions.

In essence it really boils down to simplicity.

Rubendv
A: 

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.

Alix Axel
+1  A: 

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.

Michael Nahas
+1  A: 

It's girlmetrosexual code!

alt text

Pascal Thivent
A: 

Like mentioned earlier elegant or beautiful code is difficult to quantify. It's a qualitative, subjective thing - like art - you know it when you see it.

An essential characteristic is simplicity - to quote the great Antoine de Saint-Exupery - "Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away."

But there are other aspects as well - IMO like art you can learn to recognize beautiful code - checkout this post.

I think the whole design patterns movement was an effort to identify and categorize beautiful code - like literary techniques one uses for writing a book.

Nikhil
A: 

To me, elegant code is how I would have wished I'd written it myself :) Like rapier fighting.

Thorbjørn Ravn Andersen
A: 

Quoting Why, from Why's Poigent Guide to Ruby this would be

"That means code so beautiful that tears are shed."

In my mind it's code that simple, clear, and makes you want to read it, almost like a good book, always bringing you back to reference it, or re-read it.

Christopher Hein
A: 

Simple to debug, ie, you can easily see/follow the programmers intention with every line.

Viktor Sehr
+1  A: 

Read "The Elements of Programming Style" by Kernighan + Plauger. It's one example after another of ugly inelegant previously published code rewritten to be elegant. You'll learn by example.

joe snyder
A: 

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

shamittomar
A: 

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.

Adrian McCarthy