Stack OverflowWhat is "elegant" code?
[+85] [83] Breton
[2009-02-18 22:01:30]
[ language-agnostic philosophy elegance ]

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!

It is indeed somewhat similar. I wonder if there's a way I can modify the question so that it's covering some new ground. - Breton
Arguably this is more concrete, because in my experience it's more common to actually hear people talking about an "elegant" solution to a problem than a "beautiful" solution to a problem. In particular, I think elegance implies simplicity, whereas beauty is more broad. But maybe that's just me. - Adam Bellaire
I've added a bonus round, that I hope builds on the question, and harmonizes in a way that I hope produces more interesting answers than each question considered on its own. It's weird that one can't vote to NOT close a question. - Breton
You can't put a bounty on someone else's question and you can't close a question with an open bounty. Interesting. - cletus
That is interesting. So you can post some really stupid essay on how lame language x is and just throw a bounty on it so it can't be closed? Nice abuse. - Bill K
I also think I earned way more badges on this question than I really deserved. - Breton
If you're looking for on-demand printing, might I suggest Lulu? I bought a book from them, and it was nicely bound. It didn't look at all like your normal self-published book. - TRiG
[+195] [2009-02-18 22:04:35] brian [ACCEPTED]

It's the intersection of simplicity and functionality.

(24) What an elegant response. +1 - Matt Briggs
(10) Define "simplicity" and "functionality" - Breton
(31) Define "define" - brian
(1) simplicity = its readable and easily groked functionality = it works - Doug T.
(1) @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':… - Jonik
(1) 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
(3) - 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
(1) @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
[+60] [2009-02-18 22:05:27] mezoid

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

(1) and this is why this is an elegant answer :) - hasen j
[+37] [2009-02-18 22:05:35] SoapBox

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.

(1) How do you quantify readability and functionality? - Wim Coenen
(1) But here's the beauty of the question: can you quantify elegance? - Adrian
[+36] [2009-02-22 22:46:51] Gumbo

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 [1]


(1) Thanks a great one! :) - epatel
[+21] [2009-02-18 22:11:34] Adam Bellaire

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

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
[+20] [2009-02-22 23:50:29] gw.

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)

(9) 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
[+16] [2009-02-18 23:34:26] Bill K

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;


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)

+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
(6) 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. - Frank
(9) 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
(4) 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
(3) @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
(1) @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
(1) 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
(3) "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. - Federico Zancan
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.
@Bill K, If you assumed that x & y were both 0 or 1 the elegent solution would have been: y=x. - 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
[+16] [2009-02-22 22:40:14] epatel

In code I believe elegance often comes from choosing appropriate data-structures. One could say doing a bottom-up-design when also thinking on a top-down-design. If one gets all problem solving dimensions aligned as simple I think that is pure elegance. Measurable? No, but you know it when you see it. (Read Zen and the Art of Motorcycle Maintenance [1] )

alt text

Picture from Thinking Forth [2]

Shakespeare puts it very concise "Brevity is the soul of wit"


Yes the question indeed sounds like the ramblings of the zen/motorcycle protagonist - sharkin
And 1+ for the Shakespeare analogy. - NoProblemBabe
[+13] [2009-02-18 22:10:19] Snarfblam

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

From [1]:

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.


[+12] [2009-02-18 22:08:32] EBGreen

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

Nice! I approve! - DevinB
[+11] [2009-02-23 10:41:43] DanSingerman

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 [1]

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
  • 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


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
[+8] [2009-02-18 22:20:33] rick

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" [1] approach measured by degrees of:

  • Simplicity
  • Correctness
  • Consistency
  • Completeness

[+8] [2009-02-18 22:54:34] David Thornley

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.

[+7] [2009-02-18 22:32:46] jacobangel

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.

[+6] [2009-02-18 22:44:51] James

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.

[+6] [2009-02-18 23:10:37] mandaleeka

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

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
[+5] [2009-02-18 22:05:05] SumoRunner

Is it something that can be measured?


Or is it a matter of taste?


[+5] [2009-02-25 13:54:32] Patrick McElhaney

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.

[+4] [2009-02-18 22:10:14] DJClayworth

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.


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.

[+4] [2009-02-22 22:22:01] Sean

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

[+4] [2009-02-22 23:05:33] MSN

I found the best definition of elegance here:

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.

[+4] [2009-02-23 02:32:14] j_random_hacker

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 [1]. 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.


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
(2) 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.
[+3] [2009-02-18 22:44:21] Adam Liss

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.

[+3] [2009-02-18 22:32:33] Brian Postow

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.

Great point; elegant code should be idiomatic in the context of the language used. This reminds me of the to-the-point foreword to Effective Java: - 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
[+3] [2009-02-24 22:22:29] Quibblesome

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

As opposed to:

foreach(Letter letter in mailbag.Items[currentLocation.GetKey()])

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));
    throw new InvalidOperationException(String.Format("Unrecognised direction: {0}", direction));

Becomes this:


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

(1) Wow! another excellent answer to the bonus round. - Breton
[+2] [2009-02-24 17:15:56] 13ren

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.

+1 for the first sentence - Svante
[+2] [2009-02-24 18:38:26] Ben Blank

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


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.


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.


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.

[+2] [2009-02-25 13:10:58] joel.neely

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!

[+2] [2010-06-28 00:17:52] joe snyder

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.

