×

Welcome to the Slashdot Beta site -- learn more here. Use the link in the footer or click here to return to the Classic version of Slashdot.

Thank you!

Before you choose to head back to the Classic look of the site, we'd appreciate it if you share your thoughts on the Beta; your feedback is what drives our ongoing development.

Beta is different and we value you taking the time to try it out. Please take a look at the changes we've made in Beta and  learn more about it. Thanks for reading, and for making the site better!

Where Can I Find Beautiful Code?

michael posted more than 13 years ago | from the not-in-anything-I-write-that's-for-sure dept.

Programming 371

eGabriel writes "One of the benefits of free software that I haven't seen explored here is that of the opportunity to study elegant, masterful code. Besides the fact that we can all share and enjoy applications, and reuse their source code, we can also simply download the code and view it for pleasure, to learn from masters of the art. Certainly there are different criteria for determining what makes a piece of code excellent or beautiful, and I am not as interested in discussing that. If however, anyone has found a piece of free software that serves as an excellent example for study because of qualities they as programmers hold dear, I would love to read that code also and be educated thereby. Equally interesting would be code that really is bad, as long as it didn't turn into direct attacks upon the programmers involved (they can't all be gems!) Any code that shows elegant and masterful design would make for excellent reading; the language in which it is written isn't as much a concern. 'Literate' code is a bonus."

cancel ×
This is a preview of your comment

No Comment Title Entered

Anonymous Coward 1 minute ago

No Comment Entered

371 comments

FreeBSD et al. (1)

