Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Possible Duplicate:
What does it mean to write “good code”?

In a discussion on coding quality, and how you identify it, I came across a discussion on testing people's coding ability by getting them to show how they would swap two values using a piece of code to achieve the objective. Two key solutions were produced:

  1. Introduce a spare variable to do some pass the parcel of the values or:
  2. Use some bitwise operators.

There then ensued an argument on which was in fact the better solution (I'd be leaning towards the first option while being aware that the second one exists, but may not always evaluate as expected depending on the values in question).

Bearing in mind the story of Mel the Real Programmer, I am interested in knowning how you evaluate code as being elegant or not, and is succinctness a key feature of elegant code.

share|improve this question
add comment

marked as duplicate by Macneil, Walter, Michael K, Tim Post, Mark Trapp Aug 4 '11 at 2:35

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

22 Answers

up vote 69 down vote accepted

Good code should be clean, simple and easy to understand first of all. The simpler and cleaner it is, the less the chance of bugs slipping in. As Saint-Exupery coined, "Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away."

Moreover, elegant code is usually the result of careful analysis of the problem, and finding an algorithm and design which simplifies the code greatly (and often speeds it up too). E.g. Programming Pearls shows several examples where an insight gained during analysis gave a totally different angle of attack, resulting in a very simple, elegant and short solution.

Showing how clever the author is, only comes after these ;-) Performance micro-optimization (like using the bitwise operations you mention) should be used only when one can prove (with concrete measurements) that the piece of code in question is the bottleneck, and that the change actually improves performance (I have seen examples to the contrary).

share|improve this answer
5  
Not to mention if you are going to do something clever it should be WELL documented. 2 Years from now you are probably not going to be around to ask questions of or at least you should not have to answer questions about your old code. –  Chad Aug 2 '11 at 16:29
2  
Rei, I disagree, or maybe it's that I want this to be the answer when for many other people it is not. Ultimately, I have a concern with people describing code as elegant when really all it is is code that is too clever and exclusionary. –  temptar Aug 3 '11 at 13:36
1  
@temptar Good code and elegant code are two different things. Elegant code can be impossible to read (x ^= y ^= x ^= y) or extremely inefficient (purely functional quicksort). To speak of the two as the same is not only imprecise, it encourages elegance when there are more important values in question. –  Rei Miyasaka Aug 3 '11 at 21:05
1  
Rei -- I think you have it exactly backwards. Readability is a requirement of elegance. –  Nick Hodges Aug 3 '11 at 22:30
show 7 more comments

Elegant code is a combination of:

  • Correctness. IMHO no wrong code can truly be elegant.
  • Succinctness. Less code means less to go wrong, less to understand*.
  • Readability. The easier it is to understand code, the easier to maintain.
  • Performance. To a point. Prematurely pessimized code cannot truly be elegant.
  • Following the established standards of the platform or project. When given two equally elegant options, the one that is closest to the established standard is the best.
  • Exactly the way I would do it. Okay, I'm joking, but it's easy to label code that is NOT how you would do it as "inelegant". Please don't do that - keep an open mind to different code.

Of course, there's also the all-too-often true adage: "To every problem there is a solution that is simple, elegant, and wrong".

*As the comments below show, there is some contention on shorter code. "Succinct" does not mean "in as few characters as possible", it means "Briefly and clearly expressed.".

share|improve this answer
5  
+1 for "simple, elegant, and wrong": I've seen a few of those! However I'd say Readability far outweighs Succinctness. –  AAT Aug 2 '11 at 16:29
13  
My only concern is with succinct. To many developers think that Code Golf is good programming. It is not. A single line with one object and 15 method calls is confusing and hard to read or follow. –  Chad Aug 2 '11 at 16:32
2  
I don't think he meant to define it as "less lines", that was just an example. Obviously something that is squished into a single line (when it shouldn't be) isn't succinct –  user606723 Aug 2 '11 at 17:43
1  
I love the phrase prematurely pessimized! –  HLGEM Aug 2 '11 at 18:14
1  
@Chad (and IAbstract) - in my experience it's a difficult and precarious balance between succinct and readable. I would put them equal because readability can depend on the ability level of the person reading the code, which means that sometimes there may be a more "readable" solution for that particular level which is strictly less elegant overall than a more succinct solution that requires more in-depth knowledge of the language or platform. –  Joris Timmermans Aug 3 '11 at 7:31
show 5 more comments

