69

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.

0

22 Answers 22

78

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

12
  • 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. Commented Aug 2, 2011 at 16:29
  • -1 to both this and the other popular answer. They describe good code, not elegant code. They aren't answering the question. Commented Aug 3, 2011 at 5:21
  • 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
    Commented Aug 3, 2011 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. Commented Aug 3, 2011 at 21:05
  • 3
    Rei -- I think you have it exactly backwards. Readability is a requirement of elegance. Commented Aug 3, 2011 at 22:30
47

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

9
  • 7
    +1 for "simple, elegant, and wrong": I've seen a few of those! However I'd say Readability far outweighs Succinctness.
    – AAT
    Commented Aug 2, 2011 at 16:29
  • 17
    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. Commented Aug 2, 2011 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
    Commented Aug 2, 2011 at 17:43
  • 1
    I love the phrase prematurely pessimized!
    – HLGEM
    Commented Aug 2, 2011 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. Commented Aug 3, 2011 at 7:31
29

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.

14

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.

4
  • I like this answer and I have to confess the discussion of elegance between languages had not occurred to me when I asked this question - I was concentrating more on equivalent solutions for a problem all written in the same language.
    – temptar
    Commented Aug 3, 2011 at 13:42
  • parens are just superficial syntax; solution elegance tends to be high in lisp. reading lisp is a lot like reading math. Commented Aug 3, 2011 at 14:39
  • @Dustin - I suggest you read the lisp for Emacs's ruby-mode - in particular, the ruby-calculate-indent function. There's nothing about lisp that enforces high solution elegance, except that more novice developers tend to be turned away by all the parentheses. Commented Aug 3, 2011 at 15:25
  • @temptar - see my comment to your question. The overall point I'm trying to make is that there's no objective standard of elegance, and it's hard to come up with universal traits that describe code commonly thought to be elegant. Here, I'm trying to describe what I think causes the subjective feeling that code (or anything else, really) is elegant. Commented Aug 3, 2011 at 15:42
11

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.

11

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

4
  • There are a lot of poets that beat around the bush though, and end up saying nothing.. But I agree that functional languages often have some very elegant solutions!
    – poke
    Commented Aug 3, 2011 at 9:20
  • 2
    @poke, some are better than others, even poets.
    – user1249
    Commented Aug 3, 2011 at 9:23
  • @Thorbjørn - It's not just about saying more with less - it's about saying something most effectively. The opening of Joyce's The Portrait of an Artist as a Young Man is a huge, stream-of-consciousness run-on sentence, whose tone changes as the author progresses through life. It uses a lot of pages to express that idea very effectively. In code, I'd consider people.sc.fsu.edu/~jburkardt/c_src/pig_latin/pig_latin.c to very elegantly solve the problem it's trying to solve: to create an amusing source-representation of an English-to-pig-latin program. Commented Aug 3, 2011 at 15:51
  • An issue I see with this example is that the Haskell code, while expressing a similar concept, is actually doing something entirely different, with different performance characteristics and semantics from the usual C versions. I don't mean to deride the elegance of the Haskell code; it is just important when comparing to be aware of when once piece of code is sacrificing performance or some other value to achieve its elegance. Commented Aug 3, 2011 at 22:08
7

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.

3
  • I know about the XOR swap - obviously. I also know that some people think it is an elegant solution; others don't agree. Ultimately I used this as an example of a solution whose elegance is disputed to some extent for the wider question of how do we recognise elegant code.
    – temptar
    Commented Aug 3, 2011 at 13:39
  • @temptar: You asked for a definition of elegance. I gave you one, which includes simplicity, i.e. the code being self-explanatory. Based on that, the XOR swap is not the least bit elegant. It is clever. In fact every hack, every quickfix and every other trick requires a lot of cleverness. But that doesn't make it elegant. Elegance is effortless and beautiful even in the eye of a moron. Elegance: The beauty of an idea characterized by minimalism and intuitiveness while preserving exactness and precision (http://en.wiktionary.org/wiki/elegance).
    – back2dos
    Commented Aug 3, 2011 at 13:59
  • I agree with you - note I said I would lean away from it as an elegant solution myself. I used it and the alternative of an example of why I felt that the definition of elegant was subjective and I was interested to see how other people would evaluate code as elegant or not.
    – temptar
    Commented Aug 3, 2011 at 14:02
4

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.

1
  • In principle I would agree with this. I also wonder how much elegance is linked to a style and when the code is maintained by a different programmer, this causes the drop off in elegance.
    – temptar
    Commented Aug 3, 2011 at 13:43
2

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

2

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.

2

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

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

0

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.

0

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.

0

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!

0

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.

0

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.

1
  • -1 Your argument in the first paragraph isn't really an argument against elegant code, but an argument against the tool you are using (i.e. SQL) Elegant code is always correct and maintainable (which are most important), and if the tools provide the proper abstractions it also performs well. So in essence if you strive for elegance you strive for all of the facts above. Commented Aug 3, 2011 at 9:19
0

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

0

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

0

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.

1
  • What if the idioms of the language are inelegant? Commented Jan 27, 2016 at 14:10
0

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.

-2
isElegant(code)
{
  return isSimple(code) && isReadable(code) && code.reducesComplexity();
}

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