I was thrilled to see the book Beautiful Code: Leading Programmers Explain How They Think show up in my Amazon recommendations. It seems like exactly the type of book I would enjoy. So of course I bought a copy.
Unfortunately, Beautiful Code wasn't nearly as enjoyable of a read as I had hoped it would be. It is by no means a bad book, but there's something about it that's not quite right.
Part of the problem is that it's a compilation of disconnected essays, much like The Best Software Writing I. Because there are thirty-three different authors, there's naturally going to be a lot of variance in tone, content, and quality. How you feel about the book is largely dicated by how much you like the individual essays. There's certainly no lack of quality in the authors. There are plenty of famous, highly regarded programmers represented here: Brian Kernighan, Yukihiro Matsumoto, Jon Bentley, Charles Petzold, and many others.
Despite all that, I loved The Best Software Writing; why can't I love Beautiful Code? I wasn't able to put my finger on exactly what the deeper problem was with Beautiful Code until I read this eloquent reader review from Dmitry Dvoinikov. I suddenly realized what ultimately trips up Beautiful Code. It was right there in front of me, all along. It's even in the title: Code.
With rare exception, the authors don't even mention the word "beautiful" in their essays. They allude with "There, we have this system, it works like this." What exactly the author finds beautiful about it, and why, remains a secret.The chapter written by Yukihiro Matsumoto, the creator of Ruby, was the most impressive standout. It is three pages in which he simply writes about what he believes beautiful code is. He explains his understanding of beautiful code to you. This is what the book should be!
Instead, many chapters just reprint a few pages of code and conclude - see, it is beautiful!
Many times I was unable to grasp the problem - what was it that required that so-called beauty to emerge? I couldn't see the whole picture, but the authors presume I do. Any possible appreciation of beauty requires deep understanding. What if I show you a magnified fragment of Mona Lisa's background, an area of 3x3 blackish pixels? No doubt Leonardo had to paint them too. But where is the beauty?
Only a few authors were wise enough to use pseudocode, something that anyone can read, no matter from which camp. It's just weird when the authors present their beatiful code in Ruby or Perl or Lisp. Look, I haven't touched Ruby yet, I hate Perl and I can't imagine using Lisp in practice. Nevertheless the authors repeatedly say something like "It's easy, I'll show you, this bracket does this and that character does something else. Now do you see how beautiful it is?" They literally show you a piece of poetry in a foreign language and ask you to appreciate it.
A classical example of awful poetry in Russian is (transliterated)
Ya poet, zovus' Neznajka,
ot menya vam balalajka.Can you tell whether this is good or bad and why? What if I told you it's beautiful? Would you believe? Does it appeal to your sense of beauty?
Ideas are beautiful. Algorithms are beautiful. Well executed ideas and algorithms are even more beautiful. But the code itself is not beautiful. The beauty of code lies in the architecture, the ideas, the grander algorithms and strategies that code represents. The code samples presented are indeed clear, readable, and well written. But they are weak evidence of beauty; it's not the language that is inherently beautiful. Barroom doggerel expressed in French or Russian is never automatically elevated to the level of poetry.
So when the Beautiful Code authors proffer pages of code-- real live production code-- and ask us to see the beauty, the code doesn't help. It gets in the way.
It's been a long time since I found *dst++ = *src++ beautiful.
Focusing on the code is exactly the wrong approach. It's like a detailed technical description of the paints, brushes, and techniques used to paint the Mona Lisa, without any of the historical or artistic context that makes it such an important painting.
Can't we expect readers to see past the language? I'd ask the very same question of the authors. So many of them got mired in the minute details of the code and language that they never got around to the "why" underneath -- the beautiful ideas and concepts that code represents. I'd also ask the same question of every working programmer today. I can scarcely post any code snippets in Visual Basic today without a slew of comments complaining about how awfully horrible Basic syntax is, how their eyes are bleeding, it's unreadable, the horrors of End If versus curly brackets, etcetera, etcetera, ad nauseam. Never mind the language-- what about the underlying algorithmic concept I am trying to represent in code? How does that look?
Apparently, for many of us, beauty really is skin deep.
But the code itself is not beautiful.
Actually, it is. To those who speak it. That was Dmitry's point. And therefore, a book presenting beautiful communication to people who don't speak the language has to be different than an ordinary book of poetry which would be read by fluent users of its language.
In the first chapter Kernighan concludes that the example "really uses the underlying language to good effect" and goes on to explain why. The .NET framework is essential for Petzolds' chapter; pseudo code would not make sense.
My problem with the book is that I don't have a C.S. degree, so much of it just feels impenetrable.
I would hold up "Programmers at Work" and "Out of their Minds" as examples of what Beautiful Code was trying to achieve.
http://www.codinghorror.com/blog/archives/000541.html
Jeff Atwood on February 21, 2008 5:06 AMA commonly heard (and silly) saying is "beauty is skin deep, but ugly goes to the bone". It's funny in part because we all know that it is often the opposite of reality. Pretty skin can hide an ugly algorith, but no amount of beauty at the algorithmic level can hide the ugliness that is some languages.
Jess Sightler on February 21, 2008 5:21 AM@Jess: and physically ugly people may be pretty nice to talk to as well. So that saying is indeed silly, since the opposite is just as common.
Nicolas on February 21, 2008 5:37 AMHumm, I quite enjoyed the book (even though I can't read, grok, love or tolerate lisp ;)). And while there was a lot of code in there, the authors also wrote about their thoughts, designs, et cetera - maybe it's just me, but I think most chapters presented the reason why the author thought the thing was beautiful, and for their various reasons.
It was also nice seeing a lot of different languages and their associated programming styles, from the condensed and impenetrable to the almost self-documenting.
But I guess if your definition of "beautiful" is too narrow, you could end up disappointed :)
f0dder on February 21, 2008 5:43 AMThe difference is that "The Best Software Writing" carefully selected from years of the best writing whereas beautiful code just asked N people for a free bit of text the correct length.
m on February 21, 2008 5:58 AMA beautiful algorithm, a beautiful implementation, and beautiful code can all be very different things.
You get complaints when you post VB code because VB *is* ugly. The syntax, a twisted corruption of what was once a very simple attempt to make interpreted pseudocode attacks us on an almost visceral level, the few remaining English keywords hurtling us into that uncanny valley where freaks and monsters lament their cruel fate. ;-)
But of course, you can take a beautiful algorithm and implement it beautifully in VB. It won't be pleasant to look at, but once you get past the scars and blemishes on the skin you can still find beauty in the meaning.
You just posted about Michael Abrash's books. Most of us today read assembly only with difficulty if at all, yet those books were entertaining because of the great stories surrounding the code. IMHO, that's the way to write about code - give it a narrative, a plot, a protagonist a villain and a great struggle which at length is overcome. But of course, the code itself doesn't have to be beautiful, and indeed may be far more entertaining if it isn't - the success of The Daily WTF should prove that.
The idea of beautiful code, like beautiful poetry, is deeply attached to the language in which it is written. There's no point in translating "The Wasteland" into Latin, and any modern English translation of "Jabberwocky" is just boring - the beauty comes from how they use the language in which they're written, not necessarily any specific problem solved... or even the ideas conveyed. Beautiful code, like beautiful prose, can open our eyes to how we may use a language.
There are plenty of gripping stories. And plenty of clever algorithms. Truly beautiful code is rare.
Shog9 on February 21, 2008 6:28 AMWell they do say that beauty is in the eye of the beholder. So as Josh said if you understand the language you might also see the beauty, but someone like myself who is a web developer, I only know PHP, AJAX, and a handful of other seemingly useless languages (HTML etc), any lisp or even any C(++, #) over the vary basics would not make any sense to me so I don't think I'd see it as very beautiful. In addition what I see as beautiful, like a PHP script to do entire file system handling, would not be seen as beautiful to someone who knows C(++, #) or even shell scripting.
Arron on February 21, 2008 7:38 AMThere is no "elegant" code, either. "Elegant" is an adjective reserved solely for artists, poets and fashion. Code works - well - or it's "gorilla" - and crap.
PaulG. on February 21, 2008 7:43 AMI think you could describe some of the Ruby language as either beautiful or elegant. That is probably why the chapter by Yukihiro Matsumoto stood out.
The following code, for example, I would say is very elegant:
(3..6).each { |num| puts num }
# = 3
# = 4
# = 5
# = 6
I think beautiful code exists. However, not only do you have to understand the language, but the code itself always is built with an abstraction that is RARELY beautiful underneath the hood.
At that point, you have something akin to pseudocode anyways, that represents the bigger picture in a compact fashion.
BSD on February 21, 2008 7:59 AMThe book has some good stuffs, but I never could enjoy it much ve read like code complete etc..
As you said either they've to stick with single programming language and explain things in that way or to stick with pseudo code.
But still having some good nice stuffs inside it. I was almost stopped reading it. Anyway have to restart it again with the interesting part first :) (Obviously goes to C/C++ items)
Sarath on February 21, 2008 8:02 AMOne part of the beauty is when your brain likes what it gets served.
I feel that ruby comes very close to this mind, but i guess other languages have a similar way (though different syntax).
What matters most at the end of the day of course is the good IDEAS that are put forward and realized. But until then I can dream of a better (software) world, where bugs fix itself (or even better dont even start to exist)
Eloquent:
characterized by forceful and appropriate expression
I've never written elegant code... but eloquent code, ah yes!
Evil Mike on February 21, 2008 9:06 AMEnd Function, CType, Me. That is ugly. There is such a thing as beautiful code it is anything with a curly bracket or a def.
ryan on February 21, 2008 9:23 AMWhat's the most beautiful code? DNA, I guess, even without understanding what it does.
Chris L on February 21, 2008 9:30 AMIt's like you don't even read your own posts, Jeff. Your last one linked to an entire book about optimizing C++ and assembly at the instruction level and this one complains about how much it sucks when random people dump a bunch of code on you and ask you to see the beauty.
Abrash's book is full of complex, subtle, and, yes, even beautiful code. That's why you mentioned it and linked to it. Why did you like his books so much and hate these other authors who are proud of their particularly elegant solutions and similarly display their own code for all to learn from?
If you're going to drive all of your readers to the beach to show us how neat all the water is, don't bitch about a specific lake the next day. Not only is your obvious "me too" criticism a waste of your time, it makes you sound wishy-washy.
Sean on February 21, 2008 9:45 AM@Sean you obviously missed the point. It's not the code that's not beautiful, it's the lack of context with which to understand why it's beautiful. That's why his last post is not incongruous with this post.
In any case, great post Jeff. How about a new book, "Beautiful Blog". ;)
Haacked on February 21, 2008 9:53 AMIt's like you don't even read your own posts, Jeff.
Not really. It's the context that the code appears.
A book about optimizing C++ and assembly code is strict in its point. If you don't want to see C++/assembly code, it should seem fairly obviously that this won't be a book for you. And, at no point, does the book, or the post about it, imply a study of the beauty of C++/Assembly. Rather, it implies (hopefully) helpful guidelines and suggestions in actually writing code. Thus, warranting a plethora of code.
But, a generalized book about the beauty of code only implies a limited amount of code. You expect to find the majority consisting of information about the code.
jLl on February 21, 2008 10:05 AMI was also massively disappointed by the book. It wasn't just the title that disappointed me - I think the back cover said something like "leading programmers explain how they think" which sounded incredibly appealing to me. Unfortunately many of the authors missed the point entirely (not all - a couple of the essays really were good). Many just presented a piece of code they worked on and then explained in excruciating detail how it worked. Show a code snippet, then translate it "look, this bit tests to see if the file exists and if not, creates it". Another came out with something really vacuous like "I decided to use object orientation to make the design cleaner" which really explains nothing at all. At that point I actually started to wonder about the "leading programmers" part. Mostly, the genuine "leading" programmers who I'd heard of before had quite good articles. I'm not convinced by some of the other authors - they're certainly not good writers anyway.
Luke H on February 21, 2008 10:21 AMshark jump landed :P
intriguing post!
I was actually quite pleased with the book. I haven't read as many books as you have had, but I did enjoy it.
Jesus DeLaTorre on February 21, 2008 10:39 AMYou dont know a language, you dont understand it - of course.
You dont know maths, you can not see beauty on theorems.
Even in music is difficult to see beauty if you dont belong in a specific culture.
Can any russophones translate that snippet of awful russian poetry? Just out of curiosity.
Lieutenant Geyser Shitdick on February 21, 2008 11:31 AMVery well said by Dimitry and very well quoted by you.
This book has been appearing on my Amazon "recommended books" and "people who bought this item also bought ..." sections for a few weeks now. So, I browsed through it at a local book store. And I browsed through it some more. And a little more. And then I figured exactly what you have stated: its a bunch of disjointed essays by a few programmers I know and a few I don't.
If I have to read anything from Jon Bentley, I would rather pick up Programming Pearls. If I have to read anything from Kernighan I would rather read (all over again) "The C Programming Language", "The Unix Programming Environment", "Elements of Programming Style", "Software Tools", "The Practice of Programming". The same logic applies to a lot of other authors on the list.
More importantly, I figured that my knowledge of languages is so restricted (C, C++, a little bit of Perl and a little bit of Ruby) that I just cannot convince myself to go out and figure what "the beautiful-code writer" was saying in his "foreign" programming language.
The final question was: how can code be beautiful? Code, no matter who writes it, is always ugly. And it is a maintenance hazard for the guy who has to fix it later.
Regards,
Mahesh
@Lieutenant
It's from the Russian books about Neznaika (translated as Dunno)
http://en.wikipedia.org/wiki/Neznaika
Once Neznaika was explained that to write poetry, all is needed is rhyme. What his first poetry meant was:
"I'm a poet, my name is Dunno,
Let me to present you a balalaika"
(http://en.wikipedia.org/wiki/Balalaika)
Jeff, (if you haven't already) you might want to see Jon Bentley's TechTalk on the quicksorts he mentioned in the book: http://video.google.com/videoplay?docid=-1031789501179533828
Sharma on February 22, 2008 1:42 AM1. though u have not used ruby/lisp/perl in projects, it is shameful to say foreign language as a OLD programmer. how do you spend your holiday?
2. beautiful sense is common sense, like music, art.
thanks, the Russian poem made me laugh
Reinis on February 22, 2008 1:47 AMBeautiful is a horribly overloaded word anyways.
Joe Chung on February 22, 2008 1:48 AMCould not agree more.
A beauty code is a functional, robust one.
That code your client loves (and no nothings about it) and make you do money.
The rest is just bla bla bla.
John Prado on February 22, 2008 2:04 AMI don't think the comparison to the Mona Lisa is apt. Reading about the paintbrushes that Da Vinci used and the difficulty he went through to obtain the various hues for his paint helps you to appreciate the beauty of the Mona Lisa.
I do agree with you though. I don't think the paintbrushes that Da Vinci used are beautiful, nor the paints. Code is not beautiful, no matter whether it's VB, C# or Lisp. Nor are the individual words in a book beautiful, but combine them together and they can move a person to tears with their beauty.
Only the artist who understands his tools (whether paintbrushes, words or code) can create beautiful art.
Jeff, (if you haven't already) you might want to see Jon Bentley's TechTalk on the quicksorts he mentioned in the book
http://twitter.com/codinghorror/statuses/741686032
Indeed, some of the chapters of Beautiful Code are quite good. Just not enough of it..
Jeff Atwood on February 22, 2008 2:19 AMIt can be a difficult balance to achieve, where the code you write does something really well, is not too verbose but not so condensed that you get a headache reading it.
People and language preferences are too subjective to even talk about (but I might as well!): I can't stand C, C++, and don't like C# too much. VB.NET is a lesser evil, and I prefer Delphi's Object Pascal.
And, I've seen some REALLY beautiful code in PAL (Paradox Application Language)!
Interesting, I had a very different reaction to the book. Granted, there are some stinkers in there, but overall there were enough good reads to more than make up for it. For instance, the chapters written by Bentley, Kernighan, Peyton-Jones and Matsumoto were alone worth it. I'
m not sure the editors clearly expressed the intent of the book. On the other hand, I'm not sure they really understood what would come of it. In some sense, it has an emergent quality to it. A lot of the book was not really about the beauty of coding so much as highlighting what, to me at least, it is that draws me to write code and, most of all, to read it.
Perhaps I just have a different sense of what I wanted out of the book. I wasn't looking for a guide to what makes code beautiful. I was looking for something that expressed the beauty in the code. I did that for me. Not all of it, but enough to satisfy me.
Thomas on February 22, 2008 2:42 AMCode, like words, can be beautiful. It is called typography. However, the book in question is not about typography at all.
Karel Thnissen on February 22, 2008 4:26 AMIt reminds me of VHDL when we were doing our neat semi additionar cells, and then we linked them together to make a nice regular pattern of carry/propagate.
The code was nice, regular, and all the most beautiful that when we learned that it was an algorithm for a millenar chinese algorithm of multiplication.
Then we made the bool table and found that it could be simplified, this was sparing a nice number of cycles. Codes would break down in xor/and/or losing it's tight code readibility, but was gaining once the trick known a certain beauty, because we all knew that in our architecture MULU and DIVU where the 2 operations limiting the core frequency.
But this is not beauty, this is knowing you are initiated to programming because you know the trick lies behind the code. This is technical.
John Carmack square root (see previous article) is beautiful, because it is a "float" square root made with amazingly fast integer operation relying on Newton approximation, seeded with a good starting point enabling a fast convergence in one iteration. All you need for a game.
The beauty of john carmack's square root fast square root is that it relies on a fast, easy neat trick relying on classic highschool knowledge. Any 16 years old kid have the knowledge to write the main of it.
Simple, powerfull, easily understandable once you know the trick. The most beautifull code should appeal to the sense of elegance : a simple trick that everybody could have done doing amazing result. The hardest trick of programming is finding neat, simple obvious efficient solution no one thought of before you. That is what I defined as beautiful code.
Some code from a project I am working on. (Not mine, but I think it is beautiful and elegant). This method is from an object representing an uploaded file that must be indexed and virus-scanned and stored on the file system. This shows off some of the coolness of ruby, rails, and acts_as_state_machine.
def process
(scan! and index! and ready!) or error!
end
Hey Now Jeff,
I like the cover, it reminds me of lessons from geese you tube vid. Worse is better right? http://www.codinghorror.com/blog/archives/001046.html All code is beautiful, just some may be better that others. Eye of the beholder right? I really like your comments about seeing past the language.
Coding Horror Fan,
Catto
Here is some pretty code for you to do fancy math. I'd rather read books about life in the IT business world like "NetSlaves" by Bill Lessard and Steve Baldwin. Or "dot.bomb: My Days and Nights at an Internet Goliath" by J. David Kuo.
000010 IDENTIFICATION DIVISION.
000020 PROGRAM-ID. FancyMath.
000030 ENVIRONMENT DIVISION.
000040 DATA DIVISION.
000050 WORKING-STORAGE SECTION.
000060 01 Quantity PICTURE 999 COMPUTATIONAL.
000070 PROCEDURE DIVISION.
000080 ArithmeticDoneHere.
000090 MOVE 6 TO Quantity.
000100 ADD 4 TO Quantity.
000110 DIVIDE 2 INTO Quantity.
000120 DISPLAY Quantity.
000130 STOP RUN.
*dst++ = *src++...
while(*dst++ = *src++);
is much more useful.
certainly not beautiful... just a major fag to read. Certainly not efficient either... post increment is evil. :)
*dst = *src;
while(++*dst = ++*src);
and its still ugly...
I really agree that algorithms are the truly beautiful part.
Jheriko on February 22, 2008 6:11 AMI enjoyed a number of the essays, but the quality overall was pretty uneven. Some of the projects seemed pretty banal (eg the 'mars rover' and ERP system) and there were even a few that I considered examples of 'anti-beautiful' code. Some of the essays were also quite specialized or domain specific. Overall I would agree that I was somewhat disappointed with the book.
Paul Gunn on February 22, 2008 6:32 AMI agree with you. In contemporary art, no artist will ever explain why his work is beautiful, this is the job of art critics, it could have been a better idea to do it this way for this book.
Yet art somehow is framing and displaying beauty in a quite playful and evident way, something you will never find with software and code, since it is mostly hidden/compiled. It is like a modern car, nobody fancy to look at the engine these days, even if it is probably and endless resource of wonders and ingenuity.
My code is ugly at first glance, full of outdated comments, bad indentations, redundant conditions and long forgot unused variables but I like to think the structure is quite polished and inventive. Too bad none of the authors had the patience of introducing what are his methods to design the structure.
Jeromelab on February 22, 2008 6:48 AMNovelist Thomas Wolfe once wrote of an editor whose great talent was his innate sense of "rightness", the ability to know when then exact right words had been set to the page. When I see beauty in code, it is something akin to that; a realization that the prgrammer has done exactly what is needed, and anything more or less would somehow detract from the whole. I do not find any programming language inherently beautiful. None can be said to be particularly ugly either, so long as it allows the developer to effectively communicate with the compiler and other developers, while solving the broader problems that prompt us to create software in the first place.
Jim Snyder on February 22, 2008 6:57 AMI can't get over the cover photo. The formation of the bird should indicate leading, but somehow I havt to think of a arrowhead all the time (which wouldn't be beautiful at all):
if () {
if () {
while () {
if () {
goose.IsLeader = true;
}
}
}
else {
}
}
It's too bad the authors didn't discuss their aesthetics, commonalities and differences.
Lisp and Ruby are as different as Futurism and Impressionism.
brian on February 22, 2008 7:17 AMI remember reading this book a while back and had no problem at all understanding the included code, even when it was a language like Ruby that I've never used before. Programming languages are a lot a like and my years of Java experience was plenty to understand everything in the book.
Maybe this reviewer who compared the code examples to an incomprehensible foreign language simply isn't a programmer. People who can't speak Russian don't try to read Russian books, so why is this guy who can't read code trying to read a coding book?
a on February 22, 2008 7:26 AMNice post, reminds me of one of my favourite ever quotes;br/br/
i
When I am working on a problem, I never think about beauty but when I have finished, if the solution is not beautiful, I know it is wrong.
br/span style="font-size: 0.8em"R. Buckminster Fuller/span
/i
I wouldn't mind it if you posted VB, Jeff.
Mattkins on February 22, 2008 7:30 AMRead most of the book; agreed. I wonder how http://www.codersatwork.com will compare?
Brad on February 22, 2008 7:52 AMIn technical subjects, it takes a pretty thorough understanding of the subject to see the beauty. You can't expect to be able to see it after a single chapter of light reading. The essence of what makes it beautiful is much more subtle than that. And I suspect that you honestly cannot explain to someone else what makes a technical subject beautiful unless they already believe it. Otherwise, you can allude to the reasons for it being beautiful. You cannot demonstrate it.
One case of this I've seen over and over again is the beauty of mathematics. I have taken a number of classes where the professor gives a few classic proofs to show the elegance of mathematics. They are almost always: sqrt(2) is irrational, there is no largest prime integer, and there exist irrationals a and b such that a^b is rational. The point is supposed to be that such obscure, hard to reason about questions in math can be proved with absolute certainty in about 5 minutes. But in a few of my classes (the C.S. ones ;-), many of the students' eyes simply glazed over. They could perhaps follow each step of the logic individually, but even after giving into the fact that these theorems are true, they certainly must not have seemed at all beautiful.
Beauty is to a large extent an acquired taste. Part of the acquisition of that taste is learning the language the example is given in. Lisp looks like total garbage until you see a bootstrapping interpreter for it, and your audience needs to understand what an equivalent interpreter for C would look like. Haskell is overly abstract and seems to complicate the simplest tasks, but once you see how monads unify some of the most difficult concepts in programming: backtracking, continuations, error propogation, state management, and parsing, among many others, you can begin to appreciate how elegant monads really are. But to people not familiar with those topics and their difficulty and who have never seen monadic code, monads are just weird math crap.
Tac-TIcs on February 22, 2008 7:55 AMI was also disappointed with (the majority of) this book:
The "RESTful" chapter with all that really clunky Java?
The FORTRAN, fer cryin' out loud? All in all a wonderful
idea for a book, but too many bum entries to bring that
idea to fruition.
I must admit that i didn't read the book. But i saw a presentation by Andreas Zeller, who did the part on Beautiful Debugging.
If this man wrote the chapter as well as he did the presenation at JAOO 2007 about it, it must have been an awesome-wicked chapter.
Chadk on February 22, 2008 8:21 AMJeff,
'Beauty is in the eye of the beholder'.
Code is art driven by purpose. If the purpose is speed, sometimes code will get obfuscated as shown by your example. It is kind of Machiavellian.
There there are the folks who want to cram as much on the screen as possible:
if ( a == b )
{
printf( "Yo!" );
}
else
{
printf( "No!" );
}
versus
printf("%s",((a==b)?"Yo!":"No!"));
I'd be a liar not to say I've written the latter in instances with knowledge that the former would make it easier to follow.
Some people look at spaces, blank lines, and indentions as wasted space: ugliness, if you will. However, many coders 'hide' their laziness behind a 'pursuit of speed' justification. There is no excuse not to comment, and make easy-to-follow code.
Consistant rules is my personal issue. I really don't care, as long as the rules are logical and consistant. As an aside, many of my coleages laugh at one of my idiosynchracies: I add a semicolon to the end of my bracketed if-statements in c??. I just think it should be there. The optimizer removed the nop, so I really don't care about it. I will say it has saved me with mis-placed else statements, but it is really just a style thing to me.
Short of ratcheting back to the days of fixed-format FORTRAN, we are stuck with these free-flowing formats. I guess the best advice is for us to stick to our guns and work on making our code clear and concise.
-Doug
Doug on February 22, 2008 8:23 AMJeff,
You can post all the VB code you want to, I would rather you speak to me in my native language than Russian after all.
I am struggling through a OO class using Java and frankly dealing with the curly braces makes my head hurt. I grok the OO part, and Inheritance and Classes and even Polymorphism isn't that hard to grasp, struggling through layers of curly braces and remembering NOT to type "end if" is frustrating beyond belief.
Thanks for a good post...
Student
Craig on February 22, 2008 8:25 AM"...it's not the language that is inherently beautiful. Barroom doggerel expressed in French or Russian is never automatically elevated to the level of poetry.
So when the Beautiful Code authors proffer pages of code-- real live production code-- and ask us to see the beauty, the code doesn't help. It gets in the way. "
You're contradicting yourself. You're saying that it's not the language that makes the poem beautiful, but then saying that if you DON'T look at it in its original language then it effects the beauty of the poem. You're right on the latter account.
You're conflating two ideas. There can be beautiful algorithms expressed purely mathematically, but then there are beautiful algorithms that are beautiful *because* of the code used to express them. If you repaint Monet's in a Pre-Raphaelite style, would they still be beautiful? Maybe, but certainly not in the same way. The style is PART of what makes a Monet beautiful. In the same way, using different tricks with Ruby or LISP is often what makes the code beautiful.
Tim on February 22, 2008 8:42 AMWell, I enjoyed the book! Nothing is perfect, but I took it as a well-edited collection of essays from experienced programmers about code that they enjoyed writing and, in their opinion, they found "beautiful".
With that assumption, I benefited from reading the book and recommend it to others.
Defining beauty is like trying to define intelligence, a slippery task at best.
~Matt
Matt Doar on February 22, 2008 8:44 AMBeauty is in details. Here is one example below.
A gentleman was once visiting a temple under construction.
In the temple premises, he saw a sculptor making an idol of God.
Suddenly he saw, just a few meters away, another identical idol was lying.
Surprised he asked the sculptor, do you need two statutes of the same idol.
No said the sculptor. We need only one, but the first one got damaged at the last stage.
The gentleman examined the statue. No apparent damage was visible.
Where the damage is? Asked the gentleman.
There is a scratch on the nose of the idol.
Where are you going to keep the idol? Asked the gentleman.
The sculptor replied that it will be installed on a pillar 20 feet high.
The gentleman asked- When the idol will be 20 feet away from the eyes of the beholder, who is going to know that there is scratch on the nose anyways?
The sculptor looked at the gentleman, smiled and said, "The God knows it and I know it ".
The desire to excel should be exclusive of the fact whether someone appreciates it or not.
Excellence is a drive from Inside not Outside.
Nitin Badole on February 22, 2008 8:50 AMI too wasn't particularly impressed with the book in terms of the expectations raised. Some interesting stuff but not a lot of beauty. If you want to see really beautiful code, pick up anything by Donald Knuth.
A. Lloyd Flanagan on February 22, 2008 8:51 AM@Student: The best cure for cognitive dissonance between brackets and end statements, or any two competing syntactic styles, is to learn a language that uses the style you're not used to. But it's got to be a language that you enjoy.
Lua was the one that taught me to code switch between "}" and "end," personally.
Evan on February 22, 2008 9:18 AMto: ThatGuyInTheBack
"and frankly I'm no longer arrogant enough to think I can keep 4 or 5 levels of curly braces straight."
No matter what the language or indentation, I use a comment after the tail.
} // while whatever
END IF ' daytime in Norway
What is wrong with VB syntax?
Why should I need all c's punctuation? ;
Why should I need a ; before } but not after?
Why should I need ( ) around subroutine parameters?
I like that my VB functions and subroutines look like native functions and statements. The only situation where that is not true is where the syntax of my own output formatting subroutine can't use and ; rather than , between parameters to indicate no spacing.
I will admit that VB has a readability ambiguity design flaw:
A: B = C
Is A a statement label target of a GOTO or GOSUB? or
Is A a call to subroutine A that takes no parameters?
You can't tell from reading the line.
David
DAKra on February 22, 2008 9:41 AM End Function, CType, Me. That is ugly. There is such a thing
as beautiful code it is anything with a curly bracket or a def.
Let's see...
- "End Function" is actually less ambiguous than a curly brace. So are "End For", "End Select" etc....
- "CType" is just a cast which is present in the 'curly-brace' languages. It's better than C and C# casts because at least "CType", like C++'s cast templates, are searchable.
- "Me" is the same thing as "this" in the 'curly-brace' languages.
- An application that is written using VB.NET and then translated to C# (or vice-versa if you want) looks remarkably similar in both VB.NET and C#. The main differences being the keywords used.
In the end, Visual Basic's keywords and structure flow are in some ways better than the 'curly-brace' languages and it looks like you just have a prejudice against Visual Basic. I could call you a 'language racist'.
I understand why so many people don't like Visual Basic:
- It's different. But that's no reason to say a language is really "bad". These languages are different but do not have the criticism VB has: Python, Lisp, F#, Nemerle, assembly.
- Visual Basic (especially prior to .NET) was breeding ground for coders who can't code well and mistakingly thought themselves "software engineers" (these people used no engineering practices at all). While these people's code is ugly and miserable to maintain, this does not mean that VB can't be used elegantly. Far from it. I've seen elegant VB code -- both pre- and post-.NET. It's just that VB has been easier for people to use (not necessarily a bad thing by the way) -- but the consequence of that is you have a higher proportion of less skilled people using the language.
As for me... I work daily using C and C++, but I also work on occasion with Python, assembly, F#, C++/CLI, C#, and VB.NET. C++ is my favorite language because of the multiple paradigms it supports.
Jeff,
I don't think the comparison to Out of Their Minds is very apt (I haven't read Programmers at Work, so I won't comment on that one). Out of Their Minds is much more about the biography and personalities of great computer scientists and the most high level description of their work possible. It was written for both laypersons and engineers to read to get a sense of the history of the discipline in terms of its prominent people. It is not very focused on the code. But, to say that focusing on the code is an error is a hard position to defend. If you do not see beauty in code, it's difficult to create beauty in code.
So do you just run off and buy a book simply based on an Amazon recommendation? I am surprised you have a lot of faith in their recommendations. Why don't you first check out the book at a nearby bookstore? If you like it, buy it right there or if you want to save some money, order it from Amazon.
Beauty is in the eye of the beholder.
Abdu on February 22, 2008 10:04 AMI have to say I disagree with the idea that only a subject (algorithm, idea) can be beautiful and never the representation. Form and content both have value.
http://basildoncoder.com/blog/2008/02/22/code-can-be-beautiful/
Jeff I also purchased this book in the hopes of learning more about how various software systems work. The title of 'Beautiful Code' wasn't the selling factor for me so I guess thats why I wasn't quite as annoyed with this book as you were. After a while of reading through the book it really does take on a snobby champagne sipping tone that really will annoy lots of folk though. You can just imagine the authors popping cristal and writing about why they believe their code is so elegant. LOL
o.s. on February 22, 2008 10:20 AMA big thing with me is that I find certain modern works beautiful. I find early Sonic Youth beautiful. I find John Coltrane and Ornette Coleman's music to be beautiful. I find Jackson Pollack beautiful.
But I would totally freak out if I saw a code base that looked like "Free Jazz" sounds.
Dave on February 22, 2008 10:35 AMMy opinion, dudes:
First off, code is not beautiful. Supermodels are beautiful (at least on the outside!) Beethoven's Ninth Symphony is beautiful. The sunrise by the shore is beautiful. Code can be well-designed, or uniquely structured but there is nothing beautiful about code. Good code should be appreciated and emulated but never cherished or adored. Strive to write good code, even great code, but don't strive to make beautiful code. I believe doing so is a mistake.
I understand the point all the essays. I just don't like the use of the word beautiful being related to coding. Of course, it's Friday, and maybe a few hours/vodka tonics from now It won't bother me so much!
Kenneth on February 22, 2008 10:56 AMBefore .NET, it used to be "use C++ to make quick applications, use VB to make applications quickly"
Now, with .NET, VB, C#, and managed C++ all compile to the same thing. There are still a number of things that VB won't let you do (since it is still designed to eliminate the need to code all of the underlying functionality), but now there is C# as a middle-ground. With C#, you get the curly-brace formatting C++ developers are accustomed to, but the rapid development of VB.
The majority of business apps (not counting critical services like database servers) can be written quickly and efficiently using nothing but VB.
Scott B on February 22, 2008 11:14 AMNot really. It's the context that the code appears.
You expect to find the majority consisting of information about the code.
So the book title "Beautiful Code" doesn't imply that you're going to read a lot of beautiful code examples? I think you may have missed the everyday zen mindfulness of the book; if Joshu can find all the world's beauty in a bucket of dead fish, you can pretty easily find beauty in code that someone has gone out of their way to make you consider. Perhaps the beauty comes from interpreting and unraveling the code yourself (much like a koan) and not form some lengthy explanation of it's beauty. The process of understanding its elegance is also fundamental to taking away the lesson that the code was meant to teach.
Like they always say, a joke explained is never funny. To me, explanations in some chapters would have ruined everything... it would be like opening a Penthouse to find photos of nude women accompanied by pages of text describing why their poses and the soft lenses make them sexually appealing.
And, at no point, does the book, or the post about it, imply a study of the beauty of C++/Assembly.
If the book you are talking about is Abrash's, it does indeed imply a study of the beauty of C++ and the raw functionality of ASM. When the book was published, everyone was still trying to beat the industry drums over C++ and its suitability for large projects. Borland and others were leaning heavily on game developers to lead the way because they were willing early adopters and could demonstrate the speed and utility of C++. The book mentions at several points how beautiful and elegant C++ can be and how you should consider using it (with linked or inline assembly, of course!) for graphics or generally optimized programming.
Dmitry Dvoinikov put forward his opinion of the book and Jeff echoed it here. I don't agree with either and can't imagine anyone having any rational objections to the book, even if they would have laid out the content differently. I imagine you are meant to read this book the way an architect walks into a building--it's not a "for dummies" book so why should it have wider appeal and be more accessible?
Sean on February 22, 2008 11:35 AMDid O'Reilly run out of animals to put on the cover?
In all likelihood the authors did not pick the title, the editor or publisher did; and with more the idea of what would sell than relating it to the content. How many have picked it up based on the title, and how many would if the title was 'Essays on Programming'?
You dont know a language, you dont understand it - of course.
You dont know maths, you can not see beauty on theorems.
Reenforcemen :beauty in theorems does not come from writing it.It is the idea behind the theorem that is beautiful.
I agree the inner beauty of code is most important, but to me, there is also how code *looks like*: the typography, how are white spaces formed, the form of comments... There is excellent article on typography of code: http://blog.hamstu.com/2008/02/03/the-typography-of-code/
m on February 22, 2008 12:10 PM
Yeah I will have to agree. Code is eloquent, maybe clever, but not beautiful. SOLUTIONS are beautiful, from "there is no largest prime number" to BitTorrent. When someone can solve a problem in a way that makes you feel dumb for not seeing it immediately, that's a beautiful thing. But indentation? Trivial verbosity? "Should that curly brace be on the same or next line" ? lol... The only person who does those things beautifully is someone who does them exactly like you!
Then again, I program in COBOL all day, C# all night, and PHP or VBA whenever web sites or excel macros require it ^_^
Hmm... I almost bought this book too...
Another great post Jeff.
One thing to note, that I think you imply or maybe I need sleep, is that if the code functions correctly and runs in optimum time, no matter how clean it is- people of various skill levels may find the code to be ugly for reasons of their own -bracket on a new line- that they're so used to. Hogwash. Respect another's creation as you wish respect onto yours.. unless if the Windows of your product line and has infinite bugs in it.
Peace
Patrick on February 22, 2008 12:30 PMBut the code itself is not beautiful.
I disagree. Code CAN be beautiful, and I think that is exactly the point of this book - to show how different languages' features can be utilized to create the most concise solution to a problem.
I think you can appreciate code in any programming language, even if you are unfamiliar with that language. A spoken language parallel would be something on the lines of appreciating music with lyrics in a foreign language or appreciating poetry written in another dialect - but surely not as foreign as Russian poetry.
Mogens Heller Grabe on February 22, 2008 12:36 PMHere is a rough translation in two versions:
{
I'm a poet, named Dontknowka,
And I'm giving you a polka.
}
* Dontknowka must be pronounced as "don't know"; and "ka" sounds like "cut" without the 't'.
And here is another localization, that does not take into account the Russian origin of the input data:
{
I'm a poet, named Jar-Jar,
And I give you a guitar.
}
I prefer the latter.
It's simple.
Beautiful code is code you can understand, that works well.
Ugly code is anything that:
1) You can't understand
2) Is fragile (no error checking on inputs or dies easily)
or
3) Uses bad coding practices
@Doug:
I think you picked a really bad example, the first code you seem to consider better duplicates code and while it is more verbose I do not think it is clearer at all.
With the second code it is obvious that it will always print something, only what is printed depends on a condition, whereas for the first example a reader must explicitly check that.
This becomes worse if e.g. there are multiple files open and you use fprintf, then you might have to look really closely to find out that indeed the only difference is in the strings printed.
Being mired in a world full of Visual Basic one would not be expected to see the beauty in code.
Diego on February 23, 2008 4:40 AMJust some further thoughts to throw in the mix…
For me there is a kind of universal beauty, for example recently my niece upon seeing a flower extended her finger to gently touch a petal with care and precision that belied her 17 months. There is no code getting in the way here it is intuitive.
The beauty of code is not so much in the syntax or what it looks like (mind you code displayed in an ide using the zenburn theme does look great) but in what it does. For example: Take a simple formula, iterate it many times, check the result and then depending on its value plot a pixel in a given colour at a location given by the starting formula, then repeat and you get the Mandelbrot set.
English (apologies to non readers/speakers) is a code that has an element of beauty because of its expressiveness, and the range of ideas it can convey. Not without its problems – it dreadfully overloaded with meaning – where else would the humour come from!
In my opinion code is still tied too closely to the metal, however the paradox is that given enough abstraction the code disappears and becomes the thing it expresses, the solution itself. So I am thinking the degree of abstraction is what matters.
I recently saw 200 lines of code for checking the validity of urls replaced with a 30 character regular expression, which to me encapsulates the whole problem discussed here, both are damn ugly but one is far more concise!
Perhaps we need code to be humourous….
Oh yeah, fortunately, Amazon had that look-inside scanned chapter, and I could tell immediately that it's a killer title for a mediocre book :)
Gil Megidish on February 23, 2008 7:23 AMWay back, I got a chance to work on some code that extremely sophisticated. After decades of people making agonizingly small and consistent 'tweaks' to prove their abilities, it was absolutely the cleanest and most elegant thing I have ever seen. The beauty comes from how closely the code accomplishes it purpose with little or no artificial complexity. It is like so many proofs for theorems in calculus text books, they have been refined so many times that you take their simplicity for granted. It is the lack of elegance that you really notice.
As it happens I was musing over this very issue this week in my blog. I put together the simplest answer for elegance that I could:
http://theprogrammersparadox.blogspot.com/2008/02/fundamental-coding-issues.html
Paul.
The beauty of code lies in the architecture, the ideas, the grander algorithms and strategies that code represents.
The code itself is a necessary evil subcomponent of a beautiful [or otherwise] system. To me, beautiful code is that which regardless the language, is simple, concise an understandable--approaching transparent, even if its not my language of choice or comfort.
You know.. like regex..
Sam on February 23, 2008 10:32 AMJheriko, I cannot see the beauty in this code:
*dst = *src;
while(++*dst = ++*src);
is definitely not a pre-increment version of
while(*dst++ = *src++);
its only an inefficient way to set *dst and *src to '\0' :)
asdf on February 23, 2008 12:10 PMThe Mona Lisa isn't really that beautiful anyway. It's famous because of its history (it's been in the possession of several historical figures) and because of the speculation and mystery about it. Also because it was stolen.
Justin Cunningham wrote "
The following code, for example, I would say is very elegant:
(3..6).each { |num| puts num }
# = 3
# = 4
# = 5
# = 6
"
I don't know, I think Perl's
print (3..6);
is more elegent.
Of course, Perl defaults the output field separator to undefined, so that prints out 3456. Settings $, = "\n"; makes it work like expected.
Powerlord on February 23, 2008 12:30 PMm wrote
"I agree the inner beauty of code is most important, but to me, there is also how code *looks like*: the typography, how are white spaces formed, the form of comments... There is excellent article on typography of code: a href="http://blog.hamstu.com/2008/02/03/the-typography-of-code/"http://blog.hamstu.com/2008/02/03/the-typography-of-code//a
"
Did you check the urls at the bottom of that article? One of them is Jeff's: a href="http://www.codinghorror.com/blog/archives/000969.html"http://www.codinghorror.com/blog/archives/000969.html/a
Powerlord on February 23, 2008 12:56 PMA beautiful code is one that works. If, on top of that, it does not consume too much sweat tears from its programmers ( maintainers), call it sexy.
I find that elegant code quite often is stupid code. People often call their code elegant whenever they've managed to cram a complex operation into one single expression in some kind of way...
I say that is ugly.
Beautiful code to me is one singluar operation per line, logical grouping of operations, one comment per group of operations, and no more than five or six logical operations for each function.
Simplicity, in short.
Jesus Maria on February 24, 2008 2:56 AMCode which works? That's a given. The question beyond that is how to write code which works, and which at the same time is easily maintained and/or passed over to others.
If you only focus on creating code which works... I don't want to hire you as a programmer.
Jesus Maria on February 24, 2008 3:59 AMI agree. I got this book from the library and could barely get through the first chapter. I don't feel like it is something I can learn from. I was hoping for more of a "here's what I did and this is how it can help you" type of book.
At least the proceeds for its purchase are being donated to Amnesty International!
lauren on February 24, 2008 8:52 AMPreincrement is worse, in general, as it introduces dependency between the increment and the following copy. Post increment is better, because result of increment is not required at all, at least not in the same iteration.
vtolkov on February 24, 2008 10:05 AMCraig the Student,
I know how you feel, I went through the same problems with Java when I first entered comp sci at my school. It wasn't till 3 years later when I discovered Ruby that I really enjoyed programming. Try it out, you'll never want to code in another language again.
Taylor Redden on February 24, 2008 11:39 AMHi,
there is beautiful code. At least, if you like abstract art. Then your choice should be a language called "Piet". Here is an example: http://99-bottles-of-beer.net/language-piet-1269.html
Perhaps the author did not do a good job explaining, but the title is a reach.
Code CAN be beautiful. The proof is: if code cannot be beautiful, then it cannot be ugly, either. Yet we all have seen ugly code. Therefore the code can be beautiful, even if we don't know what it looks like.
Just like a beautiful poetry comes from effective use of few words to express profound ideas, beautiful code comes from effective uses of the language constructs to express the ideas.
If all code needs to do is to work, then we might not have invented higher level constructs. We might duplciate a procedure ten thousand times instead of putting it in a loop. Heck - we might not even have procedures!
Of course - few will say loops or functions are beautiful, because loops are everywhere, and we come to accept that as the norm. But it's no doubt more beautiful than the alternative, and that's the key: beauty is a relative thing, and there is no such thing as absolute beauty.
If one know what ugly code looks like know how to improve it so it's no longer ugly, then one have produced a more beautiful code in comparison.
And beautiful code is rare in the wild indeed.
Code can be ELEGANT.
james on February 25, 2008 8:34 AMFolks, I made an effort and collected a series of translations of the verse about Neznaika. If you're curious, check it out: http://railean.net/index.php/2008/02/25/russian_translation_challenge
Alex on February 25, 2008 12:13 PMThe comments to this entry are closed.
|
|
Traffic Stats |