Simple code is code that's so readable that even novice programmers can work out (at least generally) what the code is doing. (See: Ruby expression syntax)

Impressively complex code is code that does as much as possible in as few lines as possible, without real regard to readability (See: Perl)

Elegant code is code that makes other developers say "Oh man, why didn't I think of that?!" It's sort of in between the first two, with code that may not be so readily apparent that your parents can read it, but not some arcane scrawling that requires a codex to interpret. It does the job, does it well, and doesn't leave the people maintaining the code scratching their heads.

share|improve this answer
add comment

Fred Brooks breaks the complexity of a solution down into the categories of "essential complexity" and "accidental complexity". Perfectly elegant code, to me, is that which is all "essential complexity", and no "accidental complexity". The trick is, different programmers will have different ideas about what's "complex", so we're likely to disagree on whether a bit of code is elegant.

For example, I find the structure of Lisp code to be significantly more elegant than the structure of code in C-like languages. On the other hand, Lisp's prefix notation and explicit parse-tree construction violate our intuition about how mathematical expressions should look, which can make reading lisp code more difficult for people. As a result many programmers consider all those parentheses in Lisp not to be "elegant" at all, but in fact rather ugly. To someone who's really concerned about how the compiler will interpret the code, Lisp can seem elegant. To someone who's more concerned about how people will interpret the code, Lisp can seem ugly.

share|improve this answer
show 4 more comments

Succinctness is an important component, but for me, in order to be called elegant, code must also be easily understandable to the point that you say, "Of course that's the obvious way to do it!" Even if paradoxically it's not the first way you thought of. If it doesn't pass that test, it can be called "clever" or "efficient," but not elegant.

share|improve this answer
add comment

It is similar to poetry, which is elegant language.

Poets can say in very few words what it would take others pages, and pages, to say and not as well. Elegant coders can do the same with code.

A typical example is comparing a typical implementation of quicksort in C with quicksort in Haskell:

quicksort :: Ord a => [a] -> [a]
quicksort []     = []
quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater)
    where
        lesser  = filter (< p) xs
        greater = filter (>= p) 

(lesser and greater can be inlined for a three line solution).

share|improve this answer
2  
@poke, some are better than others, even poets. –  user1249 Aug 3 '11 at 9:23
show 3 more comments

The XOR swap is quite well known. And everybody, who has at least a bit of the humility Dijkstra called for will tell you, it's the wrong way to do things. Not only is it harder to read for humans, but also for compilers. Compilers are relatively good at flow analysis and register allocation and all sorts of things. Having a good compiler, you cannot expect, that every variable you create will actually exist on the stack/in a register at any point in time. What you need to do is to express things clearly. In a language that supports call by reference, this is the way to go: swap(x, y);.
This is the best solution (I dare say so, at least given the alternatives you provided). It is one statement and it is self-explanatory. It doesn't use voodoo as the XOR swap does. It doesn't introduce the noise of a temporary variable and 3 assignment statements. That's something that happens within swap. Assuming it is a function, a decent compiler will inline this call. You could also make it a macro. Whatever.

What makes code truly elegant is the lack of redundancies, is orthogonality, is simplicity. It ensures robust systems that grow on top of each-other. Having reoccurring statement-groups all over the place any time you want a swap introduces redundancy, lacks orthogonality and fails simplicity.

share|improve this answer
show 3 more comments