[+1] [2009-02-27 09:23:38] Federico Zancan

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.

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 ;). - Federico Zancan
[+1] [2009-02-27 22:46:29] Trampas Kirk

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.

[+1] [2009-02-26 05:53:41] VirtuosiMedia

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

[+1] [2009-02-26 06:22:50] Cyril Gupta

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.

[+1] [2010-02-07 17:00:15] Michael Nahas

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.

Like I said with the other post: "Separation of Concerns" can lead to "Separatist" bloating. Separate concerns, but don't separate things of no concern (e.g. don't isolate loop iteration beyond the languages foreach level) - sehe
[+1] [2010-02-07 17:12:29] Pascal Thivent

It's girl metrosexual code [1]!

alt text


[+1] [2009-02-24 11:00:05] MarkJ

StackOverflow says [1] everyone should read Code Complete [2]. 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?)


[+1] [2009-02-25 15:00:58] Svante

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

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

[+1] [2009-02-24 23:49:02] Christoffer

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

Yes! this is the most thoughtful answer to the bonus round I've seen yet. - Breton
[+1] [2009-02-18 23:02:10] J.F. Sebastian

Elegant [1]:

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.


[+1] [2009-02-18 23:03:11] Jas Panesar

Simple, clean, clear, effective, extensible.

Less code is almost always more.

[+1] [2009-02-18 23:07:15] Andy Johnston

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.

+1...I recommended his book, didn't know wikipedia had a more detailed description of the books thema - epatel
[+1] [2009-02-18 22:12:09] pfunk

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)

[+1] [2009-02-18 22:13:14] community_owned

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

[+1] [2009-02-23 03:18:14] Joe

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)

[+1] [2009-02-22 23:21:19] Wim Coenen

Robert Pirsig [1] (author of Zen and the Art of Motorcycle Maintenance [2]) 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.


[+1] [2009-02-22 22:26:08] user35978

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.

[+1] [2009-02-22 23:01:24] BubbaT

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.

[+1] [2009-02-18 23:12:40] Jon Ericson

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

(1) 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] [2009-02-18 23:18:22] chaos

Elegant code does not multiply entities needlessly.

[0] [2009-02-23 10:58:26] Dan Olson

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 [1].


[0] [2009-02-23 04:00:38] OscarRyz

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:

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
[0] [2009-02-23 04:02:59] jonathan.cone

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

Nahh that would be "Ok" code or "Good" code. Elegant code would have other say "Thank you!!" :) - OscarRyz
[0] [2009-02-23 04:05:45] Jack BeNimble

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.

(1) 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
(1) 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
[0] [2009-02-23 04:54:14] Earlz

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

[0] [2009-02-18 22:05:45] digiarnie

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.

[0] [2009-02-25 11:04:14] 13ren

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.

[0] [2009-02-25 12:29:42] ya23

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.

[0] [2009-02-25 12:41:18] MadKeithV

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

[0] [2009-02-25 12:55:01] BigJump

E = mc2 baby!


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

[0] [2009-02-25 23:33:54] Aaron Daniels

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

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


[0] [2009-02-26 05:48:03] 13ren

Elegant solutions, workmanlike code.

[0] [2009-02-24 22:23:40] MicSim

Googling for "elegant code" I found here [1] 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."


[0] [2009-02-24 21:55:22] Joshua

Beautiful Code [1] has a number of examples of elegant code.


[0] [2009-02-24 22:09:23] Scott

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.

[0] [2009-02-24 22:17:38] John

Code is to elegant code what prose is to poetry.

[0] [2010-04-19 23:22:46] Nikhil

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 [1].

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.


[0] [2010-06-14 18:09:59] Thorbjørn Ravn Andersen

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

[0] [2010-06-14 18:17:13] Christopher Hein

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.

[0] [2010-06-14 18:19:45] Viktor Sehr

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

[0] [2009-03-11 12:13:56] Sung

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.

(1) I think elegant code has to be better than human-readable. It has to appeal to humans as well. - Adrian McCarthy
[0] [2009-03-11 12:43:50] Kev

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. [1]


[0] [2009-03-11 12:45:00] Rubendv

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

[0] [2009-08-02 02:02:15] Alix Axel

I believe that elegant code or "girl code" as some like to call it can be measured, to some extent, with cyclomatic complexity [1] - 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.


[0] [2009-02-26 06:52:33] Guffa

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.

[0] [2009-02-26 17:58:59] Joel Coehoorn

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.

[0] [2009-02-26 18:11:07] flussence

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

[0] [2009-02-27 00:18:51] Avram

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.

[0] [2009-02-26 06:16:43] Strilanc

{Speed, Size, Readability} Pick Three.

(not two)

[0] [2009-02-25 13:40:36] Sharique

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

[0] [2010-09-02 15:30:33] Adrian McCarthy

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.

I wouldn't always state that elegant code needs to hav e_all_ redundancy factored out (I too often fell in that trap when doing Java in the past: making a wholesome bloated class hierarchy that 'magically' did stuff somehow through baseclasses and virtual methods all but to avoid redundancy; The end result of that idea appears to me to be less elegant sometimes than just rewriting some of it. I guess I am concluding that you need to factor out all redundancy while keeping with the class responsability (the flip side of base classes not PullingTheirWeight antipattern) - sehe
[-1] [2009-03-06 20:54:39] Omar Abid

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

[-1] [2010-09-02 15:00:43] shamittomar

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

[-2] [2009-02-27 22:49:06] leppie


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