views:

1558

answers:

29

For anyone that is passionate about software development, I'm of the opinion that you should always strive to write beautiful code; however, is there a clear definition of what beautiful code really is?

On one hand, I see elegant code being something that's easy to read while simultaneously solving the problem at hand in the most efficient way possible. It seems like readable code often comes at the expense of, for example, creating several new variables in order to represent the data with which you're working. Depending on your platform (or depending on how picky you are), creating these variables could be considered to be a performance hit.

On the other hand, this brings up another perspective that I've often seen that defines beautiful code as code that succinctly and efficiently solves the given problem. It can be argued, though, that succinct code may come at the sake of readability and thus ultimately detracts from the attractiveness of the code.

I personally want to be able to write expressive, effective, and elegant code, but I often find myself debating if adding a couple of more variables to improve the readability of the code three months later really does improve (or pollute) the code.

+3  A: 
  1. Reusable
  2. Self-Documenting
N8g
+1  A: 

The least amount of code possible to fulfill a requirement.

John Sheehan
+15  A: 

art is subjective :)

I like code that is

  • succinct
  • well laid out
  • readable and self documenting
  • makes me smile when all the above become apparent

Clever code is often ugly so when clever code is beautiful that's where the masterpieces are hidden.

sparkes
Art is partially objective as well. Otherwise you wouldn't have the nearly universal agreement that the Mona Lisa is art and a solid blue canvas is not. Hence, the fact programming is both art and science: that would imply that a significant amount of criteria for code beauty is actually objective. But that doesn't mean this criteria isn't incredibly complex. Philosophy aside: I generally agree with your criteria :-)
Ryan Delucchi
Art is maybe partially objective, but "good art" is definitely subjective. Regarding blue canvas, see : "Suprematist Composition : White on White" by Kazimir Malevich http://www.moma.org/collection/browse_results.php?object_id=80385, worth thousands of dollar ...
Brann
+2  A: 

This is a difficult question to answer, because there are many qualtiy attibutes of code that could make it "beautiful". To make it more difficult, some of the quality attributes conflict. For example, if I need to make a piece of code execute an algorithm that uses as little memory as possible because I am running on an embedded device that has very little, then that code might not be as resusable, or readable, or maintainable as the same algorithm that doesn't have this requirement.

With this in mind, my definition of beautiful code is any code that does the job inteneded, and fulfills all the quality attributes it is required to fulfill.

Craig H
+45  A: 

Beautiful code is like obscenity. You know it when you see it. Here's some things that might be beautiful:

  1. The abstractions snap together perfectly. There is very little leakage. The code reads like English. The data structures and/or objects fits the problem perfectly. Everything goes in and out of procedures and functions with minimal fuss.
  2. You can use a beautiful API based on intuition. You almost know what to type without even looking it up because of some inner structure to the API.
  3. Each line of code is elegant in that it performs seemingly complicated operations with amazing simplicity and very succinctly while simultaneously appearing bulletproof (by assuming nothing)
lbrandy
+1 for #2, I agree with the others as well
Shadow
This is spot on. Kudos.
Ryan Delucchi
A really old thread, but "Beautiful code is like obscenity. You know it when you see it." is a good one! +1.
GmonC
+1  A: 

This is a very subjective area. My opinion is that it means:

code that succinctly and efficiently solves the problem.

While something like

for word in words:
    if word == word_to_check:
        new_words.append(word)

works,

new_words = [word for word in words if word == word_to_check]

looks much more beautiful to my eyes.

mk
A: 

Some very beautiful code

On a serious note code that doesn't take >5 minutes to comprehend is good enough for me. I'm also an overuser of whitespace (braces on new lines, breaks before and after if/loop blocks etc.) so that would probably factor into how attractive I find someone's code.

Ross
That picture is great. Made me smile.
pi
+3  A: 

All of the 'beautiful' code (as subjective as the interpretation is) I've encountered generally is:

  • Easy to read
    • Variables and functions are named so that comments are rarely needed to understand most logic/flow
    • Appropriate whitespace and comments only when needed
  • Minimalist
    • Solves the problem, and nothing more
  • Standard
    • If there is a coding-style to the entire codebase, it should follow it
    • Should in implementation adhere to if possible a recognized language/syntax standard, even if it is not internationally recognized
Chris
@Minimalist: In many cases in math and programming solving more generic problem that covers specific problem is beautiful.
alpav
+3  A: 
  • Well formatted with white space.
  • Consistent naming and formatting.
  • Simplest possible solution.
  • Loosely coupled code.
  • Well named & self documented identifiers.
  • Effectively meets requirements.
Jim McKeeth
+3  A: 