Anonymous Coward | more than 13 years ago | (#482973)


Check out /usr/src on a FreeBSD system. There are countless examples of excellent code in there.

For example, ever wonder how ping(8) works?

$ cd /usr/src/sbin/ping
$ ls
Makefile ping.8 ping.c

Re:The most beautiful piece of code... (1)

Anonymous Coward | more than 13 years ago | (#482974)

Tsk tsk. You forgot the "return(0);". And you didn't indent. AND you didn't check the return value of printf() (forgiveable, everyone forgets that). Is this what beauty's about? That particular snippet is ugly enough to warrent a warning in most compilers, but slashdot seems to think its worth a +1...

Windows98SE (1)

Anonymous Coward | more than 13 years ago | (#482975)

Windows98SE is the *BEST* code which I've had the privilege to view. Superb. It's unfortunate that Bill Gates won't release it for all to see, because it would put *everything* else to shame. When it comes to quality, Windows98SE wrote the book! One of the perks of working for Microsoft has been the honor of being allowed to touch this cyber-magic known as Windows98SE source code.

Knuth (1)

Anonymous Coward | more than 13 years ago | (#482976)

Try anything written by Knuth [stanford.edu]...

Re:OpenSource is Beautiful (2)

Alan (347) | more than 13 years ago | (#482982)

Excellent point!

That's something that no one has mentioned yet (that I've seen). ANY code you see can be beautiful code! A couple of months ago I got thrown back into coding C at work after being in perl for a couple of years. It went well, but I *knew* my code wasn't all that great. It worked, was readable, and relatively bug-free. But I still knew it needed some work. I read a couple of books (Programming Style or something like that?), and looked over a bunch of code that I was available. Everything from smail source to code from newsgroups.

I learnt little bits from all these sources. A chunk of code can be bug free and crappy, but still give you good insight into how to code better. For example, I had a great routine for getting system mem/cpu info from /proc/*. Browsing through the wmsysmon code I found that (to my surprise) there is a sysinfo() call that can give me that exact information... suddenly my code is made simpler, more elegant, and more readable, as well as more bugfree thanks to one line in an obscure little applet (well, maybe not *that* obscure :).

If the code for these programs wasn't open source, we'd have nowhere to look. There would be code around, but having a huge array of applications to look at and scoure through, makes everyone's code better.

Deja Vu (4)

cradle (1442) | more than 13 years ago | (#482991)

I remember when I asked [slashdot.org] a similar question a few years ago. It might be informative to take a gander at it. -David

Python (2)

AMK (3114) | more than 13 years ago | (#482996)

Try looking at the source for the Python interpreter (the C version; I know little about JPython). Like any sizable program it has its messy bits, but overall the organization is quite clear, the implementation leans toward the simple and straightforward instead of the weirdly optimized and obscure, and it's one of the more pleasant medium-sized programs I've worked on.

(Where is the boundary between medium-sized and large programs, anyway? Python is roughly 150,000 lines of code, though over half of that is in the various extensions that come with the source distribution; the core interpreter itself is around 60,000 lines.)

Re:The Story Of Mel (or: Ugly Code) (1)

noahm (4459) | more than 13 years ago | (#483000)

This classic hacker legend came up in a software design class while at Northeastern [neu.edu]. It was used as an example of terrible coding practice. Sure, Mel was an artist, and an incredibly skilled programmer, but his code was completely unreadable. Unless you're one of those people who follows the "if I write unreadable code then they can never replace me" school of thought for job security then you should definitely not look up to Mel.

noah

Re:perhaps the most visible projects? (2)

drix (4602) | more than 13 years ago | (#483002)

I'm not quite sure about that. Konqueror isn't even close to being stable, ditto Mozilla. If you're looking for how to pull off a lot of complicated things, they would be the place to go. If you are looking for actual elegance and educational value, to say nothing of things that actually work, there are better places to look. For example, Scheme is a very simple language through which a lot of high-level, fascinating concepts can be demonstrated quite easily. I find some of the more intricate parts of Abelson & Sussman's SICP more enlightening than chugging through 10,000 lines of Konqueror, but to each his own...

--

Tex (3)

drix (4602) | more than 13 years ago | (#483003)

Donald Knuth's Tex certainly qualifies. Not only was it written, from the ground up, by arguably the greatest computer scientist of our time, but it's so good that it's bug free. Literally, there are no bugs in it. Stop and think about what that means for a minute. Can you come up with any software program on the planet of equal size and complexity (several megs of source code - not huge, but still formidable) that can make that claim? I can't. Granted, I may be incorrect, but nevertheless I find that amazing. You can view the parts of Tex that Knuth actually wrote here [stanford.edu]. They're written in (I think) CWEB, which is some literate programming language he has a real hard-on for. That probably means it fscking rules all, but personally I don't have the time/patience to pick it up. If you're sufficiently motivated, though, I'd imagine the Tex sources would prove very enlightening.

--

A Search (1)

jjr (6873) | more than 13 years ago | (#483018)

Your search for Beautiful code depends on the person reading the code. What is understood by one person is not by another you must look through the source files and look for yourself for Beautiful code

Elegant beautiful code? try perlmonks.. (3)

dallen (11400) | more than 13 years ago | (#483029)

I've seen more elegant code on perlmonks.org [perlmonks.org] than anywhere else. I've learned a lot there. People submit their craft, and more advanced disciples of perl comment on it and occasionally turn it into beautiful code.

--
Q: What do you get when a Postmodernist joins the Mafia?

It's right under your nose. (1)

mrsam (12205) | more than 13 years ago | (#483034)

See ftp.kernel.org.

A month or two ago I could no longer ignore an itch that wanted to be scratched. I've had a few gizmos whose capabilities were only partially supported by the Linux kernel. After two years of waiting for the device driver to be updated, I searched the web until I found the specs that I needed, then just grabbed the kernel tarball, and started poking around.

Now, keep in mind that until then I've never looked at the Linux kernel source in much detail. I have manually compiled it a couple of times, but that was many years ago, in 2.0 days.

Still, after only an afternoon of poking around, I was able to easily figure out what I needed to hack, and how. I came away with a very favorite impression of the kernel's innards. I did not fully understand everything I've seen, but the code was clearly laid out, and there was no doubt that if I really wanted to invest some additional time, I wouldn't have any problems figuring it out.

It's not every day that you can download almost twenty megabytes of compressed source code that you've never seen before, and only a few hours later you are able to figure out how to go about doing what you want to do.

---

Re:Emacs Source Made Me Decide to Remain a Program (1)

joshv (13017) | more than 13 years ago | (#483035)

Such a good coder, and yet your web site is hideous and unreadable.

Dump the tiled background, those fell out of style years ago, and backgrounds that make the text unreadable were never in style to begin with.

-josh

NeoMail (3)

LawnMowerMan (13750) | more than 13 years ago | (#483038)

Many have the belief that NeoMail (http://neomail.sourceforge.net) is a project written in Perl which is not only excellently coded and well commented, it is also very efficient.

Why just code... (5)

platypus (18156) | more than 13 years ago | (#483049)

I'm far away from being a linux zealot, but an real good example (IMO, YMMV etc.) is reading linux-kernel.
L.T. and the other kernel hackers sometimes get into very interesting discussions. Lately there was a discussion where L.T. called the HP-UX sendfile implementation obviously stupid (and BSD's too, yeah, roll on ;-)).
One of the people who answered was ... well the implementor on HP-UX himself and a very interesting discussion began.
So, leeching on mailing lists might help - and if you're not into low-level os programming I'm sure you'll find a open source project which covers areas interesting to you (unless you're doing ERP applications or such stuff).

--
"There is so much to be said in favor of modern journalism. By giving us the opinions of the uneducated it keeps us in touch with ignorance of the community."

Oscar Wilde (1854-1900)

Content, Content, Content (1)

LionMan (18384) | more than 13 years ago | (#483050)

Although readability is neccessary in code, it is more imporant that it works. Certain concepts are hard to code, and some algorithms have to be implemented in a certain way so that they work how you want them to. Library functions, for instance, require speed. Although you could code them "beautifully", without a perfect optimizer (which really doesn't exist) it would be slower than coding the function for that purpose.
The most important niche for readability is in new code, high level code, or constantly changing code. Maybe some others. Those are the places that you need to be able to understand the algorithm by looking at the code and/or comments. If something is rock solid and is not going change, is well documented and tested, the code doens't have to be pretty since it works how expected and nobody needs terribly to read it. If you're working on a multiperson project, though, and your code is likely to change, it's a good idea to document it and code it prettily so others can tell if they're adding or subtracting.
And, as always, it is important to stress the engineers'/scientists'/programmers' motto: Function before Fasion.

Re:Functional Programming (1)

_Splat (22170) | more than 13 years ago | (#483055)

If you ever code in MUSHcode, you'll learn to hate functional programming.

The best code has lots of comments. (5)

Dr. Tom (23206) | more than 13 years ago | (#483060)

When I download something, the first thing I look for is comments. No matter how clever or elegant the code is, nothing 10,000 lines long can ever be so self-evident that you don't need comments.

Especially if the algorithm is particularly clever, it can be relying on some subtlety that will be entirely missed without a good long comment. Modifying such code is dangerous.

One of the reasons people like Knuth's approach so much is that he puts the comments first, conceptually. The code is essentially embedded in a great long comment that describes everything that's happening. The code is just there to distill the essence of the algorithm into a form a stupid machine can understand. If the machines were a bit smarter, they would be able to run the program by reading the comments and executing them!

Code with no comments is not a sign that the author understands his code so well that he doesn't need them. It is a sign that the programmer is lazy, sloppy, and doesn't care whether or not his code is maintainable. I just can't emphasize this point enough: for Open Source projects commenting is even more important than code. A large faceless company can get away with releasing products built on hundreds of thousands of lines of uncommented code, because they have external documentation, and can afford to spend thousands of dollars training new programmers. But if you want other people to even look at your code, you have to help them understand it. People making patches to code they don't fully grok are just going to make a mess.

Good commenting style is as difficult to develop as good coding practices (the two really go hand in hand). Mental discipline (did you ever say to yourself "I'll go back and comment it later"? Did you?), clear exposition of an algorithm (no, the code is not a clear exposition -- remember code is CODE, it's meant for a stupid machine, not an intelligent human), maintainability, etc. Comments should be written in complete sentences wherever possible. Don't comment like this:

/*

* this comment
* is pretty
* but hard to format again
* when you change it
*/
Rather, write them like this:
/* This comment is a paragraph. Any text editor can reformat this comment after you change it. */

Not everybody uses the same tools you do. Comments should be as easy to change as possible. If they aren't, people won't do it, and the comments can get out of synch with the code, which is even worse than no comment at all.

Languages without block quotes are very irritating in this respect.

So don't look for beautiful CODE, look for well written prose comments. THAT program will be more stable, easier to use, more functional, and a joy to work on.

Re:The most beautiful piece of code... (1)

maw (25860) | more than 13 years ago | (#483068)

You shouldn't use tabs in code. (The exception that makes the rule is that Makefiles require tabs.)

It's better, in a cross-platform portability way, to use individual spaces. If somebody is using an editor which can't automatically change the number of spaces, too bad for him.

Obviously, indentation is important.
--

hard to identify beautiful code (3)

J.J. (27067) | more than 13 years ago | (#483071)

The problem with reading source code is that it's a lot like art. Not art the idea, but art the thing. (Writing good code is an art (the idea) but that's not the point)

Art is enitrely subjective. And the definition of good code is subjective. You realize this, and state that you're not interested in what defines excellent code. But we do agree that to find excellent (to you) code, you're going to have to dig through a lot of good (to others) code before you find that gem. Which leads to the next problem...

Art takes study to fully understand. And again, excellent code takes study to fully understand. Some will say that the ability to understand code quickly is an element of excellence, but this goes back to the first point, that art is subjective. Perhaps someone else places versatile and consistent APIs across a tool set above readability. Programmers are always making trade-offs between the relative incline of the learning curve and the power of the interface. (windows vs. unix, for example)

You can continue the analogy for a while, but these two combine to make a situation where you're going to have a tough time finding good code. You'll get tons of submissions of what excellent code is, but to make that distinction yourself, you're going to have to study each case in-depth.

Good luck.

J.J.

www.altivore.com (3)

RobertGraham (28990) | more than 13 years ago | (#483076)

I wrote a piece of code in just a weekend that emulates the functionality of Carnivore. Because it was a rush job, I wouldn't call it particularly artful, but one of the "artful" things is that it compiles on Linux, Solaris/SPARC, and Windows (yes, Windows) with identical functionality but no platform-specific #ifdefs.

The reason I think this is artful is that people tend to write code that runs only in their own platform. The fast majority of Linux code I see will not compile/run on a Solaris/SPARC system. Likewise, the Solaris/SPARC code rarely runs on Linux. Throwing Windows into the mix makes things even tougher.

For example, one of the chief problems is that the old *(int*)p problem. If you are lucky, you simply get a byte-swapped value; if 'p' is unaligned, your program will actually crash (it's a RISC thing).

When deal with external data structures (network protocols, binary files), most programmers think it is "elegant" to map structures on top of pointers. In reality, it is one of the most evil/ugly things you can do to code. One of the prettier pieces of code I've seen recently actually had a comment /*struct are for weenies*/ (meaning the structure-mapping process, not internal data structures). Dealing with such data one byte at a time sure look ugly to the uninitiated, but it really is the prettiest way.

In any case, one of the reasons I'm posting this is because I don't post much open source, and therefore don't know much about what other people find ugly. I would be interested in hearing your comments about the source on www.altivore.com. Please send e-mail to altivore-comments@robertgraham.com.

Re:Functional Programming (1)

msaavedra (29918) | more than 13 years ago | (#483078)

Slashdot doesn't support <PRE>
Slashdot does, however, support the <tt> tag, which does basically the same thing.
---------------------------
"The people. Could you patent the sun?"

Re:The Story Of Mel (1)

Synoptic (39163) | more than 13 years ago | (#483092)

Heh.. makes me think of something I always do, but still get in trouble for with my coworkers.

Elem *pMyLinkedList;

Elem **pSrch;

for (pSrch = &pMyLinkedList; *pSrch;
pSrch = &((*pSrch)->pNext));
(*pSrch) = new Elem;

(management of a link list with double ptrs so you don't have to condition the first element)

OpenBSD (1)

kinger (39543) | more than 13 years ago | (#483093)

If I recall the OpenBSD guys don't necessarily audit the code for security, they focus on good, clean, correct programming practices. Security then naturally falls into place.

Although I have no personal experience with it OpenBSD might be a good place to look.

Re:OpenSource is Beautiful (1)

p3d0 (42270) | more than 13 years ago | (#483096)

That reminds me of the loop abstraction I learned from the Linux kernel. If you have a linked list, you define something like this:

#define for_each_thingy(current, list) for(current=list->head; current; current=current->next)

Then you get to write code like this:

void print_thingy_list(Thingy_list list){
Thingy *t;
for_each_thingy(t, list){
/* Wow, nice and abstract. */
print(t);
}
}

--
Patrick Doyle

Want nice code? (1)

alehmann (50545) | more than 13 years ago | (#483100)

http://www.ioccc.org
http://www.muppetlabs.com/~breadbox/bf/
http://linuxassembly.org

TeX (5)

cyrusp (65739) | more than 13 years ago | (#483107)

Jargon file says it best:

TeX has also been a noteworthy example of free, shared, but high-quality software. Knuth offers a monetary awards to anyone who found and reported bugs dating from before the 1989 code freeze; as the years wore on and the few remaining bugs were fixed (and new ones even harder to find), the bribe went up. Though well-written, TeX is so large (and so full of cutting edge technique) that it is said to have unearthed at least one bug in every Pascal system it has been compiled with.

The Story Of Mel (5)

Eight Star (67539) | more than 13 years ago | (#483109)

For all of those who haven't read it, or want to again, this is a good story [pbm.com] about cool code, and a cool coder.
This [google.com] is the Google search I found it with.
The real Eight Star misses Technocrat.

Hello World Seven Ways (4)

amnesty (69314) | more than 13 years ago | (#483112)

This really got my geeky juices excited when I saw this. One piece of source code that could compile/run unchanged into 7 different languages. Listed in the source they are: ANSI COBOL, ISO Pascal, ANSI Fortran, ANSI C (lint free), Shell script (GNU Bash, Ksh, sh), PostScript, and 8086 machine language. No matter which you use, the magical words "Hello World" will appear!

Click here [latech.edu] for the link.

Y-Combinator...... (3)

ndfa (71139) | more than 13 years ago | (#483114)

This is in my mind some really really sexy code.
I guess you can call is OSS, you see it in almost every Programming Language book that uses scheme or something like scheme/lisp.... to see what it does check out Y-Combinator Derivation [uark.edu]. So the basic idea is to be able to have a recursive func. that does not have a name.....

(define Y
(lambda (m)
((lambda (f) (m (lambda (a) ((f f) a))))
(lambda (f) (m (lambda (a) ((f f) a)))))))


The most beautiful piece of code... (1)

mduell (72367) | more than 13 years ago | (#483118)

#include <stdio.h>

int main( void )
{
printf( "Hello world!" );
}


Mark Duell

Re:The most beautiful piece of code... (2)

mduell (72367) | more than 13 years ago | (#483119)

Ok, in my rush to post, I forgot to #include <stdlib.h> and add return EXIT_SUCCESS to the end.

Mark Duell

Re:The most beautiful piece of code... (1)

nycsubway (79012) | more than 13 years ago | (#483127)

its beautiful, but aren't you missing the return value? since main is an int...

Emacs Source Made Me Decide to Remain a Programmer (5)

goingware (85213) | more than 13 years ago | (#483132)

I was in and out of my University physics studies a number of times, and having a generally bad time, because of a serious illness [geometricvisions.com], and at some point decided I should get out and get a programming job because I figured I'd be better at that than school.

I didn't really know how to program, I knew a little FORTRAN, C and Basic from doing data analysis during summer jobs, and I didn't really like it all that much. I used to really have to struggle to spend several weeks writing a 500 line program, and I'm sure I'd be embarrassed if I had to look at the source code to those programs today.

I figured I'd program for a while because it paid the rent (I was making $20k a year doing Sun administration and writing image processing software), but when I figured out what I really wanted to do for a living I'd quit programming and get a real job.

That was in 1988. Then some consultant visited and installed GNU Emacs [gnu.org] on our machines (two Sun 3/160's, one diskless, both with terminals and no workstation monitor, but with frame grabber cards and NTSC color monitors). He explained about the GNU manifesto [gnu.org].

I thought it was pretty cool but didn't see it affecting me personally in a big way. I was mostly annoyed that I had to wait up while the consultant installed the software on what was supposed to be my day off while a ladyfriend was visiting from away.

Then my friend Jeff Keller, who went to MIT for a while and vaguely knew Richard Stallman, spent an evening with me singing the praises of Emacs. What I really wanted was VI with macros you could program to include conditional branches, and he said it had all though and much much more.

So I learned to actually use Emacs, and soon learned that it was quite extensible, but it wasn't made too clear how to extend it. The online manual was useful mainly to people who already knew what they were doing.

So I read the source code. One thing I was interested in doing was writing C functions that were callable from Emacs lisp as lisp functions. There are many such functions built into Emacs (usually for performance) and you can add your own. There's this big DEFUN macro that even makes the C API look like Lisp.

I learned that and a lot more. I learned what an eloquent statement of software architecture Emacs is.

I learned that there really was something worth my while doing in the way of software.

I wanted to write a program like that someday. Not another big editor, but a program that would someday strike other young programmers the way Emacs struck me.

During the course of reading the source code, one day I stayed at my terminal 24 hours straight, arising only to get coffee and use the restroom, not even eating. I only realized how much time had passed when I started to fall asleep.

That was when I started to take programming seriously. I began to put serious effort into studying programming, and studying it deeply.

For example I would read Knuth's The Art of Computer Programming [fatbrain.com] on the bus on the way to work and I would stay up all night after work learning to program better on my Macintosh at home.

For many years I selected all of my jobs based mainly on what I could learn from them.

I've become a very skilled programmer. You can see this from my consulting business website [goingware.com], my resume [goingware.com] (on my resume the place where I first encountered Emacs is the Programmer job at Verde Technologies) and my programming tips pages [goingware.com].

So in a very direct and profound way I owe it all to Richard Stallman [stallman.org] and Emacs.

I still haven't written my great program yet. I don't even know what it will be. One project I've worked on peripherally is the ZooLib [sourceforge.net] cross-platform application framework and a project I've just started up but not gotten too far with yet is the Linux Quality Database [sunsite.dk].

I did finally get my B.A. in Physics, from UC Santa Cruz [ucsc.edu], but only after being out of school working at a programmer for a number of years.


Michael D. Crawford
GoingWare Inc

Got to be Jive talkin ! (2)

GreggBert (89663) | more than 13 years ago | (#483141)

Check out Jive [coolservlets.com] for an excellent example of beautiful coding in Java. There are a lot of forum software packages out there but none as complete (in terms of code design).

I've been able to look at this code and immediately understand, admire and learn from Matt Tucker's code from day one. Makes a good read.

Re:Python (1)

err666 (91660) | more than 13 years ago | (#483144)

Yeah, the Python source shows how you can get the most out of plain old C. I find the parts that insure type-safety especially cute :-) Type-safety in C ... weird. The GNU Hurd code is also of very high quality.

For especially good Ada 95 code, look at the source of the GNU Ada compiler (GNAT). This is really a masterpiece of compiler writing. I think it is also the largest chunk of open source Ada code available.

Gerhard

Beautiful Code (2)

pauldy (100083) | more than 13 years ago | (#483154)

I think beautiful code is subjective like art but unlike art programming has a relatively short history. I think things that would define beautiful code could be things like originality of thought, simplicity, and efficiency as well as the more common things like is it easy to read through and does it exhibit the general consensus of how things should look at the time. I think that in time groups will begin open source "peer reviews" where people could actually vode on things like syntax, originality, simplicity, how well they perform the function for which they were intended. I'm not sure of anything out there like that right now asside from the obscufiblagh* whatever they call it.

I think it would be neet to see a site pop up where thats all they did was take pretty code and imortalize it for study and general advancement of the "science".

Re:The most beautiful piece of code... (1)

thelaw (100964) | more than 13 years ago | (#483159)

> sent back to Visual Basic where they belong.

or tcl.

jon

Re:The most beautiful piece of code... (1)

Girf (101378) | more than 13 years ago | (#483160)

Actually, I find that piece ugly. If I were wanting a beautiful 'Hello World' I would:
  • Lose the '!'. Exclaimation marks are lame; there isn't really much to get excited about.
  • Tabs, need I say more?
  • Use a '\n'. I really hate when a program makes my console look like Hello world![james@jimbob ~]. Any code/coder that doesn't use line breaks should be whipped and beaten then sent back to Visual Basic where they belong.

Do you work for Microsoft? (1)

chancycat (104884) | more than 13 years ago | (#483165)

OK, it's probably a bit late for this one, but:

Any chance you work for Microsoft? A little 'research', eh?

OK, sorry.

Re:The most beautiful piece of code... (1)

RoninM (105723) | more than 13 years ago | (#483167)

How about:
#include <stdio.h>

int main(void)
{
(void)printf("Hello, world!\n");
}
?

Functional Programming (1)

RoninM (105723) | more than 13 years ago | (#483168)

See functional programming. Not that it's terribly efficient from what I've seen and heard. I don't do it, myself, but it's something that got my attention and, at times, is really quite elegant. In Haskell:
qsort [] = []

qsort (x:xs) = elts_lt_x ++ [x] ++ elts_greq_x
where
elts_lt_x = [y | y <- xs, y < x]
elts_greq_x = [y | y <- xs, y >= x]
Your browser may mangle that. Slashdot doesn't support <PRE>. Anyway, see Haskell [haskell.org]. List comprehensions of the sort seen above are also new in Python 2.0 [python.org]. Very nice.

Re:Functional Programming (1)

RoninM (105723) | more than 13 years ago | (#483169)

Well, like I said, I don't write it and it's slow, but it's beautiful and elegant. You're right that I forgot the recursive call. My fault. :) Anyway, I was intending to give a brief look at the language (which I fux0red, anyway), not an exposé on it. Monads still beat the hell out of me. Still, pretty.

Re:What kind of question is that? (2)

RoninM (105723) | more than 13 years ago | (#483172)

Uhm, what's wrong with reading code? It's very nice to see how someone did something. Some of the most creative and elegant constructions I've seen ANYWHERE have been in source code. It's really an underrated form of expression.

TCL or AOLServer (1)

DanIncognito (112160) | more than 13 years ago | (#483174)

A couple of peices of code that I find pretty are TCL and AOLServer. I know there probably aren't many fans of these 2 products on slashdot of all places, but there both open source and beautiful to my eyes. Some of the highlights are
  • Both follow meticulous published engineering standards documents found Here [scriptics.com] and Here [aolserver.com].
  • Both create an easy to use API for extending themselves in C.
  • Both are great examples of how to keep your code flexable, many portions of this code would be useable in other projects.
  • Navigation proves easy for both of them. it never takes me more than a few seconds to find the file and function I want to look at.
  • Everything is well documented.

That being said, I'd also like to point out theres more to an open source project than just the code. A beautiful project includes docs (not just inline with the code), communications channels (mailing lists, newsgroups, etc.), useful examples, FAQs, etc. It takes alot of work to get these things to a useable state by the community.

Schwartzian Transform (1)

cheese_boy (118027) | more than 13 years ago | (#483180)

Perlmonks page on it [perlmonks.org]


my @output =
map { $_->[0] }
sort { $a->[1] cmp $b->[1] }
map { [$_, expensive_func($_)] }
@input;

The question is: Is this code that is "really bad"? Or "code that shows elegant and masterful design"?

Or is it both?

My vote is for both... Elegant, masterful, excellent and beautiful, yet can be really bad in certain uses.

Re:Slashdot isn't for you (1)

mr_gerbik (122036) | more than 13 years ago | (#483184)

"To the person who posted this comment, I don't think this community is for you. Many people have grown tired of the appearance of more and more trolls, who have nothing to offer this community. I myself have thought about leaving many times, and going to greener grass. "

Oh please. Trolls make Slashdot fun. There is nothing more entertaining than dropping your threshold to -1 for a few laughs. Instead of bitch and moan at trolls, why not raise your threshold? If you don't know how to raise your threshold I don't think this community is for you.

"If you are also tired of these trolls, and of the blatant bias and sheer overload (of posts) the authors of this site are showing on Slashdot I would like you to check out Kuro5shin.org "

So posts should be censored? If you believe in censorship, I don't think this community is for you.

-gerbik

Beautiful Code Links (2)

mr_gerbik (122036) | more than 13 years ago | (#483186)

Some of the most beautiful code produced in the past 20 years can be found here. [spacebarcowboy.com]

you can thank me later

-gerbik

This question is a bit too vague (5)

Triscuit (122259) | more than 13 years ago | (#483187)

I think the question can really only be answered to applying it to a particular task.

There are almost always good solutions to a certain task that can be considered good.

Next thing that must be done is to define "Good Code". I'm sure everyone has their own opinion as to what good code is;

Readable, Well Commented, Efficient Algorithm, Proper Naming Conventions, Follows Appropriate Documented methods, etc...etc...

I'm sure there are hundreds others!

Perhaps a question like "What defines good code" would still be only slightly more beneficial to those reading the posts.

perhaps the most visible projects? (2)

small_dick (127697) | more than 13 years ago | (#483192)

Kernel source, Apache, Samba, Gnome Bonobo, KDevelop, Mozilla, Konquerer...the big name stuff should be pretty juicy.

It's sorta Zen, unfortunately (1)

Gorobei (127755) | more than 13 years ago | (#483193)

You will not find good code by seeking it. Write your programs: use Open Source, third party libraries, and misdocumented APIs.

Bend as a reed in the wind. The novice curses unknown authors. The expert smiles and writes his code.

Code is poetry. Do not impressed by bombast, vocabulary, clever phrasing, rhyme, allusion. Beautiful code is distilled idea: language, syntax, style, comments, format, philosophy are mere surface quality.

If you attain enlightenment, you peers will laud you with praise. One day, you will meet one of the masters whose work led you to Satori. You won't have much to discuss, because you both understand the deep meaning of code.

IJG, ZLIB, BZIP2 (3)

istartedi (132515) | more than 13 years ago | (#483196)

Not so much the code itself, but the APIs are easy to use, they're highly portable, and very free. I wish I could say libpng, but it took a little bit too long to figure out how to make it do what I wanted. Maybe that was just me though. There was some trial and error involved. Let's hear it not only for "beautiful code" but the entire package being well designed and easy to use.

Re:NeoMail (2)

rgmoore (133276) | more than 13 years ago | (#483197)

You'd better not say that too loud, or the "Perl is incomprehensible line noise" crowd will have fits. Of course they'd probably be happy to say that to find some of the really awful, unmaintainable garbage you should just look here [slashcode.com].

Squeak! (1)

bzhou (138968) | more than 13 years ago | (#483211)

Surprised nobody mentioned smalltalk code.

See Squeak [squeak.org] for example, even the bootstrap C code is generated from squeak itself.

Once you get used to the syntax, the code is so much easier to understand for the same functionality compared with ones in other languages. Thanks for the OO nature, the code is easier to maintain as well.

I don't want to start another comp.lang war. I like C, I like Haskell, I use java/python quite a lot, but for purity and elegance, nothing comes close to Smalltalk.

The fact is..

no matter how closely I study it,
no matter how I take it apart,
no matter how I break it down,
It remains consistant.
I wish you were here to see it.
I like it.
- King Crimson [Discipline] "Indiscipline"

One Word - Quake (2)

desideria (140436) | more than 13 years ago | (#483212)

Probably one of the most groundbreaking graphics engines ever. Examining the code is like watching John Caramack think. Beautiful, Beautiful, Beautiful...!

Re:The most beautiful piece of code... (2)

StarDrifter (144026) | more than 13 years ago | (#483221)

subl $8,%esp
addl $-4,%esp

You cheated! This code was produced by gcc with slight modifications to remove the obvious compiler generated names and directives. No beautiful hand-coded asm program can have those two lines next to each other in the source.

Beauty.. (1)

gnireenigne (147835) | more than 13 years ago | (#483225)

.. is in the eye of the beholder - this amphorism works in this case too. But anyone who has had a chance to look at M$ MFC or Native Winblows code would have to agree that you would have to be blind to find beauty in any of that kludge. But code is not s'possed to be pretty. It's gotta work. That's what it's there for. Code On.

-*-*-*-*-*-*-*

Some beautiful code... (1)

TomRitchford (177931) | more than 13 years ago | (#483243)

Awright, this is code I wrote but I'm rather proud of it.

The javadoc is here [editeverything.com], with links to the code, and I chat a bit about it here [editeverything.com].

Perl Obfuscation (1)

SlipJig (184130) | more than 13 years ago | (#483248)

For an example of how NOT to code, why not check out some Perl Obfuscation [perlfoo.org]? I think it's a great thing to look at, even though (or especially because) I really don't like Perl as a language (heresy! heresy! Don't flame me please, I've heard the arguments).

Hello Polyglots (2)

ideology (191536) | more than 13 years ago | (#483251)

The home page for polyglot is: http://ideology.com.au/polyglot/ [ideology.com.au]

"A long time ago (1990) some people were talking about polyglot programs in rec.puzzles, these are programs that are written in several languages. We thought this sounded like fun so we wrote this [ideology.com.au] one."

We think it contains some pretty cool code, and most people still haven't found the hidden gems! There are two superfluous characters in the whole file (not including those used for formatting). Can anyone identify them?

It still seems to work on most modern platforms.

"Keep the blank lines, they are important"
Cheers, Peter

Re:The most beautiful piece of code... (3)

garett_spencley (193892) | more than 13 years ago | (#483256)

How about:

msg:
.string "Hello, world!\n"

.globl main

main:
pushl %ebp
movl %esp,%ebp
subl $8,%esp
addl $-4,%esp
pushl $14
pushl $msg
pushl $1
call write
addl $16,%esp
xorl %eax,%eax
jmp return

return:
movl %ebp,%esp
popl %ebp
ret

????

I know it's not indented... I tried... Darn html.. Oh well...

--
Garett

Read Gabriel's Book (1)

sv0f (197289) | more than 13 years ago | (#483257)

Read Gabriel's "Patterns of Software: Tales from the Software Community" for one man's search for beauty in a lot of places -- his code, his company, the arts, his life.

Is anyone taking this seriously? (4)

sv0f (197289) | more than 13 years ago | (#483258)

Beautiful code is a subject worth contemplating, not speeding by with the standard crap answers above. Here are two quite-different places to find beautiful code:

(1) The "Programming Pearls" books by Bentley.
(2) "On Lisp" by Paul Graham

Also, Here are some quotes of relevance:

The [benefit] which rhyme has over blank verse...is, that it bounds and circumscribes the fancy. For imagination in a poet is a faculty so wild and lawless, that, like an high-ranging spaniel, it must have clogs tied to it, lest it outrun the judgment. -- John Dryden

The central task of a natural science is to make the wonderful commonplace: to show that complexity, correctly viewed, is only a mask for simplicity; to find pattern hidden in apparent chaos. - Herb Simon

The mathematician's patterns, like the painter's or poet's, must be beautiful; the ideas, like the colours or the words, must fit together in a harmonious way. Beauty is the first test; there is no permanent place in the world for ugly mathematics...It may be very hard to define mathematical beauty, but that is just as true of beauty of any kind -- we may not know quite what we mean by a beautiful poem, but that does not prevent is from recognizing one when we read it. -- G. H. Hardy

Joseph LaGrange..."believed that a mathematician has not thoroughly understood his own work till he has made it so clear that he can go out and explain it effectively to the first man he meets on the street." -- E. T. Bell

When judging a physical theory, I ask myself wether I would have made the Universe in that way had I been God. -- Einstein

Beauty is the proper conforminty of the parts to one another and to the whole. - Hesienberg

There is no excellent beauty that hath not some strangeness in the proportion! - Francis Bacon

Simplex sigillum veri - The simple is the seal of the true. And Pulchritudo splendor veritatis - Beauty is the splendour of truth. - S. Chandrasekhar

The Scientist does not study nature because it is useful to do so. He studies it because he takes pleasure in it; and he takes pleasure in it because it is beautiful. If nature were not beautiful, it would not be worth knowing and life would not be worth living... I mean the intimate beauty which comes from the harmonious order of its parts. -- Poincare

My work always tried to unite the true with the beautiful; but when I had to choose one or another, I usually chose the beautiful. -- Hermann Weyl

Beauty is truth, truth beauty - that is all Ye know on earth, And all ye need to know. -- Keats

There are some great men of science whose charm consists in having said the first word on a subject, in having introduced some new idea which has proved fruitful; there are others whose charm consists perhaps in having said the last word on a subject, and who have reduced the subject to logical consistency and clearness. -- J. J. Thomson

Do you know we're sitting on 4 million pounds of fuel, one nuclear weapon, and a thing that has 270,000 moving parts built by the lowest bidder? Makes you feel good, doesn't it? -- Steve Buscemi ("Rockhound") in "Armageddon."

Re:NeoMail (3)

happystink (204158) | more than 13 years ago | (#483270)

wow, they must have really cleaned it up from a few months ago then, cause back then it had a security flaw so super-basic that it showed that they didn't really understand a single thing about web security, and I decided at that point to never use it, who knows what else they were forgetting. (the flaw was that if someone clicked a link on an incoming message, and the url of that message got passed to your referrer log, you could go to that url and you'd be intheir mail, with full access to their mailbox. The worst example of session-tracking I have ever seen).

sig:

Who is Mel? (3)

TheVet (205479) | more than 13 years ago | (#483272)

From the Jargon Files: Mel's full name is Mel Kaye. He is refered to in the LGP-30 manual as "Mel Kaye of Royal McBee who did the bulk of the programming [...] of the ACT 1 system".

Re:OpenSource is Beautiful (1)

atrowe (209484) | more than 13 years ago | (#483277)

Well, you certainly don't want to look at Slash [slashdot.org] if you're looking for well-written, easy to read code.

...in a language some don't even know is OO... (1)

borgboy (218060) | more than 13 years ago | (#483281)

the JCL [delphi-jedi.org] has it's moments. I'd actually suggest the Delphi VCL first, but the source ain't free. Too bad - it's an excellent lesson in inheritance.

Re:Functional Programming (1)

blamario (227479) | more than 13 years ago | (#483284)

Apart from the fact that you forgot the recursive call, this code exactly shows one of the problems of functional programming. Yes, the code is beautiful, but it's also slower than it should be. The problem is the list join ++ that must be avoided, as any LISP programmer knows. You should youse the accumulator technique, like this:

qsort l = qsort1 l []

qsort [] tail = tail
qsort (x:xs) tail = elts_lt_x (x : elts_greq_x)
where
elts_lt_x = qsort1 [y | y <- xs, y < x] tail
elts_greq_x = qsort1 [y | y <- xs, y >= x] tail

Wrong approach (3)

blamario (227479) | more than 13 years ago | (#483285)

Gosh, this is really a hard question as you can see from the apparent lack of enthusiastic answers. If only you asked where can you find BAD, AWFUL code I can guarantee there would be a lot more links. I mean, there are movements devoted to producing as bad code as possible. Take a look at Obfuscated C Code Contest [ioccc.org]. You can learn from negative examples as well, and they are much easier to find.

I don't know about the 3.1 source but... (1)

sheetsda (230887) | more than 13 years ago | (#483286)

I have managed to track down the source code for Windows 95 [cybercheeze.com] (which, with minimal modification, became 98).

On a semi-related note I think the slashdot crowd would get quite a kick out of these weird C compiler errors [cybercheeze.com]

"// this is the most hacked, evil, bastardized thing I've ever seen. kjb"

Really, really old "c" (1)

xFoz (231025) | more than 13 years ago | (#483287)

Dennis Ritchie kindly makes available source for "two very early compilers". Circa 1970 stuff from under the floor boards resurrected from tape.
Check out:http://cm.bell-labs.com/cm/cs/who/dmr/primeval C.html

Re:The Story Of Mel (1)

HoldmyCauls (239328) | more than 13 years ago | (#483290)

That's interesting. I played with my school's Hero-1 robot and the programming was all in Hex, via a keypad (0-F, of COURSE!) on the top of the machine. I can do THAT, and I've always been able to do BASIC, and I picked up HTML easily (completely out of context, I know), PLUS I learn actual verbal languages easily, but for some reason I suck at Java for my CS lab, and I can't comprehend the kernel code, or get started in Linux programming. Go fig.

Song Code (1)

tattered_tux (240373) | more than 13 years ago | (#483291)

#include #include "bawls.cpp" void main (){ Bawls A[99]; //initialize type Bawls to Array for(int i = 99; i > 0; i--){ passAround(takeOneDown(A[i])); } } // eof

CircleMud (3)

slugo (243955) | more than 13 years ago | (#483294)

http://www.circlemud.org I had fun intalling this on freebsd and getting it to run. You can open the code and make mods to the mud and enjoy playing your mods. Apply the patches from the ftp site. Others can come in and enjoy your mods. I learned alot about C programming from modifying this software and had fun playing with the mods I created. For instance, mod the software to have Puff roam around town instead of hanging out in Limbo. RO mud did this. Is it still around?

Doesn't anyone remember the 'scene' (1)

codetalker (245862) | more than 13 years ago | (#483296)

Remember back in the days of Second Reality by Future Crew and groups like Orange et all. If you can find the source to a demo, you can witness some truely awe inspiring code. www.scene.org [scene.org] These people squeezed every last clock cycle out of those old 386's. Most people didn't think it was possible. I know I didn't back then.

id software: doom, quake (5)

eulevik (258261) | more than 13 years ago | (#483301)

The source code to id software's doom and quake is the nicest real-world code that I have seen. Knuth's TeX, especially in book form, is also worthwhile.

Re:What kind of question is that? (3)

kilgore_47 (262118) | more than 13 years ago | (#483307)

I'm inclined to disagree. Code can be an art form, and if you dont agree you probably arn't a programmer. I wish I could write code decent enough to post under the 'beautiful' subject here, and I would tend to respect those who can...

Study at the foot of the master... (1)

3333t00l (301558) | more than 13 years ago | (#483313)

... you need to read some classic Raster code. I suggest Enlightenment 14.0. The elegance can move a geek to tears. To see the subltle gravity of his code, where just one loop can bring tears to the CPU. You too will be moved to ask a question similar to that ancient riddle: can god make a stone he cannot lift? Can Raster make a performance killing kluge that he would flinch at? Learn my son, learn. Only after can you be prepared to work on gnome-pannel.

a work of brilliance... (1)

Kewjoe (307612) | more than 13 years ago | (#483328)

didn't microsoft give the source code for windows 3.1x ?? that should be a good read :)

Re:FP! (1)

CmdrButtPlug (308493) | more than 13 years ago | (#483329)

Dude, take that back! It's not my fault that we're a bit more alert here in Canada! Btw, your post was funnier than mine. But mine was first! Ha! :-)

Re:Some beautiful code... (1)

pimphandofgod (308517) | more than 13 years ago | (#483331)

wow that is pretty sweet. ok,i'm lying, i didnt look at the code, just the program itself is sweet itself. 0 - offtopic

?? (1)

kLoNe343 (308775) | more than 13 years ago | (#483332)

What exactly is the question here? Isn't it "Ask Slashdot"? I see no question marks in the entire message.

My favorite code snippet... (1)

MegaManSE (309031) | more than 13 years ago | (#483334)

When I was in the 11th grade in high school I was coding using borland C++ 4.5 which did not allow me to use 32 bit instructions. So I figured I could cheat the compiler and do something interesting to get maximum performance on a copy from a buffer copy to svga framebuffer:

unsigned long far *dbtemp= dbdw[0];
asm {
push ds; //save regs
push es;
push bx;
mov bx, 0xA000 //get vram seg
mov es, bx //point extra segment to vram
lds si, dbtemp; //get buffer location
mov di, 0 //start at offset 0
mov cx, 16384 //dwords to copy
cld //set dir to forward
}
__emit__(102,243, 165); //32bit movsd

This was 3 years ago now and I still keep the file that this snippet is in around. How many C coders out there know of the __emit__ function anyway ?
Load More Comments
Slashdot Account

Need an Account?

Forgot your password?

Don't worry, we never post anything without your permission.

Submission Text Formatting Tips

We support a small subset of HTML, namely these tags:

  • b
  • i
  • p
  • br
  • a
  • ol
  • ul
  • li
  • dl
  • dt
  • dd
  • em
  • strong
  • tt
  • blockquote
  • div
  • quote
  • ecode

"ecode" can be used for code snippets, for example:

<ecode>    while(1) { do_something(); } </ecode>
Sign up for Slashdot Newsletters
Create a Slashdot Account

Loading...