Slashdot Mirror


Where Can I Find Beautiful Code?

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

371 comments

  1. FreeBSD et al. by Anonymous Coward · · Score: 1


    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

    1. Re:FreeBSD et al. by arnald · · Score: 1

      Better still, take a look at NetBSD - much cleaner. :-)

      --
      arnald
  2. Re:The most beautiful piece of code... by Anonymous Coward · · Score: 1

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

  3. Windows98SE by Anonymous Coward · · Score: 1

    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.

    1. Re:Windows98SE by Ice-d++ · · Score: 1

      Are we talking about the "WINDOWS SOURCE CODE HERE???" IMHO the most beautiful code ever written isn't "Can find file" or a bsod, there must be more elegant ways of handling errors don't ya think

  4. Knuth by Anonymous Coward · · Score: 1

    Try anything written by Knuth...

  5. Re:OpenSource is Beautiful by Anonymous Coward · · Score: 1

    You gotta be kidding. This is _exactly_ what fucking useless ugly code looks like. Its a terrible misuse of the C preprocessor that buys you nothing in form, fucntion or clarity. When I read a C file I want to see the C language, not some l33t redefinition of its basic looping constructs. And why call it a loop abstraction? Do you call

    #define unless(a) if(!(a))

    an if abstraction, too?

    If there really is crap like that in the Linux kernel (cant say it would surprise me given what a pos Linux has become) then the linux kernel desperately needs some guidelines.

    You write shit like that for a living and you starve.

  6. freeciv code by Anonymous Coward · · Score: 1

    I was surprised that, just 5 minutes after reading freeciv code, I could find what I was looking for. Consider I hadn't programmed C forg the past 3 years. www.freeciv.org It's a masterpiece in my humble opinion.

  7. Re:A Search by Anonymous Coward · · Score: 1
    "Answer me these questions three
    Afore the other side ye'll see!

    WHAT is your name?"

    "Anonymous Coward."

    "WHAT is your quest?"

    "I seek the holy grail of beautiful code."

    "WHAT is your favourite code design methodology?"

    "Top-down. NO! Object-oriented! AIEEEEE.....!"

  8. Re:The Story Of Mel (or: Ugly Code) NOT by Anonymous Coward · · Score: 1

    god damn it!
    Ok, yea, right there in the hex, you should put a few lines like

    # function for generating the card to be delt to the user from the computer.

    Ok, so with compiler coding (post-Mel), you could do this, and that useless ascii would total maybe half a kilobyte, maybe one. In olden days that was a gabillion dollars!!

    Arogent people who bash those before them with their 20/20 hind sight piss the shit out of me.

    Mel wrote the fastest and most optimal program possible, hands down. That's not a negotiable fact. He went the extra mile(s) to get get it working the fastest, at which point, it became a work of art. Since Mel, things have changed, and now greener pa$ture$ rule the world. That wasn't the case back then, when conserving resources was everything. Why do you think we had y2k? Because it was that damn important to save resources. That was the real cost.

    Anyone who calls Mel's code Spaghetti code should go to hell. Mel was an artist. That's like saying that frank lloyd wright's blueprints where scribble, because his buildings couldn't go through a tornado. Mel was an architect in a world of engineers. To quote RENT, "take him for what he is". Damnit, that really really pissed me off.

  9. Where Can I Find Beautiful Code?... by Anonymous Coward · · Score: 2
    Certianly not here

  10. Re:OpenSource is Beautiful by Alan · · Score: 2

    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.

  11. Re:The best code has lots of comments. by mcoletti · · Score: 1
    Unfortunately, there are many concepts that cannot be expressed in C

    Yes, but none of those concepts are programming concepts.

    This doesn't scan. What do you mean by "programming concept?"

    The original point is valid. C, or any other programming language, has limited ability to convey semantic intent to a human being. It is up to the human to insure that there are sufficient commentary to explain why the code is the way it is.

    --

    MAC | A polar bear is a cartesian bear after a coordinate transform.

  12. Just to augment your point by mcoletti · · Score: 1
    Source code shows only how you accomplish your task; it is only through comments (and meaningful naming conventions) that you convey anything about its purpose.

    Another way to look at this is that source code is intended for two audiences. The first is obviously the compiler itself, which equally obviously cares not a whit about commentary, names, and formatting. The second audience are the human beings that are going to be looking at that code. These humans can be anyone from the original author to a maintainer; and, each of them has their respective level of programming (in)competence.

    A lot of effort should go into appeasing the second audience. The relevent expression is "computer time is cheap, human time is expensive." A good programmer will insure that there's enough commentary for others to understand why they did what they did. And, for that matter, even for themselves; it's amazing how much you can forget after several months spent on other projects.

    --

    MAC | A polar bear is a cartesian bear after a coordinate transform.

  13. coldsync is a good example of The Right Way (tm) by mcoletti · · Score: 1
    coldsync, a Palm Pilot synching utility, has the cleanest code I've ever seen. The design is well thought out. The source is extremely well commented. It also has a lot of documentation, which has the bonus of being informative, comprehensive, and otherwise very well written. It also has some good "meta-level" documentation; e.g., the top-level "HACKING" file, which gives some basic pointers for those wishing to, well, hack the hell out of the thing.

    In other words, this application should prove to be an excellent programming how-to reference for wannabe hackers. Also, pay attention to the bibliography on coldsync's web site; there's some damn good stuff there.

    (Yes, that's right: an application with a bibliography. How cool is that?)

    --

    MAC | A polar bear is a cartesian bear after a coordinate transform.

  14. Re:Hungarian Notation by mcoletti · · Score: 1
    It can be hard to get used to Hungarian, but I don't know anybody who has gotten used to it who was able to stop using it.
    Hungarian Notation is good for rendering source code into obsfucating noise. I like the heuristic that names should be pronounceable, and be just lengthy enough to convey most of the semantics that that name represents.
    --

    MAC | A polar bear is a cartesian bear after a coordinate transform.

  15. Look at *BSD /usr/src by Dom2 · · Score: 1

    I see that nobody has mentioned the BSD source trees yet. All the BSDs (and NetBSD in particular) have some of the cleanest, simplest source code I have seen (barring /usr/src/contrib/, which is imported).

    It may not be earth shattering stuff, but every time I have needed to modify the source code to FreeBSD, it has been a delight to see how good the code is.

    Check out an unpacked source tree at ftp://ftp.freebsd.org/pub/FreeBSD/FreeBSD-current/ src

    -Dom

  16. Smalltalk by Stu+Charlton · · Score: 1

    I don't believe too many have mentioned the beauty of the Smalltalk class library. It was carefully crafted over many years and I don't believe there's any method with over 15 lines of code (except for the bit-blitting classes).

    Take a look at one of the non-commerical versions of VisualWorks, or even Squeak (an open source variant). It's quite impressive, and teaches one a lot about good object orientation.

    --
    -Stu
  17. Re:Try expressing this programming concept in C. by Stu+Charlton · · Score: 1

    I think the point is that English is a very poor language to express precision and C is a very poor language to express "gestalt" or big picture issues.

    For this reason, I think purpose statements and algorithm "walkalong" comments are crucial.

    I think what I do feel is that I don't like useless contextual comments that either

    a) state the obvious,

    x = 1 // set x to 1

    or

    b) tell me something WITHOUT rationale or explanation.

    /* passing in null may cause problems */
    calculatePricingContext(quoteContext, null);

    Which is what 80% of commenting tends to be.

    --
    -Stu
  18. Re:The best code has lots of comments. by Xtifr · · Score: 1

    Better yet, make the comments flow with the code:

    /* ok, finished with the current line, so we */
    linecounter++;

    The best comments describe why, not what. And if you leave the code as part of the sentence, then it becomes far more jarring when the code is changed, adding an additional incentive to keep the comments up-to-date.

  19. Deja Vu by cradle · · Score: 4

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

    1. Re:Deja Vu by eGabriel · · Score: 1

      Oh man... I missed that one. Ah well, t'was not wasted. Good answers when you asked also. --Gabriel

    2. Re:Deja Vu by cyber-vandal · · Score: 2

      Deja vu indeed. That was the very first Slashdot article I read, when I used AOL, I thought Microsoft were merely incompetent and I had only vaguely heard of Linux. Now I wouldn't touch AOL with a bargepole, I despise MS and Linux is an interesting hobby.

  20. Re:Y-Combinator...... by shdragon · · Score: 1

    ...ya know, it just seems like a really bad "Revenge of the Nerds" joke in disguise....

    ;)

    --aarOn

    --
    "...we dont care about the economics; we just want to be able to hack great stuff."
  21. Re:Emacs Source Made Me Decide to Remain a Program by Evangelion · · Score: 1


    You seem to think that there's some nessecary relation to programming and graphic design because they're both expressed on computers...
    --

  22. Pretty Perl Code by Coppit · · Score: 1
    I try to be pretty careful when writing Perl code, because I know how easy it is to do it wrong. :) Check out the code to News Clipper: http://newsclipper.sourceforge.net/ I'm not posting this because I'm bragging. I *think* the code is pretty well structured, but I'd love someone to tear into it. :)

    Some code features: automatic downloading and installation of plugins, two download techniques, web content fetching and munging, FTP of output files, logfiles, version safety, OO mixed with imperative style, a meager design document, Perl, modules, about 6000 lines of code, good comments, caching.


    ------------------------------------------------ -------

  23. I nominate fvwm/fvwm2/fvwm95 by Wheely · · Score: 1

    A few years back I wanted to add some functionality to the fvwm95 task bar as well as fix a couple of bugs. I'd never looked at any window manager code before and had no idea how modules would work and communicate.

    I quickly found it concise, elegant and above all logical, I was able to make my changes incredibly quickly and added a few more things I rather fancied just because it was all so clear.

    So congrats to the multitude who work(ed) on these projects and thanks, even though I no longer use the fvwm line of managers.

    Regards

  24. Python by AMK · · Score: 2
    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.)

    1. Re:Python by err666 · · Score: 1

      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

      --
      reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))
  25. Re:The best code has lots of comments. by Squid · · Score: 2

    though I believe you shouldn't comment every single function you create, if they are obvious, because it dilutes the value of the REAL valuable comments that explain difficult-to-understand sections.

    Agreed. I've seen comments so brain-dead it made the code HARDER to understand than if it weren't commented at all. But maybe one should still include comments of the form "I didn't comment this, it's obvious" so whoever reads the code doesn't think you got lazy?

  26. Re:Emacs Source Made Me Decide to Remain a Program by Squid · · Score: 2

    You seem to think that there's some nessecary relation to programming and graphic design because they're both expressed on computers...

    Well, we are talking about beauty, no? :-)

  27. GNU libavl by blp · · Score: 1

    Check out GNU libavl for some good binary tree structure code. The stable version is well written C; the development version is a literate program. (Note: I am the author.)

  28. Re:The Story Of Mel (or: Ugly Code) by noahm · · Score: 1
    This classic hacker legend came up in a software design class while at Northeastern. 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

  29. Re:The Story Of Mel (or: Ugly Code) by noahm · · Score: 1
    I get the point, I just strongly disagree with it. Code needs to be readable in order to be useful. I aknowledged Mel's skill and creativity in my original post, but I stick to my point: he was a poor engineer. I'm sure you've heard the quote "If builders built buildings the way programmers write programs, the first woodpecker to come along would destroy civilization." That describes Mel's coding style perfectly. Make the tiniest change to the system it's running on and the whole thing falls apart, requiring a complete rewrite. That's rediculous.

    I don't know where in my post you find any reference to debuggers that hold your hand or some kind of context sensitive help system or whatever. I sure never mentioned that. I'm just saying that Mel was a bad programmer because his code was unnecessarily obfuscated and completely inflexible. It has nothing to do with what tools he did or did not use. Obfuscated, inflexible code can be written with the latest GUI IDE. It doesn't take an old timer with a hex editor, and any hack value it has is quickly lost when you're the one tasked with figuring out why the code won't work after upgrading the system.

    noah

  30. Re:perhaps the most visible projects? by drix · · Score: 2

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

    --

    --

    I think there is a world market for maybe five personal web logs.
  31. Tex by drix · · Score: 3

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

    --

    --

    I think there is a world market for maybe five personal web logs.
    1. Re:TeX by frantzdb · · Score: 2
      So it rarely has bugs. That has nothing to do with whether or not it's "beautiful."

      Perhaps, but from the kind of person Knuth is, I'm sure that it is.

      --Ben

    2. Re:Tex by CAPSLOCK2000 · · Score: 1

      The reason why gets such a kick from CWEB is that he wrote it. He wrote it to write TeX. It's very nice indeed, although it takes a bit of time to get used to. If you want a nice example, take a look at TeX :)

    3. Re:TeX by SecretAsianMan · · Score: 4

      as the years wore on and the few remaining bugs were fixed ... the bribe went up

      The bribe started out at one cent (for the first bug) and doubles for every new bug, I believe. Now THAT's some trust in your work!

      --
      SecretAsianMan (54.5% Slashdot pure)

      --

      Washington, DC: It's like Hollywood for ugly people.

    4. Re:TeX by WillAdams · · Score: 1

      This source is available from teh local library or bookstore as _TeX: The Program_, one of the volumes of the Computers & Typesetting series. The book is the source code of the program as typeset by TeX...

      I'd thought this thread would have more on Dr. Knuth's concept of ``Literate Programming''...
      --
      Lettering Art in Modern Use

      --
      Sphinx of black quartz, judge my vow.
    5. Re:Tex by Amokscience · · Score: 1

      I'm sure some of the space software could make a reasonable claim to being more impressive. In fact, they're so sure of their methods that they can tell you how many bugs a new piece of software has. They might not have an inkling of where those defects are but since they haven't hit their expected bug count they know it's there.

      Now, that's impressive. It's impressive from a psychological and programming viewpoint. It's impressive on so many levels.

      I completely agree with you about TeX. It's the opening example of McConnell's Code Complete. It's a statement that to any programmer is 'perfect'.

      Oh, and I'd suggest reading Code Complete to anyone wondering what makes 'good code'.

      --
      Fsck cluebie moderators. I'll say what I want, offtopic or not. And fsck having to qualify every bloody statement just
    6. Re:Tex by pallex · · Score: 1

      "-- Why doesn't anybody care about last posts?"

      I did a `last post` once but no-one noticed it!! It has to be on an old discussion, but one which isnt archived. Gaping loophole though - no lameness filter problems! :)

    7. Re:TeX by Blackheart2 · · Score: 1

      I have looked at the TeX code, and in fact I own the book produced from the WEB (literate Pascal) sources. I have not seen the CWEB (literate Pascal) sources, so I cannot comment on those, although I suspect they are virtually identical modulo C/Pascal differences.

      Now, I can tell you that TeX, as a program in the abstract, is designed very well, i.e., the specification is quite well thought out and not too difficult to follow. Furthermore, it handles nearly all of the things you would want from a typesetter, so it is also very complete. And, when you consider how old TeX is, this is even more amazing.

      But the code itself -- I am talking now about the implementation, not the specification -- is not particularly spectacular. If it weren't in literate form, it would be difficult to grasp, that's for sure! With the literate documentation, it isn't too bad, although it's not what I'd call modular, doesn't take any advantage of strong typing, and you will find lots of places where Knuth makes what will seem to us now some very odd design decisions; the latter are mostly things to do with dynamic memory allocation (hint: there is none! :) and I/O, and are partly due to Pascal's peculiarities, and partly due to the age of the code, since it was originally written to be run on what we would now consider to be a very puny computer.

      My conclusion is, if you want to see how to design a program well, look at the TeX WEB; but if you want to see how to implement a program well, you should look at some programs written in more modern programming languages, as they can more precisely capture formally (i.e., also in machine-readable form rather than just human-readable form) some of the higher-level abstractions which appear in the specification.

      --

      BH
      Fools! They laughed at me at the Sorbonne...!

    8. Re:TeX by VSarkiss · · Score: 1
      ...it is said to have unearthed at least one bug in every Pascal system it has been compiled with.

      TeX can even find bugs in hardware.

      TeX has a test suite called "TripTeX", which your installation must pass for you to call it "TeX". When I went to compile the whole thing on DECStation 5000 series (in 1989), I got a series of failures, involving discrepancies in the last decimal place of several measurements. The problem turned out to be with the custom floating-point hardware on the DECStations. (I didn't determine the bug, I think it was DEC engineers themselves.)

      Now that's a test suite!

    9. Re:TeX by TMA1 · · Score: 1

      TeX (the program) is also my answer to this question, particularly if you read a copy of the typeset code that has been processed by WEAVE and TeX.

  32. Re:Read Gabriel's Book by eGabriel · · Score: 1

    Indeed, it was this book that got me thinking
    about beautiful code again.

  33. Re:not many by eGabriel · · Score: 1

    That's a really good idea; codepoetry.net. I was also thinking maybe of a "Peer Review of the Week" type feature, where one can submit an excerpt from their current project and people can critique it line by line.

    In the Perl world, there is Perl Monks; something more ecumenical would be nice though.

  34. Re:The most beautiful code I've seen this week... by eGabriel · · Score: 1

    Heh, I had seen this one and spent a good deal of time marveling at it, and wondering if it was a good or bad thing :).

  35. Re:Dijkstra by eGabriel · · Score: 1

    I have read his "A Discipline of Programming"... it's interesting, especially now that someone has developed an interpreter for his invented language.

    Like functional programming, I can see the beauty, but it's a frustratingly slow read nonetheless. I WANT to believe I can write "provably correct" programs, but I don't suppose that will happen any time soon:)

  36. Re:You really should widen your reading scope by eGabriel · · Score: 1

    Certainly there is a lot of code to be found in books. The bibliography at the end of Code Complete is excellent. I guess I am looking more for beautiful production code in the Free Software community.

  37. Re:A suggestion by eGabriel · · Score: 1

    Ada code can be incredibly beautiful. While I am cranking out Perl somedays I wish 'use strict' enforced the same sort of discipline.

  38. Re:Facts by eGabriel · · Score: 1

    That is an acceptable definition for beauty too. The simple beauty of something that works. There are a lot of wonderful paintings of simple farm scenes. The rusted tractor, a broken wheel, a dilapidated barn, but besides the rustic feel, you get a sense that something honest is happening there; something useful and good, that works harmoniously with the universe.

  39. Re:What kind of question is that? by eGabriel · · Score: 1

    I think it's unfortunate that this comment got modded down; it's a legitimate question. I wouldn't have put it quite the same way, however.

    I guess it's obvious that a lot of people do enjoy reading code. It's part of what computer literacy is; being able to read and write the language.

    If you can't read it, or don't want to read it, I don't understand why you'd want to write it. I know some people think of programming as something to do to put food on the table, and their intended audience for the code is the machine itself and the QA department. If you are writing for any reason less than that, I don't see why you bother at all.

  40. Re:What kind of question is that? by eGabriel · · Score: 1

    I wasn't clear. You and I agree. When I say
    "any reason less than that" I am saying that
    you should first do it because you want to, because you love it, second because it's your job and you at least take some pride and making it
    actually work, but if you are doing it for some
    lesser reason than that, why do it.

    Best Reason: Love of the art
    Second Best: Pride in chosen profession
    ...
    Worst: Don't care about it at all, just want to write it and forget about it.

  41. Re:Got to be Jive talkin ! by The+Mayor · · Score: 2

    Jive sucks. Agreed. But, although I haven't looked at the sourcecode for Half-Full (or is it Glasscode?), I must say the user interface is quite unusable. To me, good code isn't just pretty to look at--it also has to be functional, and to function well. Half-full may well meet the first requirement (pretty to look at--although I simply don't know), but it fails miserably with the 2nd requirement.

    Slashcode would be an example of very functional code that does *not* look pretty. It's the flip side of the coin.

    Sorry to rain on your parade, nebby. But you need to study a little about user interface design.

    --
    --Be human.
  42. And, by extension, xdvi.... by Booker · · Score: 2
    I've never looked at TeX code, but I have this warm fuzzy thinking about how it must look. I actually haven't used TeX for quite some time, but I just always had this sense that it was done right.

    When I was using TeX, I was using xdvi as well - and that also really impressed me. Simple interface, SUPER snappy response on the gui - no animations, alpha blending, or themes...

    Click on that magnify button and zoom the window around... ahh..... does anybody write code like TeX any more?

    ---

  43. Re:The best code has lots of comments. by Doctor+Memory · · Score: 1

    MAN, that's some well-commented code!

    Weird commenting style, though -- he documents the hell out of his algorithms and data structures, but doesn't comment his code that much (no mention made of function return values or error conditions raised), and the thing I thought was weirdest -- he has plenty of #ifdef cplusplus statements, but then he goes ahead and uses '//' comments!

    Not that my malloc's any great shakes (e-mail for source)...

    --
    Just junk food for thought...
  44. Some Beautiful (And Ugly) Assembly Code by Mr+Z · · Score: 1

    In my day job, I'm occasionally charged with the task of writing code that takes our processor architecture to the limit. We're talking every cycle count, codesize is important, and functionality must not be overly compromised. I've been fairly proud of most of my results, and I think they're quite beautiful examples of what can happen when you first design a well-thought-out piece of functionality, and then optimize it to the hilt.

    In my application space, this is appropriate. I'm coding for a DSP, and the functions I'm coding are individual DSP processing steps. These are nice, separable functions that some would have us implement directly in silicon. My job is to show them that a programmable processor can do the job.

    The following links show some of these "DSP kernels" that I am especially fond of. In my opinion, this code is actually fairly well structured for assembly code. All of the hardware registers have been abstracted behind .asg directives, so that they can be given human-readable names. These names relate back to the C code description of the function (which is also provided in a comment block attached to the code). As an added bonus, comments throughout the code explain the numerous optimizations.

    In a different realm, I have a mix of beautiful and ugly code for an entirely different platform. Recently, I've written a Falling Tetrominoes Game for Intellivision named 4-Tris. The assembly code for this game is rather clean and heavily documented. The game actually implements a lightweight task scheduler and then builds the game on top of that as a series of event handlers. Of course, there are some definitely UNbeautiful bits around the edges. There's a Pong game hidden in there that's written as nearly complete line-noise. Also, the song format compiler is an absolute hackish mess.

    So, it's safe to say that my code runs the gamut from clean and clear to nearly line-noise.

    BTW, for those who are interested, I also have a Monitor Program that I wrote for the 8051/8052 microcontroller. I can't decide if it's ugly or beautiful. The problem here is that the architecture itself is downright ugly, but some of the optimization tricks in the code are either beautiful, insane, or par for the 8051 course. :-) At the very least, I consider it ugly compared to 4-Tris and the DCTs above, so...

    --Joe
    --
  45. A Search by jjr · · Score: 1

    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

  46. Re:The most beautiful piece of code... by QZS4 · · Score: 2

    Nah, try this:

    .data
    msg: .asciiz "Hello, world!\n"
    .text
    .globl main
    .ent main
    main:
    subu sp,sp,4
    sw ra,0(sp)
    la a0,msg
    jal printf
    lw ra,0(sp)
    addiu sp,sp,4
    jr ra
    .end main

    Or, why not this:

    .section ".rodata"
    msg: .asciz "Hello, world!\n"
    .section ".text"
    .global main
    .type main,#function
    main:
    save %sp,-112,%sp
    sethi %hi(msg),%o0
    or %o0,%lo(msg),%o0
    call printf, 0
    nop
    ret
    restore

    But my Sparc assembly is a little rusty, so the last one might not be entirely correct.

  47. Re:Sure, I Can by waldoj · · Score: 1

    Well, that wasn't *nothing*.

    Er...wait...

  48. Sure, I Can by waldoj · · Score: 3

    NOOP

    God, I love Assembly.

    1. Re:Sure, I Can by DrSkwid · · Score: 1

      er, the "1 file(s)" part
      .oO0Oo.

      --
      There are places where the networks are not touching,and there are places where they are-Boeing's Lori Gunter
    2. Re:Sure, I Can by pallex · · Score: 1

      I`d have used a case statement, instead of the if..else if business!

      :)

    3. Re:Sure, I Can by pallex · · Score: 1

      "No, that doesnt work, either."

      Really? Which compiler do you use?

    4. Re:Sure, I Can by pallex · · Score: 2

      Surely you mean:

      printf("%d file%scopied\n", n, &"s "[n==1]);

    5. Re:Sure, I Can by f5426 · · Score: 2

      > http://miranda-icq.sourceforge.net

      > elegant c code.

      > here is my favourite gem:

      > printf("%d file%s copied\n", n, &["s"](n==1));

      Elegant ? The one that coded that did not know C.

      A less obfuscated way to get the same result is:

      printf( "%d file%s copied\n", n, "s"+(n==1) );

      Anyway, this is too a bad idea, as those constructs are not localisable. You'd better aim at something like:

      if (n==0)
      printf( LOCALIZE( "No filed copied" ) );
      else if (n==1)
      printf( LOCALIZE( "1 file copied" ) );
      else
      printf( LOCALIZE( "%d files copied" ), n );

      for whatever definition of LOCALIZE you happend to have.

      Longer, more boring, but definitely nicer code.

      Cheers,

      --fred

      --

      1 reply beneath your current threshold.

    6. Re:Sure, I Can by f5426 · · Score: 3

      > I`d have used a case statement, instead of the if..else if business!

      Actaully, I first wrote it with an added if (n<0) { /* Error handling case */ } that cannot be dealt nicely in a switch. Then I removed the error test, because I felt it was pedantic to post it that way (more precisely, in real world, I would expect an "assert( n>=0 )" before the if/else)

      Btw, I generally avoid the switches because it is sometimes difficult to add new entries (it is not difficult, but it is error prone in the case where you need 'n<0', 'n==0', 'n==1' and 'n>=2', because you have to turn the whole switch into an if-else. I learnt the hard way to minimize changes to working code). Also, switches fails on non-integral types, so you need to master two idioms (one for the integral types, one for the floating point or function call decision tree, etc, etc)

      The less idioms I use, the less bugs I make, so I now only use switches when the tested value is an enumeration (because it never needs to be changed into an if/else), and where the default case is error handling or not used (so if I extend the enumeration I'll get either a warning or a run-time error, not a software that silently do something unexpected).

      It is a question of style, and you may feel better with a switch in that case.

      Cheers,

      --fred

      --

      1 reply beneath your current threshold.

    7. Re:Sure, I Can by Godwin+O'Hitler · · Score: 1

      What is particularly inelegant about: 1 file(s) copied ??

      --
      No, your children are not the special ones. Nor are your pets.
    8. Re:Sure, I Can by FigBugDeux · · Score: 1

      http://miranda-icq.sourceforge.net

      elegant c code.

      here is my favourite gem:

      printf("%d file%s copied\n", n, &["s"](n==1));

      I use it lots.

    9. Re:Sure, I Can by FigBugDeux · · Score: 1

      actually i meant:

      printf("%d file%s copied\n", n, &(n==1)["s"]);

      really should test my code

  49. Re:The best code has lots of comments. by Rob_D_Clark · · Score: 1

    Or use /* comments like * this */ plus some .emacs treachery to automatically format your comments for you...

    --
    --Rob
  50. not many by cabbey · · Score: 1

    I sat here trying to think of some examples for a while, but I can't. I went and looked at some of the code I have on my systems... it isn't.

    I sometimes think this is one of the failings of a lot of open source projects... without a good solid core group of people leading the charge you tend to end up with hack atop hack atop hack and various different coding styles and no coherent design. An example of that kind of code is SourceForge.

    Now I can think of at least three examples of the opposite... unfortunately they're all proprietary code bases so I can't share them.

    In many of the larger projects though you can ocasionally find bits and pieces of pure poetry in code. There's an example in the Linux kernel, I forget exactly where - maybe in the vmm, where someone took the time to fully digest a rather hairy function and they totally rewrote it without changing the inputs, output, or side-effects in a small clean block of code. These are the folks that turely deserve this shirt.

    We need a new website, one that can showcase really good code... make it known as the art form it is. codepoet.com and codepoet.org are both already taken by indivuals... perhaps codepoetry.net? make it required reading by cs students, just like trips to art museums are required of art students, and theatre and literature majors are required to study the great works of their fields. Maybe they can sell T-shirts and posters with elegant code on them, and books full of gracefull algorythms.

    For irony the site can also link to the obfuscated perl contest.

  51. What is beauty? by EJB · · Score: 1

    The Linux kernel source certainly shows some smart, lean code. But it is so lacking of commentary in the source code that it's unbelievable. It seems the whole idea is that if you can't figure out what the kernel does by looking at the C statements, you're not worth working with the source anyway.

    This may attract extremely smart people who like to code new stuff, but turns away many other types of people who normally do boring maintenance work, try to fix bugs, use existing code to add a simular feature, etc. etc.

    I personally prefer source code that is doesn't hurt the eyes when you look at it a few weeks after the previous time: many comments, empty lines and whitespace inserted to identify logically seperate parts of the code, etc, etc.

    Erwin

  52. Andrew Tannenbaum's original Minix by AReilly · · Score: 1

    Sure, it's a bit limited as an OS by todays standards, but architecturally it's neat enough, and small enough and readable enough to be printed in its entirety in the appendix of a book which describes the theory behind it. So you could think of the first half of the Minix book as one enormous meta-comment for the rest of the code, perhaps.

    It's nice, clean, traditional C style, too.

    From that perspective, the Unix of the Lyons book is pretty readable too.

    For something non-C, the source of the SmallEiffel compiler and it's libraries (all in Eiffel of course) is a pretty nice read too. CVSup (in Modula-3) is nice. Read lots of things, in lots of different languages. Some languages seem to lend themselves to clarity of expression a little more than C or C++ do. I don't think I've ever seen C++ code that was beautiful to read.

    --
    -- Andrew
  53. Classic code by edhall · · Score: 2

    It's old-style C code, but in terms of overall structure and organization it's hard to beat the original Bell Labs Unix. Now that the Lions commentary on 6th Edition Unix is generally available (Lions' Commentary on UNIX 6th Edition, with Source Code; ISBN 1-57398-013-7), you can both read the code and Lions' brilliant commentary on it. It's amazing what a few thousand lines of carefully-crafted code can do; most text editors and mail readers are larger than the original Unix kernel.

    Don't read this to learn how to program in C -- the language has grown enormously since this time, often in ways that allow for better style and consistency-checking. But do read it to see how to program with a clean, modular design and carefully thought-out organization, and probably learn more about operating systems per unit time spent than you would reading anything else.

    -Ed
    1. Re:Classic code by Gremlin77 · · Score: 1

      Speaking of classic code, I've always been extremely impressed with Hoare's quicksort (1962). The recursion is pretty cool. Refer to the C standard library to see its implementation (qsort).

      Recursion is a good thing, unless its with taxes.

  54. Re: Personal recommendation by dne · · Score: 1

    The "bugs" are in the design of the interfaces. That's pretty hard to fix w/o breaking the standards.

  55. Beautiful Software by chris_sawtell · · Score: 1
    Assuming you are serious, this is the home of some of the most beautiful software ever written.

    http://www.tug.org/

    Note to moderators: Small, but informative posting

  56. Elegant beautiful code? try perlmonks.. by dallen · · Score: 3
    I've seen more elegant code on 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?

  57. Re:Got to be Jive talkin ! by nebby · · Score: 2

    Though it's still pretty ugly, and apparently not as elegant, my servlet forum software might interest you.

    --
    --
  58. Re:The most beautiful piece of code... by domc · · Score: 1

    #!/usr/bin/perl -w

    print "Hello World\n";

  59. Re:The best code has lots of comments. by Omnifarious · · Score: 1

    Hey! That's what I do. If you're editor isn't big and bloated enough to reformat block '*' comments like that, then you're using the wrong editor! *grin*

    Actually, I have to do it that way because I run the source files through a documentation generator and it needs to comments to be of that form. Besides, it does help set comments apart for people who don't have color syntax highlighting.

  60. Re:The best code has lots of comments. by Omnifarious · · Score: 1

    I agree with this pretty strongly. I think code should be good enough to stand on it's own without comments. The best code I've seen has this property, and it's a quality I strive for.

    IMHO, comments are best used to describe overarching design issues, or particularily tricky algorithms that, even with well named variables and well structured code, are difficult to understand.

  61. It's right under your nose. by mrsam · · Score: 1
    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.

    ---

  62. Re:Emacs Source Made Me Decide to Remain a Program by joshv · · Score: 1

    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

  63. Re:Emacs Source Made Me Decide to Remain a Program by joshv · · Score: 1

    No, but people who are sloppy in one area tend to be sloppy in others.

    And no, not asking for any specific aptitude in graphic design - a pure white background would have been better than that crap web site.

    -josh

  64. Re:NeoMail by LawnMowerMan · · Score: 1

    Actually, this security flaw was fixed quite a while ago.

    Do yourself a favor and check out the newer releases (I'm running NeoMail 1.20pre4 and have never had a single problem and has no security flaws that I'm aware of or have heard about...) *grin*

  65. NeoMail by LawnMowerMan · · Score: 3

    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.

    1. Re:NeoMail by Bedemus · · Score: 1

      As the author, I have to admit I dropped the ball on that... the session timeouts will make this fairly difficult to pull off unless you can be watching a webserver's logs at the time a user reads a boobytrapped mail and hijack the session before the user logs out or a timeout expires, though.

      With all due respect, though, if you read the code and found a bug and didn't report it, then shame on you. That's the whole point of open source, isn't it?

      Like I said though, still, a mistake on my part.. Bugs happen. I was much more focused on validating input to avoid server compromises than someone reading someone else's mail... I do my best to think deviously when coding, to catch stuff people may try, but something slipped by my radar because I got tunnel vision.

      Feel free to fire off an e-mail to me to discuss this further, though. I'm interested in hearing what about my code makes you think it's so awful, because it had one bug. I'm only human, ya know. You've gotta tell me when I screw up! :)
      --
      NeoMail - Webmail that doesn't suck... as much.

    2. Re:NeoMail by rgmoore · · Score: 2

      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.

      --

      There's no point in questioning authority if you aren't going to listen to the answers.

    3. Re:NeoMail by happystink · · Score: 2
      Nope, session timeouts sure didn't, the way I discovered it was when someone's url showed up in my logs. I went to it and got right in.

      The fact it's fixed doesn't matter to me though: if they missed something THIS basic, what else are they missing?

      sig:

      --

      sig:
      See the "..for smart people" banners Wired runs here? Look elsewhere guys.

    4. Re:NeoMail by happystink · · Score: 3
      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:

      --

      sig:
      See the "..for smart people" banners Wired runs here? Look elsewhere guys.

  66. Re:Not anymore, Dorothy . . . The Mainframes are D by Zico · · Score: 1

    Sure, but in their efficiency, they gave us the Y2K problem. Last I heard (in January or February 2000), the costs devoted to fixing it may have exceeded £400 billion (~ $580 billion US). Thanks, guys? :)


    Cheers,

  67. Re:The best code has lots of comments. by crispy · · Score: 1

    I did that in a cs class of mine. It was abundandtly obvious. The grader agreed w/ me but I still lost points. Now that I am in the real world I javadoc every function I write. It is obvious to me, obvious to any other programmer... but is it obvious to everyone?

    <SIG>
    I think I lost my work ethic while surfing the web. If you find it, please email it to crispy@crotch.caltech.edu.
    </SIG>

    --
    My sig has a broken link in it.
  68. Well.. if it's minimalism you're after.. by mcc · · Score: 1
    for(int *p=0;;*(p++)=0);
    "The simplest Surrealist act consists of dashing down into the street, pistol in hand, and firing blindly, as fast as you can pull the trigger, into the crowd."
    --André Breton, Second Manifesto of Surrealism
  69. Re:Personal recommendation by sethg · · Score: 2
    I can't help but think that it would be better code if it noted the flaws in the standard routines and either avoided them or wrapped them instead of replacing them outright.
    Bernstein wrote his software to run on a wide range of Unixoid systems, and the software performs security-sensitive tasks (mail, Web, and DNS service, for example).

    If you were in his position, how much effort would you want to spend keeping track of which routines were safe in which versions of which OSs -- particularly the closed-source Unix varieties? And if an upgrade to an OS introduces a security flaw in a routine that was previously safe, would you want to drop everything to get out a patch for that OS's users?

    In this case, having a whole package of reimplemented routines that you know are safe strikes me as the lesser evil.
    --

    --
    send all spam to theotherwhitemeat@ropine.com
  70. Re:The best code has lots of comments. by Fizgig · · Score: 4

    The best-commented code I have ever seen is Doug Lea's malloc, or dlmalloc, the malloc used in glibc, among other places. I had no idea how a malloc would work, and I wanted to write one for my OS class, so we looked at the dlmalloc source code. MAN, that's some well-commented code! Not only does it explain what individual functions do, but it also explains each general part of the algorithm in excellent detail. And it's malloc; it better not have any bugs!

  71. Re:And it's down to 3! by FunnyBunny · · Score: 1

    Do you people *really* have nothing better to do? Does Microsoft really hurt you that much? Do you really think that the world is meant to be perfect and the software industry owes you something? What? Oh, you're thirteen! Of course...

    The appallingly bad API that Microsoft provides with their tools is a very good reason to dislike Microsoft. In answer to you question, "did Microsoft hurt me?" Yes they did. Their incredibly poor level of documentation, coupled with an almost complete disregard for decent coding style, and the near constant abuse/redefinition of C++ has cost me more time that I care to consider when trying to do my work. I can accept the occasional use of void pointers when passing data to a function in C++, but having somewhere between 30 and 50 percent of the functions in the API use one or more void arguments is completely unacceptable. The failure to provide decent examples/documentation for MFC is also unacceptable. When I am required to use MS products, that we had to pay a premium price for, I expect the products to be well documented and work correctly. Microsoft's development tools fail to meet both of my expectations, so I would have to concur that Microsoft is not the place to look for good code.

  72. Re:And it's down to 3! OT by FunnyBunny · · Score: 1

    Though I agree that most MS APIs are bad I also understand why they haven't been changed. Why are we still using sprintf instead of snprintf? Compability comes to mind. We are trying to keep source level compability with other UNIXes where MS is trying to keep source level compability with other versions of Windows(TM). In addition to compability problems changes would render current knowledge on MFC etc. completely useless. I'd think that those void pointers are there for historical reasons only.

    I would prefer to have to completly relearn the API instead of having to deal with MFC. As best I can tell, MFC is a nasty kludge on top of the WIN32 API, which does go a long towards explaining the abundence of voids. Since a price was already being paid to have C++ wrappers for many functions, it would have made more sense to have the conversions to void done inside the wrappers.

    Source level compatibility is a wonderful thing as long as it doesn't actually hinder work. In the case of windows, I think it would be a far better piece of software if teh just made a clean break with the past. Heck, they could provide some form of emulation for compatibilty, it's not that hard.

    If you still disagree think about X and xlib. Why are we still using API that doesn't have any support for alpha blending, vector graphics, decent pixmap filtering etc. features supported by hardware in current graphics chips. We don't have even anti-aliased fonts which I myself take for granted in every other OS I use these days.

    Let's not even get into X and xLib, just suffice to say X and xLib suck in their own particular ways. My current gripe with X is broken header files that use implicit type declarations, yet another bad practice.

    I wouldn't call MS documentation poor. Perhaps they don't give you all the documentation for free, but there good documentation for the areas MS wants the developers to know. Sure there's undocumented features that MS uses in its own software and others follow with reverse engineering. It's MS source and it's up to them what they want to tell about it to developers.

    I would call MS documentation poor, particularly when we did pay for it. One fine example is changing the title of a window. It took considerable time to figure out what should have been an easy task. If I pay Microsoft for development tools and documentation, I expect both to be useful. I have found books written by people who claim to have been associated with the design of MFC to be more useful than the docs with MFC. The problem here is that I shouldn't have to line the pockets of someone who couldn't be bothered to do the documentation right the first time.

    If you don't like MS APIs or their OS don't support them. Notice that if you don't make programs for their OS you don't need to care about their API quality. What comes to coding style (I assume you mean code formating)... for example I cannot stand GNU coding "standards" - fortunately I have indent.

    Not supporting an OS because I don't like it is a luxury I did not have. The customer unfortunatly convinced the boss that MS was the only acceptable platform. Quitting the job was not a viable option.

    Coding style refers to more than simplty formatting. It also refers to how language constructs are used. Void pointers exist for compatibility, not for passing the same data type to a function every time. To use void where a specific type can (and should) be used is poor coding style, particularly in C++ since it defeats type checking.

    The fact that MS does provide some old ugly APIs doesn't automatically suggest that MS couldn't be perfect source for look for good code. Unfortunately MS seems to keep most of it's code secret. Do you really think that company that hires every top quality coder it can get would generate only bad code?

    I didn't claim that the MS programmers like the state of the code. I did however claim that their code does not meet my standards. Regarding your question, I can only make judgements on the code I can see.

  73. Re:And it's down... but wait! by FunnyBunny · · Score: 1

    Have you guys ever heard the saying "IF YOU DONT LIKE IT, THEN DONT USE IT!"

    Nice idea in theory, but almost completely impractical in reality.

  74. Personal recommendation by mattbee · · Score: 4

    People seem to be mentioning the obvious targets: Knuth, BSD etc. but I notice nobody has mentioned Dan Bernstein's projects, notably qmail. This guy basically didn't trust the standard C library routines for security and wrote his own string handling, file processing etc. based on a few system calls. He also splits up his programs into separate binaries as much as possible and is very, very minimalist in other ways too. The code seems quite impenetrable at first, I'm not sure beautiful is the right word, but it's certainly an education.

    Also worth a read is Sam Latinga's C++ port of the classic Mac game Maelstrom. The actual code of the game is surprisingly small and very well-written.

    Oh, and while I think about it, the InfoZip sources are a real surprise too-- I mean this code is one of the most portable pieces of code you'll ever see; they're a very good example of the sort of lengths you'll need to go to in order to achieve this kind of portability, and it's still elegant in my opinion.

    --
    Matthew @ Bytemark Hosting
    1. Re:Personal recommendation by cpeterso · · Score: 2

      I can't help but think that it would be better code if it noted the flaws in the standard routines and either avoided them or wrapped them instead of replacing them outright.

      Or perhaps he should report the supposed bugs to so they can be fixed for everyone else.

    2. Re:Personal recommendation by Salamander · · Score: 2
      This guy basically didn't trust the standard C library routines for security

      In this particular case the author might have had good reasons, but in general reinventing the wheel is not a mark of good code. I can't help but think that it would be better code if it noted the flaws in the standard routines and either avoided them or wrapped them instead of replacing them outright.

      --
      Slashdot - News for Herds. Stuff that Splatters.
    3. Re:Personal recommendation by Salamander · · Score: 2
      In this case, having a whole package of reimplemented routines that you know are safe strikes me as the lesser evil.

      ...but still an evil. As I said, in this particular case the author may have had good reasons for replacing standard routines. In the grand scheme of things that might not make his code bad, but it can't really be listed among the things that make it good. The code's minimalism and modularity, which you also mention, are much more encouraging.

      --
      Slashdot - News for Herds. Stuff that Splatters.
    4. Re:Personal recommendation by Salamander · · Score: 2

      I've seen more bugs introduced by gratuitous rewriting than by any other single cause. You see, there's a lot of code out there that really does mostly work, even if it's poorly designed, except for a couple of bugs. You can fix those couple of bugs - patching a bad design - or you can replace it with a new version which fixes those two bugs but introduces twenty new ones. I've seen it time and time again.

      In fact, "rewrite fever" mostly seems to afflict programmers whose egos far exceed their skills. They assume that if code is hard to understand it's because the previous author was an idiot, not because they themselves lack knowledge. They also believe that they can replace in half a day what took someone else weeks to write and debug. What usually happens is that they only realize after they've done the rewrite that the old code solved or avoided some problems they hadn't even been aware of, so they start patching the new version. The net result is new code that's every bit as messy as the old, and nowhere near as well tested.

      Better programmers prefer surgery to amputation. It takes far more skill to develop the thorough and subtle understanding of code required to fix it in place, but when possible it's preferable. Rewrites should not be attempted without knowing exactly what the new code needs to do (ideally expressed in the form of thorough regression tests), and that usually requires careful study of the old code. You just can't get around that need to understand the original, and anyone too lazy or too proud to try definitely shouldn't be allowed to write any new code.

      Yes, there is a point where a particular piece of code collapses under the weight of all the patches and workarounds and needs to be replaced outright. Amputations are sometimes necessary, but only a skilled surgeon should be allowed to make that call. Patching a bad design is often the best - and certainly the most cost-effective - way to get better code than you started with.

      --
      Slashdot - News for Herds. Stuff that Splatters.
    5. Re:Personal recommendation by codepawn · · Score: 1

      yeah right !

      And we all know that the best way to get secure reliable code is to continue patching bad designs again and again. And of course this will never lead to more bugs in already flawed code will it ?

      Duh !!

  75. I got your beautiful code... by Mr.+Piccolo · · Score: 1

    ...right HERE!

    --
    Glückwünsche, haben Sie Slashdot ermordet, indem Sie zum korporativen Druck beugten und Subskriptionen einlei
    1. Re:I got your beautiful code... by Da+Masta · · Score: 1

      Well atleast its not a goatce.sx link.

  76. Why just code... by platypus · · Score: 5

    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)

    1. Re:Why just code... by shippo · · Score: 2
      I had to amend one of the lesser sound card drivers to work with my card. The code for the driver was a mess, mainly due to the number of IFDEFs for different card sub-types, and little in the form of comments.

      But the worse code I saw was the UMDOS FS prior to 2.2. I needed to run this driver for an obscure reason, and attempted to try this with the 2.1 kernel. It didn't work, and I looked at the code. A mess of unexplained comments and error messages, most derived from abbreviations in a language other than English spoken by one of the original authors. No wonder it took the new maintainer over a year to get it working again.

  77. Content, Content, Content by LionMan · · Score: 1

    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.

    --
    -Leo
    1. Re:Content, Content, Content by joto · · Score: 2

      Yeah, I'll take Function before Fasion any day...

  78. Dave Cutler by cpeterso · · Score: 2

    I used to work at Microsoft as a tester for Windows NT 5 (pre Windows 2000). I had read the "required reading" of "Showstopper" and was curious to see Cutler's code. I found his assembly code for NT spinlocks and it was highly commented and very elegant.

    When I was at school at the University of Washington, one my profs worked with Cutler at DEC. He said Cutler would print out his code into two piles: code and tests. My prof said the test code pile was 3x taller than the shipping code. Cutler is a huge stickler for testing your own damn code! ;)

  79. Documentation is not just in the comments... by meldroc · · Score: 1

    Martin Fowler said it best in his book Refactoring: Comments are a good thing, but they are frequently used as a deodorant to cover up bad smelling code. I prefer to write self-documenting code. This means that I do little things like choosing meaningful variable names, using whitespace to group code in small digestable chunks, choose expressions for their understandability in the same way I choose English phrases, use common idioms used in the industry for whatever language I'm using, and try to use good coding practices in general. There are cases where it is impossible to show in the code itself why something is done, in that case, I'll use comments, but I'll also ask myself if there is a better way to write the code so it doesn't need explanation. In any case, I try to avoid "x++; // Add 1 to x".

    --

    Meldroc, Waster of Electrons
  80. Beautiful... sort of ! (beautiful obfuscated C) by Cedricm · · Score: 1

    See http://www.ioccc.org/

    Cool stuff !

  81. Re:Functional Programming by _Splat · · Score: 1

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

    --
    -Splat
  82. Re:Functional Programming by _Splat · · Score: 1

    Well, it's not completely functional, since most implementations now support side-effect functions, but many coders frown on their use. It is, however, most definitely the ugliest language I've used.

    --
    -Splat
  83. Re:The best code has lots of comments. by hugg · · Score: 2

    I agree... though I believe you shouldn't comment every single function you create, if they are obvious, because it dilutes the value of the REAL valuable comments that explain difficult-to-understand sections. Like one comment in the JDK I remember:

    Reference getRef()
    /* gets the ref */

    Or something like that... who needs it?!?

  84. One Great Programmer by sohp · · Score: 1

    Among the best code examples in open source are those written by or lead by a single insightful programmer. Two that come to mind immediately: Perl (Every source file has an orthogonal but relevant epigram), and InterNetNews

  85. The best code has lots of comments. by Dr.+Tom · · Score: 5
    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.

    1. Re:The best code has lots of comments. by chris.bitmead · · Score: 1

      I have to strongly disagree too. For the argument against commenting see Extreme Programming. If you can't understand your code without comments, REWRITE THE CODE AND ADD UNIT TESTS. I can't emphasise this enough. If the code is obscure the chances the code is bad or the variable names not descriptive or the design is poor. I'm not saying don't use comments. I'm just saying only comment what is necessary, but try fixing the code first instead of applying the band-aid of comments.

    2. Re:The best code has lots of comments. by wuice · · Score: 1

      I know several women coders. And yes, they do. Women are a lot less magical once you actually get to know some of them.

    3. Re:The best code has lots of comments. by leo.p · · Score: 1


      remember code is CODE, it's meant for a stupid machine, not an intelligent human), maintainability, etc.


      This is bullshit. The best code is only very sparsely commented, relying instead on the clarity of its design, its data structures and it's use of the language, itself. Your principal form of documentation should be the CODE itself.

      I loathe reading heavily commented source, especially in OSS projects which are rife with barely literate morons, endlessly cutting and pasting each other's code and further obfuscating it with every turn as they propagate subtle misunderstandings down the line.

      You very rarely should have to tell someone what you're doing, merely showing it should be enough. If you have a clever algorithm, isolate it in a single source file, document it in words and psuedo code at the very top, then show me the money.

      It is a mistake to comment for rank beginers begin they cant do shit with the code, anyway. Document for people who are in a position to actually use and modify your code. Over commenting also makes it harder to understand what the fsck it is you were trying to do when the comments fall out of synch with the code and/or contain various prose and typographical errors.

      Again, comment sparsely, code well. A one or two sentence description of the function, its arguements, and an enumeration of the global variables it modifies. Most everything else belongs in a man page, in its _specification_ (something that is almost always an afterthought in Linux.)

      If you cant do this with your functions, your code is badly designed and no amount of commenting will fix that.

      As to the original question: The apache source is very cool. BSD userland is very good and very well laid out: one directory per command and right there, next to main.c in an ls, the man page source. Now _that_ is fucking class. Anyone who recommends the Linux kernel as a model of good style has a penguin up his ass. It is horrid in most places, a thing of beauty only rarely here and there. It is also terribly laid out in the filesystem and uses too many features that are particular only to the Gnu C compiler.

      The best examples of style can be found in any book whose authors include: Ritchie, Kerninghan, Plaugher. (I'm sure I've butchered the spelling of their names.)

    4. Re:The best code has lots of comments. by FireWhenRady · · Score: 1

      I find that the most useful comments are those that explain the data structures used and the reasons for the approach taken in the code.
      I can normally read code but I often need to kn ow the range of possible valuies of a function return or the assumptions made about string sizes etc. These are not part of the code iteslef so they need to be in comments.
      But comments that just repeat the code in English get in the way.
      Code like
      x++; /* Increment x */ waste time and space.
      But comments like
      linecounter++; /* Line counter has count of lines printed so far */

      help me understand code.

    5. Re:The best code has lots of comments. by KilobyteKnight · · Score: 1

      I comment sparsly. Typically I only comment the items I think I myself might forget down the road. I've got one word for you: Deadlines.

      Beauty, no; job security, yes.

      --
      When will Windows be ready for the desktop?
    6. Re:The best code has lots of comments. by alvi · · Score: 1
      The best code has quality comments.

      Thanks for writing in a more consise way what I really wanted to say. I never meant that comments are useless and should be avoided (other replies to my post completely missed my point).

      When people are looking for lots of comments, they're looking for the wrong thing. They should look for useful comments, and cleanly written code.

    7. Re:The best code has lots of comments. by alvi · · Score: 1
      Guys like this ("dammit, I'm a programmer, not a technical writer," "the first thing the compiler throws out are the comments," "it was hard to write so it should be hard to read," "/* You wouldn't believe what this does if I told you. */," "the source is always the best explanation and it's never out of date") seem to keep me rolling in cash. I always end up being hired to fix these peoples' code, and

      I'm pretty sure you never had to debug any code of mine or code from people like me.

      [SNIP]...much work I get from guys like this? (Yes, always guys, would you think a woman would have that kind of egotistical attitude about coding?)

      Rather than turning this into a silly war between genders, you could have read what I really wrote. If you need to reverse engineer comments in order to understand what the code is doing, then you're clearly not talking about good code. In case you didn't notice: This thread is about well written code.

    8. Re:The best code has lots of comments. by alvi · · Score: 2
      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.

      I wholeheartedly disagree. There are a lot of people around who sing the same song about "it's all about the comments..." I feel strange whenever I hear such claims.

      First of all, if someone is supposed to maintain a piece of code, he or she has to read the code (not the comments!) and understand it. Period. In most of the cases, its even better to just forget about the comments at all. Comments won't be translated into machine code... but the source code will, and that's what's going to run in the end. It's unlikely that a programmer will adjust all the comments (if there are changes in the code) to be completely consistent all the time. You simply can't trust comments.

      Thus, the more comments a code has, the more I try to ignore them.

      Now, I'm not saying good code has no comments, I just disagree with your your claim:
      The best code has lots of comments.

      Comments won't guarantee you good code, (and of course the lack of them won't guarantee you anything either.) There is good code around with plenty of comments, but there is also great code that is nearly comment free. You can find excellent examples at Dan Bernstein as an example.

    9. Re:The best code has lots of comments. by mckyj57 · · Score: 1
      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. */

      If you have a reasonable programmer's editor this is not necessary. My favorite, vim, allows you to simply highlight the block and press a key. Any comment with a standard beginning character (#, *, >, etc.) will be reformatted with the quoting character re-inserted appropriately. It is trivial to write a filter to do this -- use your favorite programming language and comment it well if you like. 8-)

    10. Re:The best code has lots of comments. by ebbe11 · · Score: 1
      In most of the cases, its even better to just forget about the comments at all. Comments won't be translated into machine code... but the source code will, and that's what's going to run in the end. It's unlikely that a programmer will adjust all the comments (if there are changes in the code) to be completely consistent all the time. You simply can't trust comments.

      Compilers have bugs too. If you want to be absolutely sure what the program does, you should read the assembly code output from the compiler - or better yet, the binary program produced by the linker...

      ...and so on ad absurdam.

      And yes, I have just experienced the very situation where comments differed from the code. They don't any longer - and they won't while I'm responsible for that code.

      --

      My opinion? See above.
    11. Re:The best code has lots of comments. by hardburn · · Score: 1

      You can't trust code either.

      Then what can you trust???

      In a perfect world, all programers would keep a perfect balance between comments and actual code, and the comments would allways be updated with the code.

      However, remeber that without comments, we wouldn't have these:

      /* Drunk. Fix later. */

      # You are not expected to understand this

      ; I don't know how this works, but it does. Don't touch it.


      ------

      --
      Not a typewriter
    12. Re:The best code has lots of comments. by MidnightLog · · Score: 1

      First of all, if someone is supposed to maintain a piece of code, he or she has to read the code (not the comments!) and understand it. Period.
      This is very true. Code still needs to be commented however, so that programmers can easily find things that they need to read and understand. I also find it helpful when (I/O) files and variables have a one line description where they are defined (so I don't have to check external files or a data-dictionary to see what something is for).

      In most of the cases, its even better to just forget about the comments at all. ... It's unlikely that a programmer will adjust all the comments (if there are changes in the code) to be completely consistent all the time. You simply can't trust comments.
      If you have been given reponsibity for a program and the comments in the code are that bad then either rewrite them or delete them. Forgetting about the comments doesn't help anyone - its just irresponsible and lazy. On the other hand, if some other programmer, who you don't like, is responsible for the code and you are just making a one-time change then definitely ignore the comments. Make sure that you don't add quality comments of your own either.

      Comments won't be translated into machine code... but the source code will, and that's what's going to run in the end.
      This attitude just burns me. The source code isn't just for the machine; Its also for you (the programmer). If this wasn't true then the open source movement would be pointless.

      Now, I'm not saying good code has no comments, I just disagree with your your claim:
      The best code has lots of comments.
      I have to agree with you (alvi) here. The original poster was wrong (but close). He should have written:
      The best code has quality comments.
      --

      To understand what's right and wrong, the lawyers work in shifts ...

    13. Re:The best code has lots of comments. by Ghostface+Postah · · Score: 1

      Guys like this ("dammit, I'm a programmer, not a technical writer," "the first thing the compiler throws out are the comments," "it was hard to write so it should be hard to read," "/* You wouldn't believe what this does if I told you. */," "the source is always the best explanation and it's never out of date") seem to keep me rolling in cash. I always end up being hired to fix these peoples' code, and because there's no comments the average programmer can't even figure out how it was supposed to work. So I just reverse-engineer the comments and then rewrite it as I read it from the comments, and the end result is always better than what I start with. Did I mention how much work I get from guys like this? (Yes, always guys, would you think a woman would have that kind of egotistical attitude about coding?)

    14. Re:The best code has lots of comments. by Ghostface+Postah · · Score: 1

      My condolences -- the most interesting women I know are quite the opposite.

    15. Re:The best code has lots of comments. by The+NT+Christ · · Score: 1
      I agree that comments are useful, but too many comments isn't a good thing either.

      Firstly, comments are often not maintained. You can say this is the fault of the maintainer, but with the best will in the world mistakes happen.

      Secondly, plenty of people write tons of comments but their code is still unreadable. Code should be clear, concise and shouldn't use tricks of the language like:

      if (a = (b == c))

      Adding a comment to excuse bad coding style is awful ... it's better to write the code better and lose the comment.

      The aim, in my opinion, is for self-documenting code. This is impossible in assembler. It's very difficult in C. But once you migrate to C++, then if you have a good design and good names you need very few comments. Most short methods don't require any comments at all, and adding superfluous comments is worse IMHO than having none - they get out of sync with the code.

      Your analysis that people who don't comment are "lazy, sloppy, and [don't] care whether or not [their] code is maintainable" is unfair in cases like this. When using a language like C++, too many comments is often a sign of bad design.

      Oh, and there are programmers who don't comment their code because they understand it so well. I work with one. He has a photographic memory, and actually can remember how code he wrote 5 years ago works. It's a pain working with him, but I still wouldn't describe his as lazy or sloppy - just hard to work with!

      --

      I didn't pay for my operating system either

  86. Find something interesting by noims · · Score: 1

    Several times I tried looking to what was supposed to be good code. I just found it really hard to grasp it all practically.

    Then I happened to be looking through the source for Nethack, which I was playing like a junkie, and kept spotting neat tricks, several of which I subsequently used in the project I was on at the time (I always knew playing Nethack in work would do some good eventually).

    Anyway, I found that by choosing something I was really really interested in, that's very optimised and generally well written, it held my interested and I still pick up wee gems.

    CHeers
    Noims.

    --
    This is not the greatest sig in the world. This is just a tribute.
  87. JAVA: look at Lucene but NOT Turbine by skelf · · Score: 1

    For Java code afficionados, I'd heartily recommend taking a look at Lucene. It's small but pretty. One particularly bad example of code out of control would be Turbine. The latter is very frustrating because they generally have great ideas and lots of energy, but wading through the convoluted class hierarchies and gratuitously overloaded methods (some of which must be called more than once with different arg types) is not for the faint of heart.

  88. The C Library by chris.bitmead · · Score: 1

    Often you'll find pretty cool code in the C library. I havn't looked much at GNU libc. The whitesmith's c library used to be very cool (what happened to that??). Anyway here is some cool code...

    char *strcpy(char *c1, char *c2) {
    while (*c1++ = *c2++)
    ;
    return c1;
    }

  89. Re:Screw commenting!! by ConceptJunkie · · Score: 2

    The sad truth is that I work with people that pretty much have that attitude. Maybe that's not what they intend, but that's the result. When I've asked how to make a change to a JavaScript parser, I was told: I had to trace through the code, so you should too. This coming from the guy who requested the change. The thing is, when I pressed him for more information, he finally explained enough that I was able to make the fix in a couple of minutes, otherwise it would have been hours.

    --
    You are in a maze of twisty little passages, all alike.
  90. Quake!!! by DaEvOsH · · Score: 1

    Get the quake source code. Very interesting, more even if you are into gaming or graphics.

  91. Re:Hello World Seven Ways by SeanAhern · · Score: 1
    This has got to be some of the neatest code I've seen!

    Granted, it's not that pretty or beautiful, but it's clever, and it's not that obscure once you look at it for a bit. Basically, the code that isn't for a particular compiler is commented out in that language. The neatest part was how they figured out how to make a comment block in all seven languages!

  92. Re:The most beautiful piece of code... by maw · · Score: 1
    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.
    --

    --
    You're a suburbanite.
  93. Re:The most beautiful piece of code... by maw · · Score: 1
    Ah, yet another holy war, right up there with vi vs emacs.

    No, I maintain that it is not a holy war: holy wars always concern personal preference; the tabs vs spaces debate is one of technical interoperability.

    ...but the way to solve that problem is to fix the editor, not the code.

    I disagree, and rather than repeat the arguments myself, I point you here.
    --

    --
    You're a suburbanite.
  94. Dijkstra by az · · Score: 1

    Aside from Knuth there is Dijkstra. He put a lot of emphasis on algorithms, and hence code, being beautiful. His values of beauty are primarily from a mathematical point of view.

    A classic on algorithms expressing Dijksrtas values is his book 'A discipline of programming' (ISBN 0-13-215871-X).

  95. hard to identify beautiful code by J.J. · · Score: 3

    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.

  96. This is not off-topic. Lousy moderation. by BeanThere · · Score: 2

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

    Some of the most "elegant and masterful design" I've ever seen is code from the obfuscated C coding competition (http://www.ioccc.org/); it may often look pretty atrocious to the "untrained eye", but there are some pretty amazing examples of masterful design - and good design is something beautiful in itself, no matter how aesthetically displeasing it may be to the average Joe's eye. Huge industrial structures like, say, oil rigs, often look ugly to the general public, but I guarantee you, to the engineers who design and build such things, the people who can appreciate the achievement in building such things, they are often seen as beautiful.

    So explain to me how exactly this post is off-topic? When did /. moderation become so lousy?

  97. Re:id software: doom, quake by BeanThere · · Score: 2

    I wasn't as impressed as you seem to be, at least not with the Quake1 source code (I can't comment on the doom source code). It certainly wasn't bad code, it was relatively well thought out, and relatively neat, but poorly commented, and the use of #define's and the plentiful use of function pointers in some cases made it pretty obscure and confusing to determine what was getting called when, and what parts of the code were supposed to do what (particularly since comments are so scarce.)

    of course, the only part I looked at though was the socket-level network code, so perhaps the other parts were better, I don't know. But I don't remember being overly impressed with the code. Not unimpressed, but not impressed either.

  98. Re:34 Line Web Server by nchip · · Score: 1

    uh. to a nonperl programmer like me - that looks more like line noise than anything beatiful.

    --
    signatures pending - ansa@kos.to - (dont mail there)
  99. www.altivore.com by RobertGraham · · Score: 3
    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.

    1. Re:www.altivore.com by Karellen · · Score: 1

      Sorry - I've been trying to parse one sentence in here for a while now.

      What do you mean by 'map structures on top of pointers'?

      (Note : I'm a professional C coder and have been for 4 years. I've known the language 3 years longer than that. I just can't extract the meaning from the sentence)

      --
      Why doesn't the gene pool have a life guard?
  100. Re:The Story Of Mel by Mock · · Score: 1

    Actually, if you look at the assembler output of that code versus using a dummy structure as the head of the list and testing based on pSrch->pNext, you'll notice that your version is slower to execute in the main search loop.

    I'd post a more detailed explanation, but Slashdot's wonderful "lameness filter" forbids me to post any code.

  101. Re:Functional Programming by msaavedra · · Score: 1
    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?"
    --
    "Any fool can make a rule, and any fool will mind it."
    --Henry David Thoreau
  102. Try Smalltalk by ericlondaits · · Score: 1

    Most I learned about *good* coding I got from an OOP course I took. There are a couple of factors that explain this:

    * In every Smalltalk environment most of the source is open.

    * The code for the main methods of the main classes is mostly standard... probably as pretty as it can be.

    * Code sharing is a *must* in the smalltalk community, hence good programmers try to make code very easy to understand (the best kind of code, in my opinion).

    * Certain features of the language (inheritance, polymorphism, code blocks, etc.) make for very modular code and very short and to the point methods.

    If you're interested in OOP you should give Smalltalk a look... there are many freely available environments, like Squeak, Smalltalk Express, Dolphin Smalltalk, etc. I also recommend Kent Beck's 'Smalltalk Best Practice Patterns' which is a very good coding style guide that mostly applies to smalltalk, though you can apply a couple of the rules it presents to Java and C++'. Also, the book 'Refactoring' by Martin Fowler (Addison Wesley) is worth a look, as it teaches (with Java examples, tough it also applies to C++ and Smalltalk) how to make code that's easy to change, easy to read, non-redundant and very modularized.

    --
    As a Slashdot discussion grows longer, the probability of an analogy involving cars approaches one.
  103. WUStL's ACE library (and TAO ORB) by jmegq · · Score: 1
    The ACE and TAO libraries from Wash. U. St. Louis are, in my opinion, excellent collections of code to read and understand. They're C++, which is in some ways all the more amazing.

    Even better, they make use of Design Patterns, Extreme Programming concepts, and other great software engineering practices (and as an added bonus: nice, friendly, insightful discussions minus the egos on their mailing lists).

    The source code is free for the taking (very liberal license), super-cross-platform, and you can buy solid commercial support if you like.

    It's good stuff; check it out.

  104. Re: Building ACE + TAO by jmegq · · Score: 1
    Good thought -- the ACE crew has created an automake/autoconf based build environment for ACE, and they're working on getting TAO fully building that way as well. That takes care of the building and installing woes, which to be sure can be a pain.

    While ACE is "hard to use" at first, I think this has a lot to do with inherent complexity; the patterns and OS-level stuff it takes on are really deep issues, and aren't likely to go away any time soon. ACE does a great job reducing the accidental complexity of a system, and for that reason it's well worth the (significant) investment of learning, I think.

    Honestly, though, the size of the build tree is not something I worry about as a programmer; if a gig or two of an well-designed framework are going to make my life easier and my code better (more portable, higher performance, easier to review, easier to debug, free of memory leaks), then it's a gig well spent. Besides, 80GB drives are cheap :)

    (Of course, the ACE folks cheat; their quad Xeon boxen burn through a complete ACE+TAO build in a few minutes).

  105. Re:34 Line Web Server by Salamander · · Score: 2

    That's actually an example of very bad code. Besides its obvious aesthetic shortcomings, it lacks error checking, it embeds hidden and unnoted dependencies, it's not extensible, etc. Brevity is a characteristic of much great code, but brevity achieved by doing only half the job doesn't count.

    --
    Slashdot - News for Herds. Stuff that Splatters.
  106. Re:34 Line Web Server by Salamander · · Score: 2

    I'm actually having trouble believing that you're serious. Can anyone's view of programming really be so impossibly narrow that they can't see the obvious deficiencies in that code, and actually try to argue on its behalf? Wow. That is just totally sad.

    There are 6 places where it catches and reports errors via the "or die" construct. Did you miss that?

    No, I damn well didn't miss it; it doesn't matter. Two objections:

    • "Or die" doesn't really count as error checking. Would you like to hit an "or die" every time you mistype a response at a CLI? Every time a network server got a response it didn't understand? Every time an OS failed to recognize a piece of hardware?
    • There are more than six ways this code can fail, so six checks are not sufficient. For example, it's immediately obvious that it doesn't check for or respond appropriately to errors from accept or fork. Maybe sometimes those errors will be caught in the next "or die"; often they won't, and all you'll have is an uncontrolled program termination.

    I repeat my original statement: the code does not totally lack error checking, but it does lack error checking (relative to what should be present in good code).

    it is pretty easy to argue that it is more "extensible" than most web servers because you have to know only two things to extend it:
    • Perl.
    • 34 lines of Perl.

    It is easy to argue that, but wrong - on several levels. You left out IO::Socket, a little bit of UNIX, and a little bit of HTTP, but it doesn't matter. Your argument is a little bit like saying you need to know only one thing to become a doctor, that one thing being medicine. It's absurd.

    Even that doesn't matter, though. When it comes to extensibility, anything that requires that you modify existing code is still a level below anything that can be extended without such modification. This code is only extensible according to a definition so lax as to allow any code to be considered extensible.

    What part of "the job" did it miss?

    All of the parts that distinguish software engineering from mere screwing around. I'm not talking about functionality, I'm talking about the things that make some code that performs a function better than other code that performs the same function. This code may indeed fulfill its requirements (chiefly brevity) and do so admirably, and I do think it's pretty cool. However, as an example of "beautiful code" - the topic of this article - it totally and utterly fails. I wouldn't be surprised if even its author agrees. It's not beautiful, it's not supposed to be beautiful, that's not its purpose, and however cool it may be it has no place in a discussion of beautiful code.

    --
    Slashdot - News for Herds. Stuff that Splatters.
  107. Re:34 Line Web Server by Salamander · · Score: 2
    That's pretty aggressive for someone who failed to respond in a rational way to any of my questions.

    I think most people who read it would say my response was quite rational...even if they disagree with it, or find my tone offensive. That contrasts quite sharply with cid #489, which makes absolutely no attempt whatsoever to support or rebut any relevant claims. I'd love to continue this discussion, but only if you give me something deserving of a response instead of mere meta-argument.

    --
    Slashdot - News for Herds. Stuff that Splatters.
  108. Re:TCL or AOLServer by velouria · · Score: 1

    I downloaded the Tk source a couple of years ago to make a small modification and ended up printing out and reading the whole thing for the pure pleasure of it. It shows that C can be very easy (enjoyable even) to follow. The code's modularity and reuseability is miles better than most of the "Object Oriented" code I've seen too.

  109. The TCL / TK code by tullmann · · Score: 1
    The TK code is quite excellent. It is bare bones vanilla C, but it is written in a clean OO style. Lots of useful comments, very consistent style and usage. Very portable code. Lots of good stuff.

    I haven't looked at the code in four years, though. It may have degraded since, I believe, it has a lot more authors now than it did at that time.

    Of course, all the code I work on (for example, the Janos Java NodeOS) looks great, too.

  110. Gtk+ by ajs · · Score: 2

    Gtk+ is one of the finest examples of software engineering I've ever seen. By extension, I'm including glib. Check out these documents for most of my reasoning:

    The Gtk+ FAQ
    The gobject reference
    Tic Tac Toe in Gtk+

  111. LISP by Rylian · · Score: 1

    LISP is often claimed to be beautiful.

  112. Re:The Story Of Mel by Synoptic · · Score: 1

    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)

  113. OpenBSD by kinger · · Score: 1

    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.

  114. here is one by linuxlover · · Score: 1

    while ( ( *p++ = *q++) ) ;

    this is the guts of STRCPY function. When first saw this, I was amazed how elegant & concise the code is. Yet not too cryptic!

    I always give this to candidates I interview and only about 10% guess it is something close to C strings !! I would say all these Java Strings and garbage collection has spoiled a generation of programmers :-)

    LinuxLover

  115. Re:Beautiful Code Links by linuxlover · · Score: 1

    It made my compiler go 'jerky' :-)

  116. Re:OpenSource is Beautiful by p3d0 · · Score: 1
    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

    --
    Patrick Doyle
    I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
  117. Re:OpenSource is Beautiful by p3d0 · · Score: 1

    Its a terrible misuse of the C preprocessor that buys you nothing in form, fucntion or clarity.

    Well, I guess software practitioners will never agree what makes code "beautiful".

    To me, C's for-loop construct, while powerful, is hard to grok except in the simplest cases. The phrase "for_each_thingy" seems to be much clearer than parsing the code and trying to rediscover its intent.

    I call it loop abstraction because once you write "for_each_thingy" then it doesn't matter whether the thingys are stored in a linked list, or an array, or are accessed by function calls. Your "unless" example has no such benefits.

    Why duplicate the code for accessing thingys all over the place, when you can define it once and reuse it?

    I'd like to hear why exactly you think hard-coding the looping mechanism each time is better, aside from C purity arguments and personal insults.

    --
    Patrick Doyle

    --
    Patrick Doyle
    I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
  118. Want nice code? by alehmann · · Score: 1

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

    1. Re:Want nice code? by frob2600 · · Score: 1
      Ha ha, listing the IOCCC as good code. I hope you meant to list that as bad code -- as that is the purpose of the whole competition. I love this junk. Some of the coolest code in their collection can take weeks to decipher. The IOCCC is the perfect example of how not to code in C.

      I would compete but it is harder to write code that bad, than it is to write good readable code. As for the others, I haven't checked them out; maybe you meant for all of them to represent poor code... beats me, and frankly it doesn't really matter.

      BTW: Here is one of my favorite one liners:
      main(){printf(&unix["\021%six\012\0"],(un ix)["have "]+"fun"-0x60);}

      For all of you that haven't seen it before. Try and guess what it does before you run it. You will forever miss an epiphany. Trust me on this... I had a friend who ruined it for himself and two years later he still regrets it. Give yourself at least a week before you enter it.

      All of you fledgling coders should check this site out. Learn from the masters of misdirection, learn how to earn your job security ;-). You can learn more from one example of how NOT to code, that a thousand examples of how to.

      *Note: David Korn wrote the code above... yes! That David Korn.

      ---
      "Do not meddle in the affairs of sysadmins,

      --

      ---
      "Do not meddle in the affairs of sysadmins,
      for they are subtle and quick to anger."

  119. Re:34 Line Web Server by commbat · · Score: 1

    Everytime I see something like this it makes me want to scream. Perl is interpreted! The interpreter must be loaded into memory before perl scripts can be run!
    That 650 line C program has that 34 line perl script beat.
    Please don't compare compiler source code with interpreter source code.

    --

    --
    'Intellectual Properties' are uncontrollable in the wild. To base an economy on them is just stupid.
  120. Quake and NT by Drubber · · Score: 1

    The finest code I've seen is Quake and the Windows NT kernel.

    Quake is impressive for a few reasons. Though relatively terse in comments, the code speaks for itself. Carmack, Cash and the rest know how to express the essence of a game in the fewest number of lines imaginable. This is what you would expect, of course. Then there are the deeper aspects of seeing arguably the master of high performance game programming at work. By following the flow of execution (literally or figuratively) over the course of weeks, you begin to develop an understanding (albeit pale) of what a decade on the leading edge means.

    One of the few things I enjoyed doing while working at MS was browsing the NT kernel source. The group that Dave Cutler (author of VMS) assembled to write NT was really the quintessential systems team. Now the code is definitely NOT what *nix folks would usually like in terms of style. But the clarity of thought, evident to anyone reasonably well versed in the practice, screamed a quiet elegance. A simplicity of design that I hadn't seen prior, nor have seen since.

  121. Re:Emacs Source Made Me Decide to Remain a Program by Drubber · · Score: 1

    Agreed. It's a shame that corporate interests conflict with the advancement of the state of the art. By that token, you're right about TeX. Indeed, Linux is one of the greatest things to happen in the history of computing, IMO, regardless of beauty or elegance (of which there is plenty within the Linux kernel).

    If you want a glimpse of the NT code, some is provided in the DDK. For example, ntddk.h contains many important microkernel datastructures and entrypoints, macros and inline functions. It's not the inner workings, but you can get an idea of the style and structure.

    Oh well, once Linux democratizes computing, I think MS will come out with a Linux distro to try to kill the rest (like they did with IE), introducing nonstandard extensions that become defacto because of developer adoption. Maybe when they do that, they'll "open source" NT and we can all appreciate it.

  122. Re:Emacs Source Made Me Decide to Remain a Program by Drubber · · Score: 2

    I had a very similar experience. It's nice to see the story behind a passion. I learned to program when I was 13 on the Apple II. A year later I got a C64 and delved deeper. My interest in amateur radio led me towards EE, so by the time I got to college, that was my major.

    I was a disillusioned kid at that point and learning EE only to go work for some part of the military industrial complex (this was the late 80's) made me like the prospect even less.

    Then one day I was talking to some comp-sci grad students about the state of the art and realized that the world of computing hadn't actually passed me by! This was an avenue that was still achievable. So I scraped some money together, bought a 386/SX-16 (without the HD at first, to save money) and taught myself to program. Shortly thereafter, I dropped out of college to pursue a career. Ten years and countless remedial books on algorithms and datastructures later, I can call myself a programmer.

    BTW, some of the most elegant code I've ever seen is the Windows NT kernel. That comment's likely to draw distain from this crowd, but the effort was led by Dave Cutler, the same guy who led the VMS crew. Dispite what people say about MS, this man's creation is a masterpiece (disregarding whatever is layered on top of it).

  123. Clean Code? Beautiful code? by etrnl · · Score: 1

    I think it all depends on what you define as 'beautiful' code.

    Is it aesthetically pleasing code, that's idented properly, uses newlines for readability rather than new commands?

    Or is it a piece of code that you must sit and spend a few hours on a few lines of code to truly grok all that it is?

    A good example of this is procmail. It's an extremely widely used mail delivery agent. Its code however, in my opinion is ugly. It's hard to follow (hell, they even use 'goto' in C...)... but if you spend the time to grok it, you are amazed at exactly how tightly the code was written.

    I consider procmail, for all its performance stretching obfuscated elegance, to be ugly code. I consider something like qPopper (sponsored by Eudora) to be beautiful code. It's highly readable, the variable names make sense, it's modular, it's logical.

    In working on developing a customized mail service, I had to modify both procmail and qpopper. I absolutely hated working on procmail and loved working on qpopper.

    Just my $0.02cp... all that's left after Uncle Sam takes his damn taxes...

    --etrnl

  124. TeX by cyrusp · · Score: 5

    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.

  125. Python by moshez · · Score: 1

    Python's C source is written by Python programmers - they value elegant code.

    I know a lot of people who were struck by the clarity in the Python sources. It's pretty easy
    to understand and modify. Heck, I fixed a bug after using Python for two weeks.

  126. The Story Of Mel by Eight+Star · · Score: 5

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

    --

    lsmvcprm.com, Tools for geek power
    1. Re:The Story Of Mel by Sara+Chan · · Score: 1

      GREAT story!! Thanks much for passing it on. I began programming near the end of that era, and I really appreciate it.

    2. Re:The Story Of Mel by HoldmyCauls · · Score: 1

      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.

      --
      Emacs: for people who just never know when to :q!
  127. Comments PLUS Code = GOOD by UnknownSoldier · · Score: 1

    Comments are a paraphrase of the theory. Code is the implementation details.

    One without the other isn't all that usefull.

  128. Re:The Haskell Prelude by nellardo · · Score: 2
    I'll second that recommendation. Well-written Haskell is a thing of sublime elegance. No, really. It's highly declarative (having no real notion of state - just monads, bits of state you can pass around). And its lazy evaluation enables some wonderfully elegant things, like infinite lists (no, not a function you call to get the next element - it is a list). Short examples often use combinatorial mathematics. Let's take a simple example: factorials:
    fib 0 = 0
    fib 1 = 1
    fib (n+2) = fib n + fib (n+1)
    Yes, that's the function definition of factorial. Looks a lot like the mathematical definition, don't you think? And no, it doesn't need to check for integer roll-over because integers in Haskell do that intrinsically (i.e., 32 or 64 bit til they roll over, then it goes to an arbitrary precision representation).
    Examples> fact 20
    2432902008176640000
    Examples>
    Another classic example is an infinite list of prime numbers using a modulo sieve:
    primes :: Integral a => [a]
    primes = map head (iterate sieve [2..])
    sieve (p:xs) = [ x | x<-xs, x `rem` p /= 0 ]
    The first line is an explicit type declaration saying "primes is a list of things conforming to the class Integral." I leave the rest as an exercise in reading uncommented code :-) except to note that "[2..]" is the infinite list of numbers starting at 2 (you can do finite ones, too, like [2..20]), and [x | x<-xs, some boolean expression of x] is the list of all x such that x is an element of xs and the boolean expr is true.

    Now, just in case you think Haskell is only used for dense mathematical expressions, note that it comes with literate programming functionality built in. And the Haskell Home Page has some examples of some quite meaty real-world examples.

    --
    -----
    Klactovedestene!
  129. Hello World Seven Ways by amnesty · · Score: 4

    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 for the link.

  130. Compilers depriving us of beauty? by tarsi210 · · Score: 1

    From the: Borland-has-nothing-on-Van-Gogh dept.

    It seems to me that the bulk of "beautiful code" which is produced today is that which is still written in an editor at a low level to be compiled on the fly or to do low-level, system-admin type of stuffs. (IE: Perl, shell, etc.)

    Since making it through the scads of OOP methodologies and theories in college, I have seen little to nothing in the way of high-level (C++, Java, Smalltalk, PowerScript) languages that come even close to the pure genius of a nicely written Perl function.

    Is it just me, or have our fancy compilers and IDEs and methodologies removed from us that intricate, complicated, horribly frustrating task of doing low-level, compact work that now we rarely see something of beauty? When was the last time you read some good assembly that just made you smile because it was so damn clever?

    Swiss watches still sell well because they have something that the $5 digital watch from Wal-mart doesn't. Intricacy of the parts, the beauty of the syncronization of movement, the pure elegance in physics.

  131. Y-Combinator...... by ndfa · · Score: 3

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


    --
    Non-Deterministic Finite Automata
  132. Re:perhaps the most visible projects? by captredballs · · Score: 1

    Ditto on apache

    --

    I suppose I'm not too threatening, presently, but wait till I start Nautilus
  133. Screw commenting!! by dimator · · Score: 2

    If the code was hard to write, I'm going to damn well make it hard to read!


    --

    --
    python -c "x='python -c %sx=%s; print x%%(chr(34),repr(x),chr(34))%s'; print x%(chr(34),repr(x),chr(34))"
  134. The most beautiful piece of code... by mduell · · Score: 1

    #include <stdio.h>

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


    Mark Duell

    1. Re:The most beautiful piece of code... by mduell · · Score: 2

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

      Mark Duell

    2. Re:The most beautiful piece of code... by nycsubway · · Score: 1

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

    3. Re:The most beautiful piece of code... by orangesquid · · Score: 2

      if(!printf("Hi there.\n")) {
      if(puts("printf() didn't print anything!")==EOF) {
      perror("puts() didn't print \"printf() didn't print anything!\" because your screen ran out of space(?)...!");
      /* doesn't return anything, so nothing to check... finally! */
      }
      }

      --
      --TheOrangeSquid Is it any wonder things seem so awry? We swim in a sea of confusion and don't have to think to survive
    4. Re:The most beautiful piece of code... by naasking · · Score: 1

      No, it's not beautyful. It is not even legal ISO (or ANSI) C, because main should return a value!

      bzzzt! wrong! Checking out my trusty ANSI C book, the simple program "Hello World!" (or any other program for that matter) does NOT require you to return a value at the end of main to indicate success(though some older compilers require it). If you get to the end of the main block, that is assumed to be grounds for correct correct program termination(so the compiler will helpullfy insert the return statement for you).

      -----
      "People who bite the hand that feeds them usually lick the boot that kicks them"

    5. Re:The most beautiful piece of code... by naasking · · Score: 1

      No, it was a decent ANSI C book as far as I know. "The C programming Language" by Brian W. Kernighan and Dennis M. Ritchie. Perhaps you've heard of it? ;-)

      -----
      "People who bite the hand that feeds them usually lick the boot that kicks them"

    6. Re:The most beautiful piece of code... by thelaw · · Score: 1

      > sent back to Visual Basic where they belong.

      or tcl.

      jon

      --
      -- http://www.cerastes.org
    7. Re:The most beautiful piece of code... by Girf · · Score: 1
      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.

      --

      Apathy -- The state of numbness of the mind. When you are apathic, you can think.

    8. Re:The most beautiful piece of code... by RoninM · · Score: 1
      How about:
      #include <stdio.h>
      int main(void)
      {
      (void)printf("Hello, world!\n");
      }
      ?
      --
      If a corporation is a personhood, is owning stock slavery?
    9. Re:The most beautiful piece of code... by RoninM · · Score: 1
      2. It is stupid to cast the return value from printf().

      That's not true. printf() returns an int. Casting it to void is more correct than silently throwing away the return value.

      3. I think you could afford a line of whitespace...

      Good for you. That's a matter of style. The program is not more or less beautiful or elegant because of it.

      But, point taken on 1. My oversight.

      --
      If a corporation is a personhood, is owning stock slavery?
    10. Re:The most beautiful piece of code... by commanderfoxtrot · · Score: 1

      The most elegant simple language was BBC BASIC, written by Acorn and used for the official BBC computers. Very simple, yet could do some amazing things, especially given it was written at the end of the 1970s. Here we go:

      PRINT"Hello World."

      That's it!

      --
      http://blog.grcm.net/
    11. Re:The most beautiful piece of code... by Deflatamouse! · · Score: 1

      looks like a piece of $h!t to me

    12. Re:The most beautiful piece of code... by joto · · Score: 2
      No, it's not beautyful.
      1. It is not even legal ISO (or ANSI) C, because main should return a value!
      2. It is stupid to cast the return value from printf(). It introduces more visual clutter, and serves no purpose.
      3. I think you could afford a line of whitespace between the preprocessor directive and the main function.
      4. It does nothing useful.
    13. Re:The most beautiful piece of code... by joto · · Score: 2
      bzzzt! wrong! Checking out my trusty ANSI C book

      Maybe you need to check out another C book then. Let my guess, you are using The Annotated ANSI C Standard, annotated by Herbert Schildt? This is probably the worst book ever written on the ANSI C standard. Or are you just using some other half-good book on C? I doubt you are actually using the ANSI standard, because in that case you have proven that you do not know how to read.

      If you get to the end of the main block, that is assumed to be grounds for correct correct program termination(so the compiler will helpullfy insert the return statement for you).

      No, that is not true ISO C. I think it might be true of C++, but then again, that's a completely different language. Also, the fact that some compilers will allow it, is not very interesting either, since compilers are allowed to do what ever they want when it comes to undefined behaviour, which is what this is.

    14. Re:The most beautiful piece of code... by joto · · Score: 2
      That's not true. printf() returns an int. Casting it to void is more correct than silently throwing away the return value.

      No. It is not "more" correct. In fact, both options are legal ISO C, and therefore equally "correct". It is, however, a stylistic issue.

      And when it comes to style, opinions sometimes differ. I agree that there might theoretically exist situations were a void-cast could theoretically improve some readers understanding of a program, but I have yet to see that in practice. Anyone knows that printf() is called mainly for a side-effect. And side-effecting functions should not be a foreign concept to C programmers, as C is not exactly what I would call a pure functional language.

      Anyway, I think any C-programmer on the planet knows that printf() is called mainly for a side-effect. You do not need to tell them that with a void-cast, as little as you need to tell them that with a comment. Do you really think there is even a single programmer on the planet that think it is easier to understand your programs because you put in lots of redundant unnesseceary casts?

      Good for you. That's a matter of style. The program is not more or less beautiful or elegant because of it.

      Beautyful? Yes, Elegant? No

    15. Re:The most beautiful piece of code... by Tassach · · Score: 1
      You shouldn't use tabs in code. (The exception that makes the rule is that Makefiles require tabs.)

      Ah, yet another holy war, right up there with vi vs emacs. Personally, I hate working on code indented with spaces. I'll admit that it's annoying to edit tabbed code on a broken editor; but the way to solve that problem is to fix the editor, not the code.

      --
      Why is it that the proponents of "one nation under God" are so eager to get rid of "liberty and justice for all"?
    16. Re:The most beautiful piece of code... by StarDrifter · · Score: 2
      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.

    17. Re:The most beautiful piece of code... by Abreu · · Score: 1
      Even easier:

      #!/usr/bin/python
      print "Hello World"

      Remember to chant this over and over while you code:

      Beautiful is better than ugly... Explicit is better than implicit... Simple is better than complex...Complex is better than complicated... Flat is better than nested... Sparse is better than dense... Readability counts... Special cases aren't special enough to break the rules... Although practicality beats purity... Errors should never pass silently... Unless explicitly silenced... In the face of ambiguity, refuse the temptation to guess... There should be one-- and preferably only one --obvious way to do it... Although that way may not be obvious at first unless you're Dutch... Now is better than never... Although never is often better than *right* now... If the implementation is hard to explain, it's a bad idea... If the implementation is easy to explain, it may be a good idea...

      ------
      C'mon, flame me!

      --
      No sig for the moment.
    18. Re:The most beautiful piece of code... by lpontiac · · Score: 2

      Try this:

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

      .global main
      .type main,@function
      main:
      pushl $14
      pushl $msg
      pushl $1
      call write
      addl $12, %esp
      movl $0, %eax
      ret

      You see, there's no *need* to save and restore ebp if you're nice to the stack. Additionally, you could use a linux system call (via int 0x80) instead of calling libc's write function, but the use of main kind of ties us into a C infrastructure anyways and that would just break compatability on other x86 Unices.

    19. Re:The most beautiful piece of code... by Bungie · · Score: 1

      Two lines:

      PRINT "Hello World"
      END

      --
      The clash of honour calls, to stand when others fall.
    20. Re:The most beautiful piece of code... by garett_spencley · · Score: 3
      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

    21. Re:The most beautiful piece of code... by agentZ · · Score: 1
      4.It does nothing useful.

      Nonsense! It tells you that the compiler works.

      int main() {
      &nbsp&nbsp return (printf("hello world\n"));
      }

    22. Re:The most beautiful piece of code... by neotek(maas) · · Score: 1

      To hell with compatibility.

      .globl _start
      .type _start,@function

      _start:
      jmp 0xd
      pushl $0x6f6c6c65
      andb %dh,0x6f(%edi)
      jb 0x6c
      orb %fs:(%eax),%al
      movl $0xc, %edx
      movl $_start, %ecx
      addl $2, %ecx
      movl $0x1, %ebx
      movl $0x4, %eax
      int $0x80

      xorl %ebx,%ebx
      movl $0x1, %eax
      int $0x80

      --
      A diplomat is someone who can tell you to go to hell in such a way that you will look forward to the trip. (355/113)
    23. Re:The most beautiful piece of code... by CmdrButtPlug · · Score: 1

      Exactly. Two lines:

      10 print "CmdrButtPlug "
      20 goto 10

  135. Re:The best code has lots of comments ... NOT! by Dix · · Score: 1

    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.

    1) I hope you don't mean 10000 lines in a single execution unit.

    2) Well written code needs few comments. By well written I mean, most importantly, using appropriate object names. They should come from the environment - designs, protocols, manuals etc - without abreviation, retaining spacing (with underscores) and capitalization, so that there is no ambiguity as to what you refer.

    3) Comments should be reserved for non-intuitive or optimized code. This should be rare, and well encapsulated to allow extensive testing.

    4) In general, much commenting signifies bad coding!

  136. And all I can think of... by walnut · · Score: 2

    Would it be great if you were
    writing beautiful code...
    on a beautiful computer,
    while you eat beautiful nacho chips,
    and gaze longlingly out your beautiful window,
    at a beautiful butterfly,
    and a beautiful rabbit,
    playing in your beautiful yard...

    Oh, - and your drunk.

    sorry... props go to SNL and the Jack Handey deep thoughts... but this is the first thing that popped into my mind.

    --
    You say you want a revolution?
  137. Re:34 Line Web Server by Baldrson · · Score: 2
    uh. to a nonperl programmer like me - that looks more like line noise than anything beatiful.

    Oh yeah? Well, The Kalevala looked like line noise to me, too; until I got my first edition copy of Crawford's 1888 translation. Now it looks like very strange poetry -- I think maybe I'll have to learn Finnish and appreciate it nearly as much as the Karelians.

    Fortunately, I don't think Babblefish has a Perl to Finnish mode, which means you won't see a version of Rick's server that looks like very strange code -- it will continue to look like line noise to you until you learn Perl, at which point its poetry will emerge from the noise.

  138. Re:34 Line Web Server by Baldrson · · Score: 2
    its obvious aesthetic shortcomings

    That's in the eye of the beholder. To some of us, Rick's code reads like poetry or elegant math notation.

    it lacks error checking

    There are 6 places where it catches and reports errors via the "or die" construct. Did you miss that? If not, what did Rick miss?

    it embeds hidden and unnoted dependencies

    That's too vague to be considered a valid critique.

    it's not extensible

    While the purpose wasn't to write an "extensible" web server, it is pretty easy to argue that it is more "extensible" than most web servers because you have to know only two things to extend it:

    Perl.

    34 lines of Perl.

    brevity achieved by doing only half the job doesn't count.

    In a parsimoneous form, Rick has specified, in a high level language, the functions of a web server.

    What part of "the job" did it miss?

    Then we'll see how difficult it is to "extend" his server.

  139. Re:34 Line Web Server by Baldrson · · Score: 2
    I'm actually having trouble believing that you're serious. Can anyone's view of programming really be so impossibly narrow that they can't see the obvious deficiencies in that code, and actually try to argue on its behalf? Wow. That is just totally sad.

    No, I damn well didn't miss it; it doesn't matter.

    "Or die" doesn't really count as error checking.

    Your argument...'s absurd.

    Even that doesn't matter, though.

    All of the parts that distinguish software engineering from mere screwing around.

    That's pretty aggressive for someone who failed to respond in a rational way to any of my questions.

  140. Re:34 Line Web Server by Baldrson · · Score: 2

    http://www.email.net/work-well-together.html

  141. 34 Line Web Server by Baldrson · · Score: 3

    Check out the 34 line web server written by Rick Klement, the best Perl programmer I've ever known, who says of it:

    I wrote this after seeing a small HTTP server that took ~650 lines of C. I thought it would be an interesting challenge to try for a ten-to-one reduction. Not only did I exceed that, but the ~650 line server did not do POST type CGI's, which mine will.

    This server (which I name 'ws') has been quite useful. I use it for CGI testing, it's much simpler launching 'ws' with all parameters given on the command line than modifying an Apache conf file and firing the new Apache server up.

    'ws' takes four arguments on the command line,
    ws port_number doc_tree_base cgi_tree_base cgi_location
    but they all have defaults. I usually fire it up with
    ws 80 . .
    and then fetch plain docs from machine/somedoc.html and CGI's from machine/cgi-bin/somecgi.pl

  142. Why Should I Obey the Commands of the Ignorant? by goingware · · Score: 2
    Eh?

    Tell that to the psychiatrists and psychologists who treated me in the psychiatric hospital where I spent the summer of 1985, when I was diagnosed with schizoaffective disorder.

    Or to my insurance company at the time, who sprung for the $10,000 treatment.

    I know it may be fashionable to claim one is manic depressive, but I can assure you it's unmistakeable in me, and it's not something I would choose. There's no Hell so deep as what I experienced in my college days.

    If you don't believe me, maybe you'll at least believe I do some good in my writings. I regularly receive emails in response to my website on Manic Depression from people who've experienced it - either they have it or their loved ones do - and they don't know what to do about it.

    There is a lot of information available about the illness but because of the stigma which is perpetuated by ignorant people such as yourself, not a lot of folks have the confidence in themselves to speak out about their experience publicly as I do, occasionally here on Slashdot and permanently on that website.

    I speak out in part because of my confidence in my position in my career and also my belief that speaking out on what is right is one of the most important things you can do, even when it comes at great personal cost.

    The people who write to me tell me the fact that I speak out personally as I do makes a tremendous difference in their lives. It has happened many, many times that someone has written to me to tell me that I'm the first person they've shared the fact that they think they're mentally ill, or contemplating suicide.

    You should know that that page receives about 3,000 hits a month, and I recieve several emails a day from people looking for advice, about half of them people who have the illness and the others from people who are closely involved with a sufferer and don't know how to deal with them.

    By the way, I'm happily married. I first met my wife three years ago, and we were married in St. John's Newfoundland on July 22, 2000. We just bought our first house together, in Midcoast Maine, and moved into it last weekend.


    Michael D. Crawford
    GoingWare Inc

    --
    -- Could you use my software consulting serv
  143. Emacs Source Made Me Decide to Remain a Programmer by goingware · · Score: 5
    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, 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 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.

    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 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, my resume (on my resume the place where I first encountered Emacs is the Programmer job at Verde Technologies) and my programming tips pages.

    So in a very direct and profound way I owe it all to Richard Stallman 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 cross-platform application framework and a project I've just started up but not gotten too far with yet is the Linux Quality Database.

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


    Michael D. Crawford
    GoingWare Inc

    --
    -- Could you use my software consulting serv
  144. Source Code by Enoch · · Score: 1

    I am not sure if you want to quanitfy this as being beautiful or what-not, but I am sure you can find examples of many different types of code.
    Here is the FreeBSD source tree fully HTML-ized.
    And, in effort to not start a war with the zealots, here is a link to view the Linux kernel source.

    Jeremy

  145. Lua by _egg · · Score: 1

    I picked up Lua after reading this article about it in Dr. Dobb's Journal for use in Grim Fandango. (It has since advanced and yet simplified in tremendous ways... The article is about version 2.5, and it's now at version 4.0.) In addition to being a beautifully simple yet expressive language, Lua also has one of the cleanest codebases I've had the fortune to hack around in. The compiler/interpreter are all easily navigable... Comments are sparse, but well-placed and thoughtful; there need not be more because most of the code clearly explains itself. It's all written in straight ANSI C, and is instantly portable to just about everywhere without even any configuration macros. It's extensible in clean, logical ways... and oh yeah, it's BLAZINGLY FAST.

  146. 99 Bottles of Beer, 227 Languages by MattGWU · · Score: 1

    http://www.ionet.net/~timtroyr/funhouse/beer.html Check out the "Turing Machine" submission, or BrainF***

    --
    "These people look deep within my soul and assign me a number based on the order in which I joined" --Homer re:
  147. Kernel by captaineo · · Score: 1

    I'd definitely recommend looking at the latest kernel. You'll learn neat stuff like:

    o How to do OOP in C (including virtual functions; see any of the *_ops structs)

    o How to write macros that inline well (eg the spinlock macros)

    o How to arrange structs for better cache performance (eg the network-related structs)

    o How to write portable code that configures itself via macros; the final results compile to very efficient platform-specific code without a hint of overhead

    For a higher-level view of software, I'd also encourage you to examine glib and gtk.

    o These expose a large, industrial-strength API; you'll see how a modern large-scale package is organized, and how it deals with complex issues like character sets

    o You'll learn one approach to event-driven programming; glib and gtk make extensive use of callbacks and reference counting since order of execution is impossible to predict in an interactive program

    o Along the way you'll pick up Gtk programming, which is quite a useful skill if you need a GUI sometime

    If you're interested in scripting languages, definitely check out Python; it's very well-organized and cleanly designed. Plus knowing how to embed/integrate scripts with a C/C++ package is very valuable.

    While carefully studying these packages, I'm sure you'll even find a bug or two to fix - giving you an opportunity to contribute as well as learn =)

    Dan

  148. well.... by holzp · · Score: 1

    if you want some shitty code...let me show you what I was just working on....

  149. Re:Some beautiful code... by holzp · · Score: 1

    did you need a seperate class for each piece, or can't you just use the list of moves as the distinguishing feature of a Piece?

  150. Re:Some beautiful code... by holzp · · Score: 1

    I still have to believe that those rules can be configured in a more flexible manner then hard code.

  151. Got to be Jive talkin ! by GreggBert · · Score: 2

    Check out Jive 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.

    --


    If you don't understand anything I post, please accept that I ate paste as a small boy...
  152. Not anymore, Dorothy . . . The Mainframes are Dead by Discoflamingo13 · · Score: 1
    Knuth has often (no cites here, just been muddling through his Lectures On . . . series) pointed to the decline of the mainframe as the beginning of code-muffliness. When you longer had to find the EXACT best solution to the problem, and good-enough was actually good enough, simplicity and elegance were quickly forgotten by the world that moved on, having better things to do.

    It takes a rare soul to write beautiful code off the bat (Like Nick Weininger or Paul Cantrell- if you know `em), let alone beautify the crufty/spaghetti variety. For some people, (a little more artsy) like my roommate, they can't start a project to save his life, but they elegantize more code (and save more sleepless nights/asses/grades) than I think even they know.

    Besides- Knuth cornered the mathematical/beautiful typography market 2 decades ago- and nobody's tried to go up against him since. It serves as a credit to his vision, and his art.

  153. Oh come on!! by naasking · · Score: 1

    You wanna see great code in as many languages as youve ever seen assembled? Sing and follow me! "99 bottles of beer on the wall, 99 bottles..."

    http://www.ionet.net/~timtroyr/funhouse/beer.html

    -----
    "People who bite the hand that feeds them usually lick the boot that kicks them"

  154. Ruby code by Wolfier · · Score: 1

    1000.times do
    puts "Hello? World? What?"
    end

  155. TEX by protek · · Score: 1

    If TEX by Donald Knuth doesn't bring tears to eyes nothing will. ;-) But seriously, there probably isn't a better example of programming at it's finest, particularly if you are interested in Literate Programming

  156. Randal Schwartz's Web Techniques columns by crucini · · Score: 1

    Find them here.

  157. Beautiful Code by pauldy · · Score: 2

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

  158. Re:Emacs Source Made Me Decide to Remain a Program by Broadcatch · · Score: 1

    I spent the years 1975-'80 hacking first Stallman's Teco ^R-macro-based Emacs on Dec-10's and then Bernie Greenberg's MacLisp Emacs on Multics. Moving to UNIX, I started playing with Gosmacs in 1981, and from 1982-'95 I worked on Stallman's GNU Emacs - one of the prettiest pieces of code I've ever seen.

    Some history: I forked the base for what became GNU Emacs from Gosling's CMU thesis (on optimal redisplay algorithms - necessary stuff when talking through 300 baud modems) editor that later he sold to Unipress. (BTW, Gosling got the keymap idea from Craig Finseth's FINE (Fine Is Not Emacs) who got it from Stallman's.) Because Unipress claimed ownership of the code, RMS buckled down and rewrote essentially the entire thing. And what an amazing job he did!

    (This is from memory of my old days of hacking emacs - things may have changed...) He created a 26-bit object space, with a 5-bit object descriptor and 1 bit for mark-and-sweep GC all packed into a 32-bit word. Then there's the DEFUN macro, which simultaneously defines C and elisp-callable functions, as well as setting argument limits, prompt and a documentation string. The doc string can be used interactively, via the (pre-web) hypertext info system, or run through TeX to create a printed manual! Sweet!

    My Mac's been dead for a few months and since I don't have access to the excellent Mac Common Lisp (MCL), I play with elisp these days. And there's some killer elisp packages. Vi is great, but Emacs Rulz!

    --

    --

    The antidote for misuse of freedom of speech is more freedom of speech.
    -- Molly Ivins

  159. Re:The most beautiful code I've seen this week... by Error27 · · Score: 1

    heh heh..

    that's a good one.

  160. The most beautiful code I've seen this week... by Error27 · · Score: 4

    can be found right here.

    It's cool because it's really small.

    In fact I think it's the smallest program possible with an ELF binary. About an eight of the size of the excecutable created if you use some kind of fancy-schamcy assembler. And a 50th the size of the same program created by gcc.

    darn cool if you ask me.

    1. Re:The most beautiful code I've seen this week... by hixie · · Score: 1

      Hmm. I can optimise that further...

      $ echo exit 42 > a.out
      $ chmod +x a.out
      $ ./a.out ; echo $?
      42
      $ wc -c a.out
      8 a.out

      Not quite as educational as the original though! :-)

    2. Re:The most beautiful code I've seen this week... by blair1q · · Score: 1

      It's useless, except as an exercise. But that never stopped anyone.

      Since it bastardizes ELF and therefore isn't portable to other OSes on the same CPU (well, maybe it is if their loaders treat the same fields in the same ways), it isn't ELF. It's an assembly program with comments that align with ELF fields that the Linux loader (well, his Linux loader) treats innocuously.

      But, since deconstruction is as good for learning the ropes as construction is, it's 40367 bytes of useful education.

      --Blair
      "Tomorrow: The biggest ELF program you can't run!"

  161. How about Humorous code by bihoy · · Score: 1

    The funniest piece of code I can recall was in
    a users .profile, it was:

    PS1=`echo $LOGNAME | cut -d= -f2`
    PS1=$PS1"> "

  162. TeX Reward Information by Captain+Chad · · Score: 1

    Donald Knuth's web site is here. Information about the reward for TeX bugs (currently $327.68) can be found here under the section titled "Rewards".

    It says: "If you do succeed in finding a previously undiscovered bug in the programs for either TeX or METAFONT, I shall gladly pay you a reward of $327.68. Corrections to errors in The TeXbook or The METAFONTbook are worth $2.56, as in all my other books."

    --
    Check out Chad's News
  163. Fettuccini classes by bockman · · Score: 1
    I once was the tutor of a young co-worker self-teaching C++. Basically I gave him a small assignment and returned later to inspect his code.
    I was faced with the results of learning C++ without knowing OOD or OOP principles.

    I can't post here his code, but it was bad enough to make me invent a new term on the spot: fettuccini classes, the OOP evolution of spaghetti code.

    --
    Ciao

    ----

    FB

  164. Re:Funny, but that's fettuccinE by bockman · · Score: 1

    Nope. It's fettuccini. Just like fettuccini Alfredo, the most famoush italian dish - you can find it in any italian restaurant in the US.
    The fact that nobody in Italy knows what is it is secondary - real italian food is what you eat in US italian restaurant (so start eating garlic bread everyday, please).

    --
    Ciao

    ----

    FB

  165. Do you work for Microsoft? by chancycat · · Score: 1
    OK, it's probably a bit late for this one, but:

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

    OK, sorry.

    --
    Evan - needs to hit preview before submitting
    1. Re:Do you work for Microsoft? by chancycat · · Score: 2
      Silly me. Dumb joke.

      --
      Evan - needs to hit preview before submitting
  166. Functional Programming by RoninM · · Score: 1
    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. List comprehensions of the sort seen above are also new in Python 2.0. Very nice.
    --
    If a corporation is a personhood, is owning stock slavery?
    1. Re:Functional Programming by RoninM · · Score: 1

      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.

      --
      If a corporation is a personhood, is owning stock slavery?
    2. Re:Functional Programming by RoninM · · Score: 1

      That's not exactly fair, since MUSHcode is just plain ugly regardless of paradigm (I wasn't even aware it was functional, but I trust you know better than I).

      --
      If a corporation is a personhood, is owning stock slavery?
    3. Re:Functional Programming by blamario · · Score: 1
      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

  167. Re:What kind of question is that? by RoninM · · Score: 2

    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.

    --
    If a corporation is a personhood, is owning stock slavery?
  168. Re:What kind of question is that? by ulmanms · · Score: 1

    If you're not interested in code as code, you don't get it.

  169. TCL or AOLServer by DanIncognito · · Score: 1
    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 and Here.
    • 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.
  170. Re:OpenBSD style(9) by dugsong · · Score: 1

    man 9 style

  171. Re:perhaps the most visible projects? by boarderboy · · Score: 1

    I'm not quite sure about that. Konqueror isn't even close to being stable, ditto Mozilla.

    I don't know about Mozilla(probably ugly), but Konqueror is very nicely coded. Konqueror is becoming *very* stable and I think is an excellent browser. The source code is very structured and readable. I tend to believe that using Qt and OO code helps create very readable and easy to understand programs.

  172. Schwartzian Transform by cheese_boy · · Score: 1
    Perlmonks page on it


    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.

    1. Re:Schwartzian Transform by Godwin+O'Hitler · · Score: 1


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

      I don't know, but just looking at it, it's a brilliant example of why perl is either something you love or something you just can't imagine yourself ever learning.

      --
      No, your children are not the special ones. Nor are your pets.
  173. Re:And it's down to 3! OT by mr3038 · · Score: 2
    The appallingly bad API that Microsoft provides with their tools is a very good reason to dislike Microsoft. ...poor level of documentation... disregard for decent coding style... void pointers... so I would have to concur that Microsoft is not the place to look for good code.

    Though I agree that most MS APIs are bad I also understand why they haven't been changed. Why are we still using sprintf instead of snprintf? Compability comes to mind. We are trying to keep source level compability with other UNIXes where MS is trying to keep source level compability with other versions of Windows(TM). In addition to compability problems changes would render current knowledge on MFC etc. completely useless. I'd think that those void pointers are there for historical reasons only.

    If you still disagree think about X and xlib. Why are we still using API that doesn't have any support for alpha blending, vector graphics, decent pixmap filtering etc. features supported by hardware in current graphics chips. We don't have even anti-aliased fonts which I myself take for granted in every other OS I use these days.

    I wouldn't call MS documentation poor. Perhaps they don't give you all the documentation for free, but there good documentation for the areas MS wants the developers to know. Sure there's undocumented features that MS uses in its own software and others follow with reverse engineering. It's MS source and it's up to them what they want to tell about it to developers.

    If you don't like MS APIs or their OS don't support them. Notice that if you don't make programs for their OS you don't need to care about their API quality. What comes to coding style (I assume you mean code formating)... for example I cannot stand GNU coding "standards" - fortunately I have indent.

    The fact that MS does provide some old ugly APIs doesn't automatically suggest that MS couldn't be perfect source for look for good code. Unfortunately MS seems to keep most of it's code secret. Do you really think that company that hires every top quality coder it can get would generate only bad code?
    _________________________

    --
    _________________________
    Spelling and grammar mistakes left as an exercise for the reader.
  174. Re:Slashdot isn't for you by mr_gerbik · · Score: 1

    "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

  175. Re:Beautiful Code Links by mr_gerbik · · Score: 1

    Beautiful Code Links (Score:5, Informative)

    I aim to inform. :)

    -gerbik

  176. Beautiful Code Links by mr_gerbik · · Score: 2

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

    you can thank me later

    -gerbik

    1. Re:Beautiful Code Links by Kernel+Kurtz · · Score: 1

      Yup. Thanks.

    2. Re:Beautiful Code Links by Chai_Bot · · Score: 1

      But does she compile???

  177. This question is a bit too vague by Triscuit · · Score: 5

    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.

  178. perhaps the most visible projects? by small_dick · · Score: 2

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

    --


    Treatment, not tyranny. End the drug war and free our American POWs.
    See my user info for links.
    1. Re:perhaps the most visible projects? by Quintus · · Score: 1
      I'm writing this in Konqueror from KDE2.0 under RH6.2 (somewhat upgraded -- eg libssl).

      I love it. I find it extremely stable, and quite quick. (Much quicker than Mozilla). I've had it crash only once or twice (on some odd JavaScript; eg. that at Britannica.com); and rendering is occaisionally odd, but is almost always beautiful. It seems to do ok on CSS1... Though I haven't tested it in detail. My one compaint about it is that it doesn't really fit into 32mb ram -- when I get the entire thing into ram, it seems (eg. login to twm only and run konqueror from the command line), it is dramatically faster. Usually I wait for my harddrive... It's still faster than Navigator or Mozilla, though...

      As for its code, I'm just beginning to read it, and so can't comment (pun, pun..) However, there is a fairly helpful document on the architecture at developer.kde.org...

      --
      He who fights and runs away,

  179. It's sorta Zen, unfortunately by Gorobei · · Score: 1
    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.

    1. Re:It's sorta Zen, unfortunately by codetalker · · Score: 1

      The Tao of Programming Read this to understand what makes good code.

      --
      All a coder really wants, are fast cars, fast women and fast algorithms.
  180. Colossal Cave by PotatoMan · · Score: 1
    The original version of Colossal Cave is the most beautiful work I've ever seen. You can download it here. Be sure to get the original; the site hosts many versions.

    My reasons for recommending this code are:

    1. Written in FORTRAN IV, which offers no help to the programmer
    2. No complex data structures, yet he makes them clear and readable
    3. Branches limited to arithmetic if statements
    4. Closest I've ever come to the brandy-and-cigar ideal

    This is clearly the work of a professional programmer, yet it was a game he was working on in his spare time. I use this as a standard in my own work.

  181. IJG, ZLIB, BZIP2 by istartedi · · Score: 3

    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.

    --
    For all intensive purposes, "whom" is no longer a word. That begs the question, "who cares"?
  182. Re:The Story Of Mel (or: Ugly Code) by Mark+Imbriaco · · Score: 1

    What you're failing to consider is that Mel was coding for a far different era of computers. Not only did he do things the way he did because it was *cool*, he did it because computers weren't really all that fast and you had to play dirty tricks in order to squeeze every bit (pun intended) of performance out of them that you could. -Mark

  183. The Haskell Prelude by joto · · Score: 2

    I would suggest you download Hugs, start dabbling in Haskell, and read the Haskell Prelude. It is relatively easy reading and contains code that is very beautyful.

  184. Smalltalk by tony+clifton · · Score: 1
    In Cincom VisualWorks or Squeak Smalltalk, there's probably the most mature base of object-oriented code in existence. And good browsing tools.

    Totally beautiful -- in my case it took someone who understoon object-oriented principles and had done a bit of C++ in small 6-week to 3-month college projects into the culture of real O-O development.

    Caveats -- after doing Smalltalk, C++ will get really painful and you'll keep snickering every time you read Java code.

  185. Another bit of beautiful code -- for the lispers by tony+clifton · · Score: 1
    Peter Norvig's book Paradigms of Artificial Intelligence Programming is really quite good. It gives code and commentary on some really amazing programming.

    As well as it might pay, most of the work done in Java and on the internet these days is a lot closer to COBOL programming (batch and transactional) than anything close to the complexity and ingenuity of an Eliza or GPS.

  186. Funny, but that's fettuccinE by kazzuya · · Score: 1

    ..to set records straight 8)

  187. Garlic bread by kazzuya · · Score: 1

    How could Italians live up to their hype of passionate lovers if they really ate so much garlic bread ? 8)

    Forget that crap.. start cooking yourself !

  188. The best code has comments only when needed by a!b!c! · · Score: 1

    Its interesting that you mention how to format comments but not what you put in them. Excessive and useless commenting is almost as bad as having no comments at all. Its frustrating to have the code so chopped up with crap, that I can't even fit 15 lines of code on the screen. Good variable names can greatly reduce the need for comments.

    Its interesting too that everybody is looking for "beautiful" code. Are we talking about algorithms, design or style? But whatever the focus, I greatly prefer simple code that can be easily read with minimal comments. You mention the nightmare of working with 10,000 lines of code, and the importance of comments there. I agree, but I think the design is much much more important there. I shouldn't have to know all 10,000 lines of code in order to make some patches. I should be able to determing which sections are relevant, get an overview of those sections, and be able to easily make changes in one place that don't mess up everything elsewhere.

    Despite all the hype around Extreme Programming(XP), it promotes some great ideas that lead to more simple(ok, even beautiful code.) It suggests trying to keep all methods so they fit onto 1 screen, avoid any duplication of code in classes, have everybody on your team work with a consistent style! and try to limit class sizes to under 1000 lines. But most importantly of all, one must refactor to make things simpler whenever possible. Constant refactoring!

    Before I get flamed, I should include the disclaimer that simpler is not always better. There are times when you did need to use a clever chunk in order to improve performance, then it might be worthwhile to explain in greater detail as to whats going on. But for the most part, keep it simple.

  189. Squeak! by bzhou · · Score: 1

    Surprised nobody mentioned smalltalk code.

    See Squeak 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"
    1. Re:Squeak! by Bobjects · · Score: 1

      Try telling that to the Squeak community.

      Nice try though.

    2. Re:Squeak! by Ghostface+Postah · · Score: 1

      Eiffel?! At least Smalltalk was alive once. Eiffel has such negative juice, there's probably been more written about Eiffel than in Eiffel.

  190. One Word - Quake by desideria · · Score: 2

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

  191. Re:Not anymore, Dorothy . . . The Mainframes are D by hardburn · · Score: 1

    But then, I doubt there ever was a Y2K problem, except in situations such as banks where an account holder would be given -100 years worth of intrest. Why should most computers care that its now 1900 or 19100? Not even Windows is so flakey that it would crash because of that.


    ------

    --
    Not a typewriter
  192. Wei Dai's Crypto++ 4.1 by aminorex · · Score: 1

    This is best code I have ever read, hands down.

    --
    -I like my women like I like my tea: green-
  193. Indenting with /.HTML by mrBlond · · Score: 1

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

    if only Support(/.HTML)
    CheerUp;
    //to indent
    use &nbsp;
    infrontOfText
    stopUsing
    ifOff

    PS: Allowed HTML should use lowercase examples, and allow XHTML <br /> - I keep having to remove them :-(®


    --
    mrBlond
    --
    CowboyNeal for president!
    "Hit any user to continue."
  194. PGPSDK by elegant7x · · Score: 2

    If you want an example of a sweet-ass API you should check out the PGPSDK, that's just amazing. They some how managed to make a polymophic object orientated system in pure C (or course, it probably can't be extended as easily as it could be if it were C++ or java, but still).

    Really, really easy to work with.

    Amber Yuan 2k A.D

    --

    "and dear god does this website suck now." -- CmdrTaco
    1. Re:PGPSDK by IngramJames · · Score: 1


      It's also a great example of how NOT to provide documentation. All the functions are listed, all the options are shown, but...

      1)In places the documentation is simply innacurate (p169 "keyCount indicates the number of keys required to decrypt the message that are not currently available, and these are identified by keyID in the referrenced keyIDArray" should read "keyCount shows how many keys the message was originally encrypted to, regardless of how many of these are in the currently open keyring. Period.")

      2) There is a tiny amount of sample code which shows the most basic functions. Everything else is left to your imagination and trial and error...

      You want to see good code..? Check out:
      http://www.oz.net/~srheller/dpgp/index.html which shows you how to use the API... It's in Delphi, laid out nicely, with nice comments.

      </flame PGP SDK>

      James
      ---------------------------

      --
      'No rational religion claims "supernatural" exists, that's an atheist slander.' - seen on slashdot.
  195. Re:Functional Programming - SUCKS! by kalifa · · Score: 2

    What's your point, exactly? Human may not be designed to think in reverse polish and to do recursion, indeed. However, humans were also designed for hunting and polygamy. They were also obviously not designed for using computer, otherwise they should have a hand with 105 fingers and another one with 3 or so.

    That thing we humans arogantly call "progress" has always been achieved by forgetting the straightforward applications of our "design" and by using our abstraction capabilities to accomplish unobvious activities. Functional programming is no exception. And it gave us Emacs.

  196. Re:Functional Programming - SUCKS! by kalifa · · Score: 2

    So? I'm afraid I don't get it.

  197. Try this.. by Arjuna+Theban · · Score: 1


    Check out savastio.c or any other ioccc winner.

    If you can read those, well.. you're either too good or have too much time in your hands. Either way, it's good.

  198. The Duff device by f5426 · · Score: 2

    This is the original Duff device (in pre-ANSI C). A gem, that the ANSI comitee carefully looked at and declared valid.

    Take a look at how the loop unrolling is performed. See how the loop is misplaced between the first and second case label. This is beautifull, because it have been a creative act to even think that the compiler could grok it.

    send(to, from, count)
    register short *to, *from;
    register count;
    {
    register n=(count+7)/8;
    switch(count%8){
    case 0: do{ *to = *from++;
    case 7: *to = *from++;
    case 6: *to = *from++;
    case 5: *to = *from++;
    case 4: *to = *from++;
    case 3: *to = *from++;
    case 2: *to = *from++;
    case 1: *to = *from++;
    } while(--n>0);
    }
    }

    See author comments at:

    http://www.lysator.liu.se/c/duffs-device.html

    (But clearly, I would not want that in production code)

    Btw, what I call beautifull code is crystal clear code. The first ncsa httpd was of that kind (imho). Anyway, beautifull code matters much less than beautifull _interfaces_.

    Cheers,

    --fred

    --

    1 reply beneath your current threshold.

  199. Beauty.. by gnireenigne · · Score: 1

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

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

  200. Re:Not anymore, Dorothy . . . The Mainframes are D by cyber-vandal · · Score: 2

    Bzzzt....wrong. I've worked on more examples of god-awful COBOL code than I care to count. Crap code comes from laziness, incompetence and lack of thought about the future - the Y2K bug is an excellent example (although other platforms had their share). Good code comes from talent and I've seen plenty of well-written, and easy to mod code as well.

  201. Re:id software: doom, quake by shog9 · · Score: 1

    I agree that much of the Doom source code is quite nice. For me, its beauty comes from its simplicity; the logic is split well, and free of unnecessary optimizations.
    Reading through it helped me greatly back when i was first learning C.

  202. There is lots of different aisles... by Glowing+Fish · · Score: 2

    This is a big problem for me, too. The major problem is that they tend to put the various kinds in with the food they are meant to flavor, instead of grouping them all together in a single aisles. So it is really a matter of personal preference.

    But I would suggest going over to the Mexican food aisle, because I find Tobasco to be very beautifully tasting...
    Espera un minuto...
    OH...Source, you are looking for source then! Well, never mind.

    --
    Hopefully I didn't put any [] around my words.
  203. Avoid GNU indent package by Trebinor · · Score: 1

    This code sucks like you wouldn't believe.

  204. Re:C++ exceptions replacements (nothing like it) by jdennett · · Score: 1

    C++ exceptions allow for exceptional control paths and clean non-local error handling. Anonymous Coward still doesn't have his/her facts straight.

  205. Here is an essay on this topic.... by cconnell · · Score: 2

    Here is my essay on this topic (which slashdot declined to publish a couple months ago).

    Chuck

  206. Tcl/Tk by ronys · · Score: 1
    The Tcl/Tk code is a great example of code that's designed to be looked at, since extensibility is a basic design goal of the project. The latest code snapshot is currently here

    There's also a very well-written style guide that explains the logic behind the style.

    --
    Ubi dubium ibi libertas: Where there is doubt, there is freedom.
  207. 99 Bottles of Beer on the Wall by Dave114 · · Score: 1

    Your favourite song retold in a total of 227 different languages:

    99 Bottles of Beer

  208. A Site Devoted Good Code by trikyguy · · Score: 1

    www.perlmonks.com
    I heard of this from everything2.com.

    - email account is @hotmail.com
    Discussion Never Hurt Anyone.

    --

    Discussion Never Hurt Anyone.
    Libertarians
  209. Beauty, Solutions by FooBarson · · Score: 1

    (Quoting from the c2/wiki BeautyAintMyBusinessNoSir (which is a response to BeautyIsOurBusiness)):

    "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -- Buckminster Fuller

    - Dr. Foo Barson

  210. Some beautiful code... by TomRitchford · · Score: 1
    Awright, this is code I wrote but I'm rather proud of it.

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

    1. Re:Some beautiful code... by TomRitchford · · Score: 1
      The separate pieces are needed because almost all the pieces have special rules, pawn first moves, ep, castling, king into check, rooks can't castle after being moved, that sort of thing.

      Only the bishop and queen have no special moves.

      I brought the code out and you can see it here.

    2. Re:Some beautiful code... by TomRitchford · · Score: 1

      The Java code can be found here.
      There's a lot of stuff there, feel free to wander around.

    3. Re:Some beautiful code... by pimphandofgod · · Score: 1

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

  211. Perl Obfuscation by SlipJig · · Score: 1

    For an example of how NOT to code, why not check out some Perl Obfuscation? 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).

    --
    Read my keyboard review.
  212. The good, the bad and the ugly by scosta · · Score: 1

    You are saying that you are interested to both the ends of the ladder, the Good and the Bad. It is very easy to find the Bad, so it's not worth the effort, since it is much easier to be lazy than overzeolus. What you don't expect though is *where* you can find the Bad. Bad code lies everywhere, even toghether with the Good. Even made by the same person....I whish to be deliberatly provocative: Linux. Try to see the code of floppy disk driver inside the kernel, floppy.c. From my point of view, it's an ugly mess of good hacks and sloppy coding. Try to see the source of much-abused ls command. Beware, it's so convoluted that I think non one touches it anymore. Of course, the Good and the Bad can be swapped, i.e. some people will say exactly the opposite, but code is like people: sometimes is bad, sometimes is good, depending on the way you woke up. Even for wizards like Linus.

  213. Re:Wrong approach by Gumshoe · · Score: 1

    While I agree that the intention of the Obfuscated C Code is to produce bad
    code, I can't help feeling that the best entries are very beautiful. If the
    entries were not intended to be "bad" then the beauty would have been lost
    but deliberately obfuscating a program (to the point where the viewer
    wonders if it is C at all) justifies the "poor" programming choices and
    qualifies it as art.

    I personally love to see skilled programmers stretch the compiler and the
    language to the limits and it is this, I think, that makes the Obfuscated C
    Contest so aesthetically pleasing.

  214. Hello Polyglots by ideology · · Score: 2
    The home page for polyglot is: http://ideology.com.au/polyglot/

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

    --
    ideology.com.au
  215. Re:CircleMud by eudas · · Score: 1

    i never coded on circlemud codebases (i always played, heh go fig) but every admin i've ever seen who has always said it was the worst kind of spaghetti. i'm not sure if it was that way 'out of the box', or after they had mucked it up... ;)

    eudas

    --
    Blessed is he who expects the worst, for he shall not be disappointed.
  216. Beauty - a matter of perspective by codepawn · · Score: 1

    When I was 16 I was writing a text game for C64 in basic and thought there must be a better way to store data that predeclared arrays.

    In first year Uni I learned about pointers and the more basic algorithms using pointers to represent lists, queues, recursion etc etc. I was in heaven.

  217. Read Gabriel's Book by sv0f · · Score: 1

    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.

  218. Is anyone taking this seriously? by sv0f · · Score: 4

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

  219. try HERE... by Sheik+Yerboutii · · Score: 1

    It's funny that you would ask that question right at the same time that i found this link. It's an article (with a reasonably good bibliography) about software engineering and writing good code.

    check out his links at the end of the article as well

  220. Sun's Java Classes by invi · · Score: 1

    You should take a look at Sun's Java Classes available on their Java website. These classes are designed pretty well, and the standard of the code is very high. Even though this code is pretty high-level, it shows some interesting programming aspects (hashed lists, interfaces, object oriented design, just to name a few).

  221. beautiful code is only a legend by mark_lybarger · · Score: 1

    i've skimmed a book about beautiful code, beautiful designs and such. the best kind of code is code that is "inhabitable" where one, or ones, can go into the code and feel comfortable learning the guts, and making modifications quickly and easily. this type of code is not beautiful. i've seen inhabitable code, and it's great for the maintenance team. beautiful code is more like a legend that doesn't exist. if it were truly beautiful, noone would dare touch a thing and it would outlive any usefull life. you don't see people going around touching up the mona lisa just because it needs some modifications. art (beauty) is somthing you build or create once and then walk away. code should not be art.

  222. UNIX 6th Edition by zerovoid · · Score: 2

    Take a look at "Lions' Commentary on UNIX 6th Edition" by John Lions. It's an older text, but it's beautifully coded. Although this is a great text for OS programming, if not the standard, it can also server as a good reference for style and design. It's written by the guy that invented C, so you know it's going to be good. :)

    zerovoid

  223. Sorry... by arnald · · Score: 1

    ...but the Linux kernel, useful and reliable though it may be, is NOT a good example of beautiful code.

    It's largely a hack, and a fairly poorly laid out hack at that.

    For a beautiful open source unix-a-like, look at the NetBSD kernel. In fact, all of NetBSD is nice.

    --
    arnald
  224. My thoughts by arnald · · Score: 1

    Agree with BSD, agree with TeX, disagree with Linux kernel.

    Something I've learnt a lot from myself is Scintilla. It's a free editing control (with my favourite editor, SciTE, thrown in too) written in (a subset of) C++, but in a very nice way... It's hard to put your finger on why it's so readable, but it just makes sense. I think it's at the perfect size to study - not too big to be incomprehensible, but not too small to be unrealistic.

    Have a look.

    --
    arnald
  225. Re:Emacs Source Made Me Decide to Remain a Program by JWhitlock · · Score: 1
    I'm glad I got my EE, even though all I do these days is CS, and, if I do get that masters, it will probably be in CS.

    Your Windows NT comment is interesting - it seems you aren't just trolling, that you are serious. The only problem with offering the Windows NT kernel as an example of good code is that... you can't see it. You need to sign a non-disclosure to look at it, which makes it unusuable for demonstation purposes.

    Perhaps one day, when Microsoft opens the Microsoft Source Code museum, it will be possible to evaluate the code, and compare it to other code. It may be a enlightening excercise to see what was good enough to support most of the business world for about a decade. Until then, the original poster is better off looking at open source code, like TeX.

  226. pine by egmont · · Score: 1

    check out the source of "pine" or "wu-ftpd"! you'll realize that everybody in the world writes beautiful code except people at the washington university.

  227. Beautiful Code? by hjayres · · Score: 1

    My Code looks awful It is never aligned and tabed niceley and all that jive. It often hass masses of comented out garbage. It does, however, get the job done, is written in the time allowed and makes me happy. I would dearly love to write some nice perl poetry. Maybe when I retire.

  228. Who is Mel? by TheVet · · Score: 3

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

  229. This is how to do it: by Godwin+O'Hitler · · Score: 1

    -- notice the lack of #weird incantations at the start

    class GREETINGS is

    &nbspmain is

    #OUT+"Hello, World.\n"

    &nbspend -- of main

    end -- of class GREETINGS

    --
    No, your children are not the special ones. Nor are your pets.
  230. Elegant Code != Good Code by naden · · Score: 1

    One of the most wonderful example of elegant but poor code is the recursive method for generating Fibonacci numbers. O(n!). The iterative method whilst looking so much slower runs so much faster. O(n). Remember kids good code is ANSI C code :) Naden.

    --
    Funtage Factor: Purple
  231. Re:OpenSource is Beautiful by atrowe · · Score: 1

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

    --

    -atrowe: Card-carrying Mensa member. I have no toleranse for stupidity.

  232. Quake Source Code by nnnneedles · · Score: 1

    If you read the Quake source, you will feel like God has stepped down from heaven to write software.

    --
    Will code a sig generator for food
  233. You really should widen your reading scope by Reedi · · Score: 1
    If you want to read something beautiful then get yourself a library card.
    I won't patronise you or the other /. readers by giving you a recommended list. I'll leave that to someone who will no doubt post as Anonymous Coward.

    Ian

  234. ...in a language some don't even know is OO... by borgboy · · Score: 1

    the JCL 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.

    --
    meh.
  235. Commented code by infiniti99 · · Score: 1

    My code is heavily commented... out.

  236. Wrong approach by blamario · · Score: 3

    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. You can learn from negative examples as well, and they are much easier to find.

    1. Re:Wrong approach by Crspe · · Score: 1

      Actually I found quite a bit of the obfuscated code to be very beautiful. The example that I liked the most was the entry by phillipps in 1988, available here. I just found it amazing to see what these programmers managed to achieve from what looks like a random set of symbols sprinkled into a text file. I guess that with normal programming, unless your idea of "beautiful" matches the ideas of the programmer who wrote it, then you dont find it beautiful. Whereas, with the obfuscated code competition, everyone has the same idea of "beauty" - obfuscation!

      --
      #include /* 20000608 PUBLIC DOMAIN MySig(sig.c) Tweaks welcome */
      main(c,v)char *v;{return !c?putchar(*v-1)&&main(0,v+1/* build: cc sig.c */
      ):main(0,"Disjt!Tqfjst!=dstqfAzbipp/dpn?\v\1");}/* No C compiler? No OS */

  237. I don't know about the 3.1 source but... by sheetsda · · Score: 1
    I have managed to track down the source code for Windows 95 (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

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

  238. Really, really old "c" by xFoz · · Score: 1

    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

  239. Haven't you heard of CodeGuru? by ishrat · · Score: 1

    Here's where you'll find codes of all kinds.

    --

    There's always sufficient, but not always at the right place nor for the right folks.

  240. Song Code by tattered_tux · · Score: 1

    #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

    --
    Patrick C. Lamoreux lamoreux@iastate.edu
  241. Beautiful code for dummies by wackysootroom · · Score: 1

    10 print "Beautiful code" 20 goto 10

  242. CircleMud by slugo · · Score: 3

    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?

  243. Doesn't anyone remember the 'scene' by codetalker · · Score: 1

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

    --
    All a coder really wants, are fast cars, fast women and fast algorithms.
  244. GETTING OFF ON GOOD CODE by wigger · · Score: 1

    i masterbate every night to a hardcopy of vi's source.

  245. And it's down to 3! by g_bit · · Score: 1

    (Comments that have to be made before somebody comes out with a totally unrelated anti-microsoft comment)

    Do you people *really* have nothing better to do? Does Microsoft really hurt you that much? Do you really think that the world is meant to be perfect and the software industry owes you something? What? Oh, you're thirteen! Of course...

  246. id software: doom, quake by eulevik · · Score: 5

    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.

  247. Re:What kind of question is that? by Faulty+Dreamer · · Score: 1
    If you can't read it, or don't want to read it, I don't understand why you'd want to write it. I know some people think of programming as something to do to put food on the table, and their intended audience for the code is the machine itself and the QA department. If you are writing for any reason less than that, I don't see why you bother at all.

    I was with you until you said that. Are you saying that writing code just because you enjoy it is a lesser reason than to put food on the table (or make money for your business)?

    I'm not much of a coder myself. I do a little here and there, but nothing I would call beautiful. But I still enjoy reading elegant or "pretty" code when I get the chance. My favorite passtimes however would be music (playing, writing and listening) and stories (also reading and writing). So, taking your statement to the next level are you going to say that anyone that plays music, but doesn't do it because they are trying to make a commercial go at it are doing it for a lesser reason than the people like N-Sync and the Backstreet Boys? Or are you saying that the guy that writes stories just because he loves to write is doing so for a lesser reason than the guy that is hoping to get rich off of writing the ultimate book?

    Somehow that seems backwards (if that is what you are saying). It seems the lesser reasons to me would be doing it for money/fame/fortune. Doing something just because you love and enjoy doing it seems a much higher reason. I'm not sure if you were implying what it looked like, but if you were, I disagree whole-heartedly.

    --

    ------------

  248. Re:What kind of question is that? by Faulty+Dreamer · · Score: 1

    Oh, OK;-).

    Sorry about the rant then.

    --

    ------------

  249. Re:Functional Programming - SUCKS! by IanA · · Score: 1

    Your comment seems clever, until you consider humans created keyboards,mice,computers as a whole.

  250. Goodbye? by kilgore_47 · · Score: 1

    #!/usr/bin/perl printf("Goodbye World."); return 0;

    --
    ___
    The way to see by faith is to shut the eye of reason. --Ben Franklin
  251. Re:What kind of question is that? by kilgore_47 · · Score: 3

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

    --
    ___
    The way to see by faith is to shut the eye of reason. --Ben Franklin
  252. What if famous literary figures wrote code? by shift8key · · Score: 1

    Let us take a short program and translate it into how Anthony Trollope, P. G. Wodehouse, Evelyn Waugh, Ernest Hemingway, William Faulkner, J. D. Salinger and downright bad writers like Danielle Steel and Jackie Collins would write them -- I would love to see the comments on a Trollope program.

  253. Study at the foot of the master... by 3333t00l · · Score: 1

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

  254. Re:OpenSource is Beautiful by Aunt+Mable · · Score: 1
    You write shit like that for a living and you starve.

    BZZZT! WRONG!

    You write shit like that for a living while wearing a nice suit and talk about e-ventures and you get a big car and a silicon wife.

    Trust me, I know!

    -- Eat your greens or I'll hit you!

    --

    -- Eat your greens or I'll hit you!

  255. the 5k contest entries by Glog · · Score: 1

    www.the5k.org has a great contest for writing a web page/site under 5k (html, javascripts, images included, no server scripting). As much as I dislike javascript there are some pretty impressive entres in the contest. It won't be pretty - as in the code will not be commented, and white space is stripped out - but those brave enough to go figure out the obfuscation will certainly find some of it quite "beautiful".

  256. Re:Emacs Source Made Me Decide to Remain a Program by The+NT+Christ · · Score: 1

    Hey, can I put a commercial for myself on Slashdot? Please! I could talk about what got me into programming, then when they've taken the bait I can switch and start selling myself as a consultant. ;)

    --

    I didn't pay for my operating system either

  257. Re:C++ self-documenting? by The+NT+Christ · · Score: 1
    I can't speak for other C++ coders - there are a lot out there, with varying degrees of aptitude. I advice writing any code clearly, but there's plenty of coders (in all languages) who don't!

    I agree that comments are very important in external headers, and I usually try to give an overview of the class and its purpose. If you don't have the class source code, this is of course vital.

    Code should definitely have *some* comments. I just mean that the ideal amount of English compared with code can be much lower, depending on which language you're using. In essence, the purpose of higher-level languages is to express the code in a way that's closer to English - so less English comments should be necessary.

    What I don't want to see is a comment which would be redundant, if only it matched the code. Or crap like this:

    a += 1; // increment a

    I think my opinions are close to those of Stroustrup. He has spent more time explaining them than I can. I agree with more of what he says than I disagree with. And he did invent C++!

    --

    I didn't pay for my operating system either

  258. ascii pr0n by Kiss+the+Ass · · Score: 1
    hey, there was an ascii video clip on the old DECUS tapes. It was a text file called JACK.OFF and if you just PIP'ed it to an ANSI terminal at 2400 baud this little figure would shake it pretty good and eventually "pip" on your screen.

    anybody know where to find this? I have not been able to construct a search that doesn't find a lot of stuff I'm not looking for.
    ----

    --
    trolls swarm slashdot. when will plastic get FPs and goatse?
  259. Hungarian Notation by Kiss+the+Ass · · Score: 1
    If you really want to study and learn, you should definately soak in Charles Simonyi's "Hungarian Notation" for a few days, a part of his PhD thesis. To get you in the right frame of mind
    Dr. Simonyi's idea was to think of good programming to be a test where two programmers are given the same task and then separated from each other. They "pass" if they produce identical code, and they "fail" if they don't. This is a good test because if different programmers can follow rules to produce the same code, their code will be easy to borrow, read, maintain, etc.
    Cool, right? Note it's the exact opposite of perl's TMTOWTDI, or "there's more than one way to do it."

    You can read a version at Microsoft but if you, like me, don't even like going there then there are other copies on the web. There's one at apostate that has some additional addenda that might be interesting (I didn't look too closely) and one here that has some rather mindless criticism sprinkled in. Here's a plain text version.

    A variant of this naming convention that most people have heard of was also adopted by Microsoft for use with Windows. The version Windows uses is a steaming pile of shit and is a complete perversion of the original idea, so don't base your opinion of Hungarian on Windows or on criticisms from people who only know that version. If you have the good sense to despise Windows's Hungarian because it is the opposite of abstract, you'll love the real thing. It can be hard to get used to Hungarian, but I don't know anybody who has gotten used to it who was able to stop using it.

    BTW, he also worked at Xerox PARC where he more or less "invented" WYSIWYG word processing, before he succumbed to the evil empire and became charless@microsoft.com, father of Microsoft Word.
    ----

    --
    trolls swarm slashdot. when will plastic get FPs and goatse?
    1. Re:Hungarian Notation by Kiss+the+Ass · · Score: 1
      did you read the papers about the motivation behind Hungarian?

      Hungarian Notation is good for rendering source code into obsfucating noise.

      false. Hungarian names have more semantics than non Hungarian. They are pronounceable, and they have internal structure and high-level abstract type information. They solve several problems that non-Hungarian names have, and all the problems you mention. You'd need to reference the actual arguments to make a meaningful case against the notation. The C language itself is just as obscure to someone who doesn't know it, but it has a syntax that is learnable and readable to someone who konws it. Hungarian Notation is a language just the same.
      ----

      --
      trolls swarm slashdot. when will plastic get FPs and goatse?
  260. I like his question much better by Kiss+the+Ass · · Score: 1
    Lame. He's simply asking where to look at examples of different kinds of good.

    "Good art" can be found in museums. That doesn't mean it's all the same or obeys one definition, but it's still generally agreed to be good and is at least as instructive to look at as a discussion of the definition of good art.
    ----

    --
    trolls swarm slashdot. when will plastic get FPs and goatse?
  261. Fetchmail by anarcat · · Score: 1

    I had to hack fetchmail recently to keep mail from bouncing when fetched from our isp to our internal postfix server (see the dropdelivered option).

    I found hacking the source extremely easy, the source being modular and well documented.

    This program could serve as documentation on how mail protocols (SMTP, POP, IMAP, etc) work and how to implement them.

    Yay for fetchmail!
    --

    --
    Semantics is the gravity of abstraction
  262. It's in the book by MSBob · · Score: 1

    The book is "Design Patterns" by the Gang of Four

    --
    Your pizza just the way you ought to have it.
  263. a work of brilliance... by Kewjoe · · Score: 1

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

  264. Re:FP! by CmdrButtPlug · · Score: 1

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

  265. ?? by kLoNe343 · · Score: 1

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

  266. Beauty: Ingenuity or appearance? by carbon+68k · · Score: 1
    Some might say that code beauty has much to do with the way it is read, or the way it looks, like this line of AppleScript which I thought up in about 3 seconds:

    get the last word of "The day is at its end."

    I don't find this beautiful... elegant, maybe. At this particular moment (which is tainted with fatigue and may not represent my usual thought process) I think that code beauty is about getting something done in an efficient way, taking every advantage available in the language and execution environment. Obfuscated code can be beautiful if it does what it does better than a more easily read version of said code can do.

    Okay, enough of this for tonight... Eight hours of fluorescent light + 6 hours of staring at a CRT = a tired brain..

  267. My favorite code snippet... by MegaManSE · · Score: 1

    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 ?

  268. pretty code! by greenforest · · Score: 1

    any body think of this yet?

    http://www.perlmonks.net/index.pl?node=Perl%20Po et ry&lastnode_id=481

    #!/usr/bin/perl

    join $me,

    my $gorgeous,

    and listen $carefully, $please;

    eval { the circumstances } and

    warn $me if not $comfortable;

    for ($i; "understand";

    "but please, let us" ) {

    lock our $lips,

    and link $us, $together;

    grep $me, $now, if $ready, and "i shall be happy";

    unlink our $reservations

    and do { $me, $passionately, }

    until $at, last, our $desires_are_satisfied };

    sleep $happily, my $dear_one;

    for (our $experiences_have_been_wonderful,

    and our $time_together_will ;;)

    { last }

    It could use some optimization to be sure, but it sure is pretty.

  269. Using Apache Code for Education by kefirsound · · Score: 1

    Hello!
    We plan a course for our students concerning the Apache Source Code. The goal will be to create a good code documentation for developers and to extract concepts and solutions for common design problems.
    I believe that the analysis of existing (and running) software is an important task for someone working in the software industry, because in most cases you join a project where you have to alter or extend existing code and you have an enormous advantage if you quickly understand how it works.
    I am planning a project to make available all the good ideas and solutions hidden in the source code of so many good open source projects. The analysis course is just the first step towards an encyclopedia of software engineering knowledge.

  270. A suggestion by Tramb · · Score: 1

    I would suggest that if you're interested in compilers, parsing and so on, you check the source of the GNAT Ada95 compiler, which is in the opinion of most of those who looked at it: elegant efficient and really readable Of course, it is in Ada...

    --
    ...et le pire de tout c'est qu'en plus on est contents!
  271. IP Filter by bbeausej · · Score: 1

    Beautiful code is not only defined by the quality and efficiency of it's statements. It's also defined by the quality of the design of the whole, and in the maintainability of the app/code. That's one of the reason why I really like digging into Darren Reed's code of IP Filter, I think it is ressourceful to see good code like this, that implement standards correctly and cleanly, and that use the features of the language without abusing them.

    --
    Benoit Beausejour SmartWorker Project (www.smartworker.org)
  272. Software Engineering by shic · · Score: 1

    In line with previous replies, beauty in code certainly is in the eye of the beholder, or at least in the realm of the problem domain. To my mind the only definition of beautiful code is code without ugly features, which are somewhat easier to define. To my mind, the principle causes of ugly code are:

    • Failing to meet (nebulous) requirements fully
    • Inappropriate (or even worse, misleading or contradictory) documentation/comment.
    • Inappropriate encapsulation
    • Exhibiting redundant source code
    • Inconsistency of notational style and inappropriate naming conventions
    • Employing inappropriate algorithmic techniques

    So, logically speaking beautiful code should emerge when the above errors are avoided for an interesting problem. The first point is trivial and has been covered by other replies "The software must work". The second point is dear to my heart - absence of commentary is bad, but banal, contradictory or otherwise invalid annotation is far worse! Encapsulation must be considered a central concept in any software engineering effort, and this black art should be considered fundamental. Redundant code is misleading and can have performance implications too. Adherence to house style for code is a considerable cause of strife when programmers collaborate... however a simple consistent style is important to avoid confusion. Finally, employing appropriate techniques form the conceptual link between beautiful code and beautiful programs.

    A while ago I read a great book: Programing Pearls, which discussed some of the most elegant aspects of programing the author had encountered (along with historical context). It's a great read and in my opinion highlights some fascinating historic revelations in software development... by no means a "how-to" book, nor up-to-date, but enlightening non the less.

  273. A fine example is Jaffer's SCM by Margo_Channing · · Score: 1

    see http://www-swiss.ai.mit.edu/~jaffer/SCM.html for concision, cleverness, clarity and effectiveness.

  274. I think Dia is a great example by larocca · · Score: 1

    It is a large, very well structured c program that shows how you can write object oriented code without using C++. I haven't looked at in a while, but I know that I learned a lot from it a few years ago.

    http://www.lysator.liu.se/~alla/dia/