I think truly elegant code derives from:

  • Terseness - The least code possible

  • No repetition (within reason) - This one is obvious.

  • A simple and clear API - You should be able to clearly understand what a method does purely by its name, return value and arguments.

  • Good names for things - Objects should bear the name of their intent.

  • Readability - You should be able to read the code reasonably easily, although I dislike the concept that you should sacrifice power and terseness for readability (e.g. some companies don't like ternary expressions due to readability)

  • Consistency - The code should follow a consistent underlying pattern and style. I don't want one execution path to go a completely different route to another similar execution path. They should share as much code as possible.

Quibblesome
Some companies dislike ternary expressions, side effects (++) and so on, because they are often incorrectly modified during maintenance. Not just a matter of opinion, this is measurable. If it doesn't happen in your environment, fine. But be aware many experts avoid them (e.g. Code Complete)
MarkJ
Aye but it's not particulary fair because you can't measure the benefits of a piece of code occupying 1 line as opposed to 3. I would assume that people make equivalent mistakes due to the fact that the code was larger than would fit within a method and they missed a bit.
Quibblesome
A: 

Ultimately I think the most important thing is maintainable code, while keeping the solution efficient. Sometimes that may be beautiful, but most of the time it just "looks good".

Adding variables or white space to improve readability or maintainability is better in the long run.

bruceatk
+11  A: 

O'Reilly actually published a book called "Beautiful Code" in which every chapter was written by a different programmer. Each author explains what beautiful code means to them and there are lots of examples. Some of the authors are quite famous; Matz (the creator of Ruby) wrote one of the chapters.

You can find the book here: http://oreilly.com/catalog/9780596510046/

Eli Courtwright
This book is great. It really changed how I think about code and aesthetics.
Jason Orendorff
+5  A: 

I like to think of code like diamonds, in diamonds there are four C's

Carats Clarity Color Cut

For Carats it's how SMALL is the code, less lines is less to read, maintain and directly relates to the number of bugs.

Clarity, how easy and simple is it to read, is there more then three levels of indentation, are the functions clean and compact?

Color or style, that can be very subjective. but there are things that are pleasing to the eye, like whitespace.

Cut is the bigger picture, how well was the whole system put together, and like it diamonds can be more important then the rest.

Jon Clegg
You might want to edit carrots -> carats. "Carrots" confuses a non-native English speaker like me...
Antti Rasinen
+11  A: 

The Editor stands open and empty, a vast field of white marred only by the thin blinking cursor. It is beautiful.

The Programmer sits quietly, motionless save for the finger of one hand tapping the desk. In his mind, ideas whirl and twist, designs grow from them, composed as if of their own will, and are as quickly rent asunder. Something begins to take shape behind the half-closed eyes. It is beautiful.

A keypress. And another. Like the ringing of a hammer on the nails of a coffin. The wondrous visage is carved into code, clumsy symbols replacing concepts, crude scrawls on the cave walls. Beauty is absent.

A Reader gazes, tombstone glyphs spark imagination, a window opens onto the mind of the Programmer. And the code is beautiful.

Shog9
+4  A: 

As code spends more time in maintenance development, the most beautiful code is the code that is will be understood by your successor in the shortest amount of time ...which might even be you + 1 year in time

I like to take a pragmatic approach to coding you see

ArjanZuidhof
+1  A: 
  1. Correct spelling
  2. Less is more (when possible)
  3. descriptive
  4. only enough comments as required
  5. nice spacing and indenting (but not too much)
  6. clear, concise and easy to understand
jonezy
+1  A: 

beautiful code = profitable code *

This means that your code made money, for example by automating a previously manual process, adding a feature that makes more people buy your product, or fixing a bug that was making people not buy your product. Call the amount of money generated by your code "R".

Furthermore, R must be greater than what you were paid to write it, "C0". Also, if your code requires modification in the future, the cost of revisions "Cn" must not exceed "R".

profitability = R - C0 - {C1 + C2 + C3...}

Code is beautiful when there is nothing else you can do to it that will increase profitability.

Full disclosure: I'm writing a book with this title, so this post is mildly self-serving. But I do fundamentally believe that the mark of an exceptional software engineer is that they understand and obey these simple economics of coding.


*Note: this only applies to professional developers. If you are writing code for the sciences, academia, open-source, or a hobby this doesn't apply.

Portman
So open source software is not beautiful? There are professional developers that work on open source for a living.
grom
Beautiful code is not always profitable, and profitable code is not always beautiful.
Brad Gilbert
Hm. You got slammed a little bit, but I think the points are pretty good ones. I have seen some UGLY but profitable code. And I have seen beautiful code that doesn't make a nickel. While I think your book may be interesting, I think there will be some people who find it too materialistic a topic.
Pete
@Pete: The funny thing is that this response was +3 earlier in the beta. Definitely a polarizing position, I realize.
Portman
This is very much like saying "The most beautiful thing about a tree is what you can do with it after you chop it down." I think I see what your point is, but it doesn't really have anything to do with beauty.
Jason Orendorff
A: 

Beautiful code is (to me) code that is efficient, effective and elegant.

Readability is an important code attribute but it can come as a cost to elegance and efficiency, without even going into what counts as readable. As such, I don't necessarily regard readability into beauty, although it is still an important consideration to code in general.

workmad3
A: 

Duh! WTFs per minute. Everyone knows this.

mislav
Heh, nice. I think you mean the inverse of WTFs per minute. :-)
Ryan McGeary
That would be minutes per WTF. Which makes sense.
Peter Wone
+1  A: 