It's easy to spot what elegant code does. You get the, "Why didn't I think of that?" vibe. This relative to how complex the problem and the language being used.

This does not mean that the best or simplest solution is automatically elegant. Simple is often one of its qualities. Modifications, although usually easier, don't always maintain the elagance.

share|improve this answer
show 1 more comment

Good is the absence of Bad. It applies to everything in life and code is no exception. Thus,

Good code is one that doesn't have a smell! So, it is important for you to see and understand what a code smell is. No joke intended.

Think about it. You say you are happy only because you are NOT sad or have got ridden of your sadness. Likewise, you call something a good code, when you don't see anything bad in the code. Every quality aspect of code (maintainability, readability, etc) can be attained by getting rid of code smell. And believe it or not this doesn't happen the very first time - it happens iteratively :)

share|improve this answer
add comment

I like to compare code with print media here.

You know you hate it when you read oversimplified articles. Dumbed down. Few facts, simple sentences. This translates to code that I link to beginners: Trivial, naive even, implementation, nothing is too complicated, but it's lengthy and full of unnecessary steps.

On the other hand you know this ivory tower style. You read a book from well-known philosophers. You read a science paper on a complicated matter: The style often seems to be very lengthy. Words are not reused, you have to show off that you can know a dozen synonyms. While the actual content might be pure, good, interesting - the style of writing makes it hard to follow. This style blurs the original line of thoughts. This is clever code.

Elegant code is somewhere in the middle and just as subjective as preferences can be. You can spot and describe bad cases easily, but perfection is different for most of us.

share|improve this answer
add comment

My definition is simple unfortunately you can't determine (all of) it yourself.

Elegant Code has the following features:

  • It solves the problem.
  • I can trust the tests such that if I modify any behavior, a test will break.
  • When I or +any other developer+ open the code, it is immediately easy to follow. Any non-trivial logic blocks are described by a comment.
  • Simple things are simple, hard things are possible.
  • Someone else is +willing+ to take over development of the code even though I am still there. Without being forced.
share|improve this answer
add comment

How easily can most developers read it? How easy is it to change?

As a result, I would definitely agree with you that opton 1 is significantly more elegant.

Option 2 is clever and shows a good knowledge of operators. It also saves a very small piece of memory. Useful, perhaps, in exceptional cases, and well worth a developer being able to do. But not in your average 99% case.

share|improve this answer
add comment

It had to be consistent. There had to be some kind of pattern in it. And when you do need to break that pattern, break it in a consistent way, so that overall there is still some kind of pattern in it.

If someone points to your code and ask you why are you doing it this way, and your answer is "I don't know, i'm just doing it this way because that's how i've been taught / because that's just how everyone else is doing" then that code can either be elegant or not elegant. However if you can explain why the code is that way, why had you chosen to code it that way, why are the other alternatives not as appealing, then you can be sure that the code is elegant.

share|improve this answer
add comment

I was blasé in my comment at the top, but for me elegant code is that which affects my senses much more than most.

It produces a positive reaction in achieving objectives while being short and to the point, simplicity but with purpose and power, stylish, symmetric and a little 'outside the box' in approach. It incurs an element of surprise. The method and the algorithm are not so complex (at least superficially) as to get in the way of it's understanding.

Elegant code is more than the sum of its parts. Sometimes elegant code seems almost to work with the data, to bend with it, instead of using brute force or mapping the data into another form. For me, elegance often comes in a self contained package - a single function, few or no external calls, neither too long nor too short.

By example, I have seen sorting methods I would call elegant. And elegant code/algorithms to draw fractals in unusual but highly efficient ways - combining visual beauty and coding elegance!

share|improve this answer
add comment

Elegant code uses cleverness to accomplish something in much less code than most people would think possible, but in a way that's readable and obvious-in-hindsight and doesn't look like code golf.

share|improve this answer
add comment

Personally I find elegant code to be overrated. But I work in the database world where performant code is of critical importance and "elegant" code in the context of SQL code more often than not (at least in my experience) performs badly. I cringe every time I hear someone who wants to write elegant SQL code.

In general though, I still think striving for elegance is ridiculous. In the first place no one can properly define it. What you want is code that works correctly, performs well, is maintainable and then elegant is a far distant fourth if it even makes the list.

share|improve this answer
show 1 more comment

Elegant code is not the same as elegant design although there is a cross over between the 2.

How do you define an elegant painting? It's beautiful to look at, perfectly readable, makes perfect sense is easily maintainable and just does the job.

Elegant design assists in elegant code. You can't have elegant code without good design but you can have ugly code with good design. Much better to write if can_can_add_apples_to_my_basket(20) then add_apples_to_basket(20) else render_not_enough_room_to_add_apples(20) end then write the 2 if conditions which would potentially be re usable wherever you needed them for whatever you needed them for (that's the design bit)

code that sais if b.count + 20 <= b.max then b += 20 else raise("too many apples") end

You still have the 2 methods (count and max) so you still have good design but the code is ugly and meaningless, difficult to maintain without knowledge of the system and totally ambiguous

share|improve this answer
add comment

To be honest, there is rarely a good reason to swap the value of two variables, and it isn't really an "elegant" thing to do, no matter how you do it.

Elegant code isn't about the code in and of itself, it's really about what the code does and how it does it. I personally think that this is a bad example for determining what "elegant code" is, since the thing being done is not itself elegant. I find Haskell code to be typically elegant, because it (for the most part) deals with immutable values. However, algorithms utilizing mutable state can indeed be written elegantly as well (and usually don't look so hot in Haskell).

share|improve this answer
add comment

It really depends on who you ask. Someone coming from a mathematical background will often prefer code a seasoned programmer may find problematic. This makes it seem very subjective.

Additionally, you'll find that different languages have different ways to solve the same problem. In Python, for example, swapping two variables is trivial: x, y = y, x

In practice, most programmers would agree that there are some common criteria:

  • elegant code must be as short as possible
  • but as verbose as necessary
  • it should be easy to follow
  • each statement should be easy to understand
  • no statement should seem redundant or superfluous
  • the code should follow the idioms of the language
  • it mustn't make use of leaky abstractions

This is a very pragmatic view of elegance. Code mustn't be "clever" or it fails these criteria. But it will be maintainable and easier to adjust and extend.

That said, there is code that can be a work of art despite absolutely failing by most of the rules in this list. "Clever" code often falls in this category. It is very dense, often relies on a thorough understanding of the underlying implementations (say, memory management, or the exact implementation of the compiler) but nevertheless evokes a sublime fascination.

There is a difference between the elegance you would find in Yet Another Perl Hacker scripts versus code you would actually want to use in production. This is the reason why you'd never want Mel to be in your team even though you could call his major opus elegant.

share|improve this answer
add comment

Understanding elegant code should be like solving a puzzle. It should be difficult to understand at first, then very easy to understand once you have "got it".

There's a trade-off - people who don't understand it are left scratching their heads, while people who do understand it find it obvious, in retrospect.

As for swapping variables, neither will be particularly elegant. There's no complexity to tame here, so there's no scope for an "elegant" solution.

share|improve this answer
add comment

Elegance is the minimization of complexity. If you can quickly hand the code off to another programmer with reasonable skills and they are able to continue the work (and hopefully live up to its initial standard) then the code is likely elegant.

Well-written software should stay around for at least ten years. The initial elegance may get scared by later hacks, but the length of time code survives is often a reasonable metric of how well it was initially written. Poorly written code either goes stagnant (and people hack around it), or gets re-worked (although in practice I've seen people replace elegant code with lesser solutions because they failed to look at it carefully).

share|improve this answer
add comment
isElegant(code)
{
  return isSimple(code) && isReadable(code) && code.reducesComplexity();
}
share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.