Here's a link to a keynote by Marcel Molina at Ruby Hoedown 2007 in which he talks about what makes code beautiful:

http://rubyhoedown2007.confreaks.com/session09.html

Phillip Koebbe
+2  A: 

Beautiful code is well-tested code

The simplest thing that works is beautiful. The only way to know if your code lacks unnecessary cruft is to write tests that express the behavior and then only write as much code as needed to make those tests pass.

Code is organic. For any long-lived project, code needs to be continually sculpted. Readability and simplicity play a role in making this feasible, but nothing makes refactoring more pleasant than by having the confidence to make sweeping changes while trusting that your tests will cover your ass.

In addition, if your code makes you happy, you're probably moving in the right direction. Happiness often motivates, and motivation is pivotal towards programming efficiently and effectively. This plays a role in the overall cost of your code as well. When your motivated, you accomplish tasks much quicker and avoid procrastination or analysis paralysis.

So, in summary, if it took you a short amount of time to write, costs little to maintain, causes little grief when changes are made, and is enjoyable to work on, your code is probably on the correct side of the beauty spectrum.

("well-tested" implies having automated tests and is comprised of a combination of things including test-coverage, test-declarativeness, test-effectiveness, etc.)

Ryan McGeary
I'd like to note that a good type system (such as Haskell's, but not Java's) can replace a lot of tests, and do a better job (because it's a proof that the code is correct, rather than a failed proof of the presence of bugs).
Curt Sampson
Curt, I could probably argue against being able to replace a lot of tests, but Haskell is still on my list of languages to learn, so I'll instead just give it the nod. Intrigued, thanks.
Ryan McGeary
A: 

Code that makes it easy to get things done. Code that when you see it and understands how/why it works, reminds you of why you first got into writing code in the first place.

+2  A: 

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

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

Beauty can be 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.

You should take pride in the appearance of your code. But I think words like clarity and readability are better touchstones than beauty. You can measure them - ask programmers to read code, and then test their understanding by asking questions. And that's why many experts avoid side effects and ternary expressions - because they are often incorrectly modified.

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

EDIT: This fantastic answer by Eric Lippert illustrates my point far better than I ever could.

MarkJ
I love that Kernighan quote. Always have. Mostly I see my code from 12ths ago and thick, "ick" but sometimes it's clear and simple and succinct yet powerful, it's obvious how to easily extend it in profound ways, and I wish I were as smart as the bloke who wrote it. THAT is beautiful code.
Peter Wone
A: 

Here is a very good 45 minute presentation video on beautiful code. Enjoy.

Geo
A: 

Beauty is certain intertwined with readability to a great degree. However readability to a very large degree, and beauty to a somewhat lesser one, are always seen from a particular viewpoint. Code that's quite readable to an experienced programmer, familiar with the domain, who's worked on that type of project for a long time can seem unreadable to someone without that background. And code more readable to someone without that background becomes less readable to someone with it due to the extra verbosity, missing conventions, and so on.

Curt Sampson
A: 

Many answers here say beautiful code is easy to understand, and that can be true.

However, code that is hard to understand can also be beautiful. One of the most beautiful programs I've ever read is this Obfuscated C Contest entry: august.c. If you know C, take the time to insert the whitespace and figure out what that program does. You'll never forget it.

Efficiency, correctness, and clarity are all virtues in code. Beauty and virtue are not the same thing though.

Jason Orendorff
A: 

Beautiful code is code that you want to own and support for the rest of your life.

alpav
A: 

To quote Michael Feathers:

"I could list all of the qualities that I notice in clean code, but there is one overarching quality that leads to all of them. Clean code always looks like it was written by someone who cares. There is nothing obvious that you can do to make it better. All of those things were thought about by the code’s author, and if you try to imagine improvements, you are led back to where you are, sitting in appreciation of the code someone left for you—code written by someone who cares deeply about the craft."

Jordão
A: 

I wrote a blog post on what I think constitutes beautiful code - it's something good programmers are constantly working at. Writing beautiful code is an art and like all artists as one grows older ones definition morphs... I think beautiful code like good writing has certain core characteristics - communication of the authors intent is the primary one. The elegance of the writing, the grammar, etc are other facets.

Nikhil