Beta

Slashdot: News for Nerds

×

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

Thank you!

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

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

Beautiful Code Interview

ScuttleMonkey posted more than 6 years ago | from the painting-with-text dept.

Programming 286

An anonymous reader writes "Safari Books Online has just posted an interview with Andy Oram and Greg Wilson, the two editors who put together the recent O'Reilly book, Beautiful Code. "Beautiful Code" features 33 different case studies about challenging coding scenarios from some of today's most high-profile developers and OS project leaders. There's also a new Beautiful Code web site based on the book where many of the authors are blogging about their work and coding practices."

cancel ×

286 comments

Nothing to see here (4, Funny)

AuMatar (183847) | more than 6 years ago | (#20163475)

Yeah, thats about the amount of beautiful code I expect to see in my life time.

Re:Nothing to see here (-1, Redundant)

ktstzo (885924) | more than 6 years ago | (#20163499)

Damit, i didnt make the first commend LOL

Re:Nothing to see here (5, Funny)

larry bagina (561269) | more than 6 years ago | (#20163575)

If it's any consolation, you did get the coveted first typo.

Re:Nothing to see here (1)

choongiri (840652) | more than 6 years ago | (#20164597)

Incorrect. First post also got first typo. But I guess that's what you get when you post quickly. Not that it makes any difference to me - I doubt I'll be able to type fast enough in my lifetime to get a first post anyway.

Re:Nothing to see here (5, Funny)

morgan_greywolf (835522) | more than 6 years ago | (#20163563)

"If builders built buildings the way programmers write programs, then the first woodpecker that came along would destroy civilization." -- forgot who said it.
 

Sissy Boys (0)

Anonymous Coward | more than 6 years ago | (#20164789)

Real men code in assembler to boot the system for the rest of you nancies.

hypocritter? (1, Informative)

Anonymous Coward | more than 6 years ago | (#20163577)

I find it amusing that TFA has tons of html errors.

Re:hypocritter? (1)

Anonymous Coward | more than 6 years ago | (#20163649)

When I saw the subject of your comment I just envisioned very small hpipos running around bumping into each other on a linoleum floor.

This just reminds me of my friend. (5, Funny)

Anonymous Coward | more than 6 years ago | (#20163583)

His introduction to C++ teacher told him throughout the class that his code was not "pretty" because he wasn't properly commenting. The code always worked flawlessly, but still she marked "-1 code not pretty"
On the final project he spent a good portion of time properly commenting all of his code and ended with a commented ascii flower and the following:

//Look at my flower,
//my pretty pretty flower.
//Now my code is pretty

He was marked off "-1 Sarcasm not appreciated"

Re:This just reminds me of my friend. (2, Funny)

morgan_greywolf (835522) | more than 6 years ago | (#20163655)

And to think if he posted it on Slashdot, he might've actually gotten a +5 Funny! ;)

Re:This just reminds me of my friend. (4, Funny)

mrchaotica (681592) | more than 6 years ago | (#20164199)

He should have removed one syllable from the last line; then he would have gotten "+1 haiku!"

The OpenBSD code is studly. (3, Informative)

Anonymous Coward | more than 6 years ago | (#20163591)

If you haven't looked at it already, you should glance through the OpenBSD [openbsd.org] source code [openbsd.org] . It's truly remarkable how well-written it is. But I wouldn't consider it "beautiful". I think studly is a better word. It's rugged, strong, and built to handle the toughest of the tough.

Re:The OpenBSD code is studly. (3, Informative)

Anonymous Coward | more than 6 years ago | (#20164237)

You know.. I've run across a particular bug in the OpenBSD source code on at least two occasions. Specifically, NULL is being treated as a null character.

Now, there's some bit of wiggle room for OpenBSD, since NULL can be either:

#define NULL 0
or

#define NULL ((void*)0)
(or something equivalent, like 0L, etc).

Anyway, I presume OpenBSD uses the first definition, because otherwise a diagnostic is required when void* is assigned to a char. If NULL is defined as 0, an unfortunate coincidence allows it to be assigned to chars, since 0 is the null byte.

However, it's still bad code. It's not portable (which OpenBSD might not care about), but it represents an ignorance of the language. There's really no reason to do something in a non-portable manner when it's just as easy to do it portably; who knows, perhaps in the future OpenBSD's C library maintainer will realize that defining NULL to be (void*)0 has advantages and the application will not build; or at least not build without diagnostics.

If the OpenBSD developers like using a macro instead of an unadorned zero, it's easy enough to make one yourself. Though many people find '\0' to be sufficiently self-documenting, much in the way that writing NULL is self-documenting, when you compare it with writing a zero.

In short:

char *pointer = NULL; /* Portable, self-documenting */
char *pointer = 0; /* Portable, perhaps not as self-documenting */
char character = '\0'; /* Portable, self-documenting */
char character = 0; /* Portable, perhaps not as self-documenting */
char character = NULL; /* NOT portable! Try with GNU C library 2.5 (probably other versions too) */
(the comments would line up nicely if I knew anything about HTML)

gcc will whine about a conversion without a cast on the last one; that doesn't mean a cast is the way to fix it, though! Odds are it will work but there's no guarantee and it's just not pretty, especially when both of the examples above it are legal.

If you want to see this bug in OpenBSD, check src/usr.bin/cvs/history.c.

I have no desire to report the bug to OpenBSD, because there appears to be a much better than even chance that the reply will be hostile and childish.

Re:The OpenBSD code is studly. (1)

dextromulous (627459) | more than 6 years ago | (#20164671)

char character = NULL; /* NOT portable! Try with GNU C library 2.5 (probably other versions too) */

True. AFAIK this code is not meant to be portable to other libraries or operating systems which is why it is in the OpenBSD CVS (they maintain the code in their CVS repositories.)

Re:The OpenBSD code is studly. (4, Funny)

garett_spencley (193892) | more than 6 years ago | (#20164377)

Hey Theo ... haven't chatted with you in a while. How's it going ? Family doing well ?

People hate my gotos (2, Insightful)

jimmyhat3939 (931746) | more than 6 years ago | (#20163605)

But I find goto is often as beautiful as it gets:

for (loop 1) {
      for (loop 2) {
            if (something happens that makes me want to bail on both loops) {
                  goto loop_done;
            }
            do_inner_loop_work;
      }
}

loop_done:

Re:People hate my gotos (-1, Flamebait)

Anonymous Coward | more than 6 years ago | (#20163641)

Do they tell you to "goto hell;"?

Re:People hate my gotos (1, Informative)

morgan_greywolf (835522) | more than 6 years ago | (#20163681)

Um, ahem. You might want to take a look at a while { } loop instead

Re:People hate my gotos (2, Interesting)

morgan_greywolf (835522) | more than 6 years ago | (#20163717)

IOW, for those that need visuals:

i=0;
while (not condition that makes me want to bail) {
                j=0;
                while (not condition that makes want to bail) {
                                  inner loop
                }
                outer loop
                i++
}

Re:People hate my gotos (1)

morgan_greywolf (835522) | more than 6 years ago | (#20163739)

oops. Need a j++ after 'inner loop'

Re:People hate my gotos (3, Informative)

ben_rh (788000) | more than 6 years ago | (#20164457)

That's still better as a for { } loop. Apart from it's concise variable initialisation and post-loop statement, for is while.

for (i = 0; not bail_condition; i++) {
    for (j = 0; not bail_condition; j++) {
        inner loop
    }
    outer loop
}

Re:People hate my gotos (3, Insightful)

jimmyhat3939 (931746) | more than 6 years ago | (#20163771)

Personally, I think that is uglier than goto. Also, I think it's more confusing, because you have this condition repeated twice, and you'd have to have a "break;" in the right spot in the inner loop, as well as some sort of a condition check right after you get out of the inner while loop to ensure the remainder of the outer while loop does not execute once the condition is met. Yes, you can do this a lot of different ways, but you have to torture the while/for syntax to avoid goto.

Re:People hate my gotos (1)

morgan_greywolf (835522) | more than 6 years ago | (#20163823)

What's beautiful code? Beauty is in the eye of the beholder. Personally, I think all instances of goto are ugly. But, then again, I grew up in the days when every kid with a BASIC interpreter thought he was a 'programmer'. I remember horrible, horrrible spaghetti code that used lots and lots of GOTOs. Hell, i even wrote a bunch of code like that. *shudder*

While I do think that the OPs example isn't spaghetti code, the appearance of goto makes me want to wretch.

Re:People hate my gotos (0)

Anonymous Coward | more than 6 years ago | (#20163851)

retch, even.

Re:People hate my gotos (5, Interesting)

garett_spencley (193892) | more than 6 years ago | (#20164203)

Any crap programmer can write spaghetti code with or without the use of 'goto'.

If goto were not useful or necessary then languages would have dropped it years ago when CS profs started to dread it because they couldn't teach their students properly and got tired of spitting out idiot programmer after idiot programmer who tortured them with goto-ridden spaghetti code.

Telling people to NEVER use goto is like saying "never use a chainsaw because if you attempt to cut down a weed you'll just end up with a big mess". So what, we use a hand saw to cut down an oak tree ? There are far more elegant solutions for a lot of things that can be accomplished with goto. Conversely, there are occasions where goto makes for a more elegant solution.

At the very least, as you put it "beauty is in the eye of the beholder". Using your own philosphy I opt for giving programmers all of the necessary tools that they may find useful, and deciding for themselves which ones to use. After all, there are some programmers out there who could write code that is 100 x more efficient and elegant using ONLY gotos in C with main as the only function than I ever could using goto-free, well designed and thought-out object oriented Java, for example.

No matter what you do, the end result will always be the same anyway. Exceptional programmers will continue to produce exceptional code and pasta chefs will continue to produce spaghetti.

Re:People hate my gotos (1)

ozzee (612196) | more than 6 years ago | (#20164555)

Any crap programmer can write spaghetti code with or without the use of 'goto'.

translates to:

"I can write bad code in any language!"

... which is one of my fav. responses to language wars.

Cool. You just wrote a bug. (0)

Anonymous Coward | more than 6 years ago | (#20163959)

Look at the original (pseudo) code.

When the condition that makes me want to bail occurs in the inner loop, the outer loop code is NOT executed again.

However, your "fix" resulted in the outer loop code getting executed once after condition that makes me want to bail is reached in the inner loop.

Lets hope you don't write avionics or life support software.

Unfortunately, to maintain the original meaning and avoid the goto it takes:

i=0; // I wonder why we are initializing counters for while loops
while (not condition that makes me want to bail) {
                j=0; // I wonder (again)why we are initializing counters for while loops
                while (not condition that makes want to bail) {
                                  inner loop
                }
                if (not condition that makes me want to bail) {
                                  outer loop
                                  i++
                }
}
Yes, that's right, you have to check condition that makes me want to bail 3 times

hmmmm... Maybe goto's shouldn't be considered so harmful. Labeled breaks are probably the best thing. Simplifies the code but doesn't let arbitrarily you jump INTO a block.

 

Re:People hate my gotos (1)

Breakfast Pants (323698) | more than 6 years ago | (#20164093)

j++;

Re:People hate my gotos (1)

jbellis (142590) | more than 6 years ago | (#20163719)

fortunately newer languages solve this with labeled loops and break <label> and continue <label>; no goto needed.

Re:People hate my gotos (1, Informative)

Anonymous Coward | more than 6 years ago | (#20163801)

Dude, those are gotos in disguise.

label:
for(;;)
{ //...

      if(condition)
      {
            break label;
      } //...
}


or

label:
for(;;)
{ //...

      if(condition)
      {
            continue label;
      } //...
}


is the same as

label:
for(;;)
{ //...

      if(condition)
      {
            goto label;
      } //...
}


So as you can see, there really isn't anything special about the labeled break statement you find in a language like Java. It's essentially just a C-style goto, but invoked without using a "goto" keyword. That helps make it acceptable to those who don't see the goto as the tool that it is, but instead see it as some kind of monstrosity (when it isn't).

Re:People hate my gotos (1)

poot_rootbeer (188613) | more than 6 years ago | (#20163871)

fortunately newer languages solve this with labeled loops and break and continue ; no goto needed.

0x05 dollars says that "break (loop-label)" and "goto (post-loop-label)" compile to almost identical opcodes.

Re:People hate my gotos (2, Interesting)

garett_spencley (193892) | more than 6 years ago | (#20164111)

Exactly. Loop breaking is just one of the most popular justifications for using goto. Solving nested loop breaking alone is an attempt to please both camps by saying "ok so there are *some* times where using goto makes sense but we were taught from the time we were still in diapers that you must NEVER use goto so we'll just fix that by applying a band-aid".

Goto has been a feature of almost every programming language for a reason. It is useful. If it weren't useful then nobody would ever use it and then we could strip it from languages and no one would complain because no one ever used it to begin with because it's useless and "dangerous".

I know what I'm about to say next is cliche but try grepping for goto in the Linux kernel source.

Just because some n00bs liked to write nightmarish spaghetti-code BASIC programs 20 - 30 years ago with millinos of gotos thus inspiring CS profs everywhere to threaten beating their students with paddles if they used a single goto does not mean that it's useless, evil or "dangerous". Any crap programmer can write messy spaghetti code with or without a goto.

Of course, by the same logic, coming up with better ways to do things is at the heart of everything technology. But I'm not convinced that adding in control structures to break out of nested loops is any better than just using a goto. It seems to me like these languages are trying to find a way to eventually get goto out of them (or they don't have goto to begin with and are now trying to make up for it's absence because they've started to realize is useful after all).

Re:People hate my gotos (2, Informative)

Jaime2 (824950) | more than 6 years ago | (#20164605)

I think part of the problem might be that compilers have a hard time figuring out gotos. GOTO doesn't imply any scope transition and the compiler has to figure it out. However, BREAK is very clear on which scope is being abandoned. Also, a goto will always compile (well, it depends on the language), but a break with a label will only compile if used in a sane manner.

BTW, I met a guy whose biggest dissapointment with VB.Net was that they did away with GOSUB. I shot him.

Re:People hate my gotos (3, Insightful)

Crispy Critters (226798) | more than 6 years ago | (#20164639)

So what if they compile to the same code? Source code is for humans to read, and machine code is for machines to read. Comments don't show up in the compiled code at all. Does this mean that they serve no purpose?

Break's and goto's are very different, and I am surprised to see so many people say that they are essentially the same. When I am reading code and I see a break statement, I know where the flow goes. When I see a goto statement, I have no idea where the flow goes unless the label is withing a few lines. That is the difference.

Re:People hate my gotos (0)

Anonymous Coward | more than 6 years ago | (#20163743)

In JavaScript you can use labels:

outer:
for (loop 1) {
      inner:
      for (loop 2) {
            if (something happens that makes me want to bail on both loops) {
                  break outer;
            }
            do_inner_loop_work;
      }
}

Posting as AC for obvious reasons :)

Re:People hate my gotos (0)

Anonymous Coward | more than 6 years ago | (#20163957)

Java also.
Also posting as AC for obvious reasons :)

Re:People hate my gotos (1, Insightful)

RootsLINUX (854452) | more than 6 years ago | (#20163819)

How about this as an alternative:

bool continue_loop = true;
for (loop1 && continue_loop) {
      for (loop2) {
            if (termination condition == true) {
                    continue_loop = false;
                    break;
            }
            do_inner_loop_work();
      }
}


Re:People hate my gotos (1)

DuckWizard (744428) | more than 6 years ago | (#20163873)

Don't you know that there is no circumstance under which use of goto is acceptable?

Similarly, I propose that JMP should be removed from every instruction set, because it is too much like goto and therefore is pure evil.

Beware the raptors ... (5, Funny)

Anonymous Coward | more than 6 years ago | (#20163915)

http://xkcd.com/292/ [xkcd.com]

That is all.

Re:People hate my gotos (-1, Flamebait)

Anonymous Coward | more than 6 years ago | (#20164067)

If you're still writing C in 2007, I guess you're kind of stuck: the language provides no syntactic abstraction. so hacks like that are ubiquitous.

I always end up missing Lisp's return-from (or using it, on the projects where I can use Lisp). I'm still a bit shocked that virtually no other language allows you to return a value up to an arbitrary enclosing scope.

In your case, for example, you have to label "loop_done", which isn't really relevant to your loop. You really only want to escape your scope, but to do so you have to label something outside of (and after) it to "go to". You must be a C programmer, to think that's beautiful.

Re:People hate my gotos (1)

Ekarderif (941116) | more than 6 years ago | (#20164207)

return_val func(needed_variables) {
    for(loop 1) {
        for(loop 2) {
            if(something_requires_breaking_out) {
                return relevant_information;
            }
        }
 
        do_inner_loop_work;
    }
}
Simple isn't beautiful. goto is never beautiful.

Re:People hate my gotos (0)

Anonymous Coward | more than 6 years ago | (#20164291)

What the fuck are you talking about? Simple code is usually not only beautiful, it's also usually efficient, easily-maintained, and quicker to write correctly.

Maybe it makes your ego feel really big when you write some convoluted monstrosity in Java. But for those of us who are in the real world, where we have to deal with scalability and maintainability, we tend to consider people like you to be fools.

Re:People hate my gotos (1)

Ekarderif (941116) | more than 6 years ago | (#20164551)

Simple is not synonymous with beautiful, and it never will be. Good code is beautiful but not necessarily simple. If your head wasn't up your ass, you'd realize this immediately.

Re:People hate my gotos (2, Insightful)

compro01 (777531) | more than 6 years ago | (#20164757)

simple code is always beautiful, but beautiful code isn't always simple.

Re:People hate my gotos (0)

Anonymous Coward | more than 6 years ago | (#20164235)

The whole thing should be inside a function:

function foo() {
    for (loop 1) {
                for (loop 2) {
                            if (something happens that makes me want to bail on both loops) {
                                    return;
                            }
                            do_inner_loop_work;
                }
    }
}

no goto, same structure, nicer all round: best of both worlds.

People hate my returns. (1)

Javagator (679604) | more than 6 years ago | (#20164543)

I usually put the loops in a method and do it like this.  People don't like my returns in the middle of a loop either.

for (loop 1)
{  for (loop 2)
   { if (some condition)
     {  return;
     }
     do work;
   }
}

Re:People hate my gotos (1)

urbanRealist (669888) | more than 6 years ago | (#20164665)

do_work(){
        for (loop 1) {
                    for (loop 2) {
                                if (something happens that makes me want to bail on both loops) {
                                            loop_done();
                                            return;
                                }
                                do_inner_loop_work;
                    }
        }
}

loop_done(){
        loop_done;
}

Re:People hate my gotos (1)

locster (1140121) | more than 6 years ago | (#20164783)

It drives me crazy the number of coders who still, in 2007, have a bee in their bonnet about goto statements (they're just evil apparently) or return statments in the middle of a function body - often prefering the alternative of umpteen nested if statements indented right off the the screen. I remember rolling my eyes when being taught these sorts of rules at university, the thought that some people actually took them seriously and are still using them years later just shows how willing some people are to blindly follow rules without question. I guess that's what distinguishes a code monkey from a coder?

Sure... (1)

skoaldipper (752281) | more than 6 years ago | (#20163637)

Programmer - You are sooo beautiful. My masterpiece. My pies de resistance!
[ Kisses screen and compiles code into native instruction set ]
CPU - Hmm. Where have I seen your fugly face before?

Re:Sure... (1)

WhiteWolf (95535) | more than 6 years ago | (#20164225)

Hello world, is that you?

Have to say... (0)

Reality Master 101 (179095) | more than 6 years ago | (#20163665)

I always get burned at the stake when I say this, but the biggest problem with OSS that I run into is horribly ugly code with very few useful comments. My favorite whipping boy example of this is 'ssh', one of the more critical applications. If I had written that thing, I'd be hiding my head in shame (apparently Theo seems pretty proud of it, though).

I'm sure there has to be *some* good examples of open source beautiful code out there (heck, I know at least one exists... I released it myself a long time ago. I'm a huge believer in well commented, well structured, understandable code), but I have yet to see a really good example other than my own.

Re:Have to say... (5, Funny)

Anonymous Crowhead (577505) | more than 6 years ago | (#20163737)

I have yet to see a really good example other than my own.

I, too, am the only one I know who writes decent code.

Re:Have to say... (4, Interesting)

kevin_conaway (585204) | more than 6 years ago | (#20163755)

I always get burned at the stake when I say this, but the biggest problem with OSS that I run into is horribly ugly code with very few useful comments

I struggle with this. When I was in school, my instructors drilled into me the importance of documentation and comments. Now that I've been in the real world, I have to say that I don't agree.

The problem with comments is that you now have two things to maintain, the code and the comments. Often time this is OK for a single developer but for someone coming in to maintain a piece of code, often times they are hesitant to touch the comments especially if they are wrong.

I find that (for me at least) I have the greatest success with short, composed methods that do one thing and one thing well all backed up by unit tests that test behavior and requirements, not simply that foo() returns 15.

You might be thinking that I'm contradicting myself here because now I have to maintain both code and tests. However, I feel that the tests provide much more value in that once a test for a piece of code works, you now have confidence in that piece of code. If you miss something with the test, its a simple matter of adding a new test for that case.

Re:Have to say... (4, Insightful)

Reality Master 101 (179095) | more than 6 years ago | (#20163827)

Now that I've been in the real world, I have to say that I don't agree.

I have to respectfully say that if you believe this, you haven't written 1) enough code, and 2) complex enough code, to have filled up your brain sufficiently to where you can't remember what the hell you were thinking at that time. When you've reached that level of programmer maturity, THEN you will understand the importance of comments. :)

Never mind trying to blaze the trail for programmers that come after you. I also predict that you haven't tried to unravel another programmer's crappy code.

The problem with comments is that you now have two things to maintain, the code and the comments

Yes. People who change code but don't update the comments should be flayed appropriately.

I find that (for me at least) I have the greatest success with short, composed methods that do one thing and one thing well all backed up by unit tests that test behavior and requirements, not simply that foo() returns 15.

Testing and commenting are two different subjects. Comments are not to tell you that "foo() returns 15", comments are to tell you the *context* of code, how it fits in with the overall goal of the subroutine.

Re:Have to say... (2, Interesting)

kevin_conaway (585204) | more than 6 years ago | (#20164089)

I have to respectfully say that if you believe this, you haven't written 1) enough code, and 2) complex enough code, to have filled up your brain sufficiently to where you can't remember what the hell you were thinking at that time. When you've reached that level of programmer maturity, THEN you will understand the importance of comments. :)

Again, I think that this is where the importance of short, composed methods really shines through. If every method you're looking at is 5 - 10 lines long, its a lot easier to grasp what a block of code is doing. Of course, one could get carried away and get "delegation happy" but thats what a good debugger is for :)

Never mind trying to blaze the trail for programmers that come after you. I also predict that you haven't tried to unravel another programmer's crappy code.

I have and its unpleasant. At my previous job, I worked with some poor developers who happened to be non-native English speakers. When comments are written in English and the person writing them does not have a solid command of the language, it can get ugly.

I'm young in my career and time could certainly change my attitude but for the time being, I stand by my original post.

Re:Have to say... (1)

mrchaotica (681592) | more than 6 years ago | (#20164259)

If every method you're looking at is 5 - 10 lines long, its a lot easier to grasp what a block of code is doing.

Sure, you can figure out what the code is doing, but in order to know why the code is doing it you still need comments.

Re:Have to say... (1)

quanticle (843097) | more than 6 years ago | (#20164733)

Tests can be a form of documentation too. A proper suite of unit tests will show exactly what a method does. If the method does something different than expected then the tests will fail.

Re:Have to say... (1)

yuda (704374) | more than 6 years ago | (#20163925)

I've been webcoding sice around '01. I've recently had to go back and do some work on a site I haven't touched in around five years. The thing I found was really ugly code and almost no comments - ok I was using dreamweaver at the time and have graduated to hand coding since. It was bloody hard to do even quite basic alterations. I was half tempted to do a complete re-design using css and w3c standards. As it stands at the moment I'm pretty embarrased that I ever set such ugly code into the wild

Re:Have to say... (1)

HoosierPeschke (887362) | more than 6 years ago | (#20164061)

Don't feel bad, I've used FrontPage and designed IE only sites before... now it's all proper xhtml and css. The best thing about making mistakes is learning from them.

Bingo (0)

Anonymous Coward | more than 6 years ago | (#20164167)

You've hit the nail on the head. If your code is too mysterious, it is usually easier to re-write from scratch than to modify it.

For many years, all my code has been self-documenting. http://en.wikipedia.org/wiki/Self-documenting [wikipedia.org] The result is that I can easily maintain the code and it's not too hard to find and re-use chunks of it. The joy of self-documenting code is that the code and the comments are maintained together.

Even for embedded stuff, I usually find that it is well worth the effort to do a good job of commenting it.

Re:Have to say... (1)

Porchroof (726270) | more than 6 years ago | (#20164173)

So, you would rather write code and tests rather than code and comments?

Sounds to me like more work and less information available for the poor fool who has to maintain that code after you leave.

And WTF do tests have to do with writing and maintaining code? You have to test everything regardless of how pretty or informative your code is.

All of the programmers (I wouldn't call any of them "software engineers") whom I've worked with the past 25 years thought that writing comments to their code was for wimps. (Much like the pickup truck drivers who think their balls will shrink if they turn on the headlights on a rainy day.)

Frankly, they just don't want to be bothered writing maintainbale code because it takes time and requires some intelligence. (I'm talking about you, Bob, Ron, John, Dan or whoever's left at FAPD.)

Then you're doing it wrong! (0)

Anonymous Coward | more than 6 years ago | (#20164341)

If you have to update the comments every time, you're probably doing it wrong or your design changes a *lot* (in which case, why didn't you make better plans?).

The comments should tell me *why* the code is doing what it's doing, not WHAT it's doing. I don't think anyone finds comments like this helpful:
++i; // Increments variable i by one

However, comments like this may keep you from going crazy someday:
float fastInvSqrt(float x) { /* Off by 1.5% at most. ~50 cycles faster than the more accurate version. */
}

Re:Have to say... (1)

GrievousMistake (880829) | more than 6 years ago | (#20163899)

I don't know why you'd single out open source, this applies to code at large. I think it's just one of those '90% percent of everything is crap' things.

Re:Have to say... (1)

Reality Master 101 (179095) | more than 6 years ago | (#20163983)

I don't know why you'd single out open source, this applies to code at large. I think it's just one of those '90% percent of everything is crap' things.

I agree that a lot of closed source code is crappy as well, but there's at least a chance of institutional standards that can be enforced. There's also a higher proportion of professionals that believe in good code, whereas you have a higher proportion of amateurs for OSS (because anyone can work on an OSS, but not everyone can manage to be hired at a company).

Re:Have to say... (1)

Breakfast Pants (323698) | more than 6 years ago | (#20164363)

It is much easier to get hired at a company than to produce open source code that anyone other than you will ever either use or look at.

Re:Have to say... (1)

gmf (810466) | more than 6 years ago | (#20163945)

I always get burned at the stake when I say this, but the biggest problem with OSS that I run into is horribly ugly code with very few useful comments.
The sad thing is, as far as I can tell, this is true for the vast majority of closed source code as well. You just don't tend to see closed source code as often...

The problem with the book... (5, Funny)

BlueBoxSW.com (745855) | more than 6 years ago | (#20163729)

Anyone else have laugh when they looked at the cover of the book?

A Flock of Birds?

To symbolize beautiful code?

Flock-of-Birds-style code is the UGLIEST code out there!

Used only by those who haven't learned to use case statements, build databases, or define arrays.

Is this beautiful code???

if(something==interesting)
    if(somethingelse==goodcode)
        if(somethingother==blahblahblah)
            if(somestupidbookcover=birds)
                doSomethingUseful();
            else
        else
    else
else
    if(somethingelse==goodcode)
        if(somethingother==blahblahblah)
            if(somestupidbookcover=birds)
                doSomethingUseful();
            else
        else
    else
end if
 

Re:The problem with the book... (2, Funny)

morgan_greywolf (835522) | more than 6 years ago | (#20163779)

There's a name for that garbage? Well, color me stupid. Learn something new every day.

Re:The problem with the book... (1)

intx13 (808988) | more than 6 years ago | (#20163881)

I dunno.. it could have been a big plate of spaghetti, or as my boss likes to say "a tornado hitting a spaghetti factory".

Re:The problem with the book... (0)

Anonymous Coward | more than 6 years ago | (#20164763)

Is this code at all? What language allows you to end an if block with an else?

beautiful code (4, Funny)

lottameez (816335) | more than 6 years ago | (#20163833)

while (1){
Beer b = (Beer)getBeer();
drinkBeer(b);
belch(BelchType.LOUDLY);
}

Re:beautiful code (2, Funny)

RetroGeek (206522) | more than 6 years ago | (#20164055)

You forgot to add inside the loop:

Bladder blad = Bladder.getInstance();
if ( blad.isHurting() )
{
  bld.empty();
}

Re:beautiful code (1)

RetroGeek (206522) | more than 6 years ago | (#20164075)

Sigh...

that would be:
blad.empty();

Re:beautiful code (1)

garett_spencley (193892) | more than 6 years ago | (#20164233)

It's times like this I wish you could moderate +1 Sexy

Dangers of binge drinking (1)

ichigo 2.0 (900288) | more than 6 years ago | (#20164271)

There is a memory leak in your code. Or maybe it's a feature?

Re:Dangers of binge drinking (1)

another_fanboy (987962) | more than 6 years ago | (#20164787)

There is a memory leak in your code.

Like everyone else I know, he cannot remember how many he's had. That way, he feels no regrets over having "just one more".

Most code is beautiful at one point in time (4, Insightful)

intx13 (808988) | more than 6 years ago | (#20163861)

Most code is beautiful at one point in time - namely, when it's first written. A decent programmer can produce some decent code that performs the task at hand elegantly. With a little work this can become beautiful. Most applications I write start out very elegant, beautiful, commented, clever, etc. - It's only after the project grows and I'm working on a file named "main4.3.a.iii.bak2.worksithink.c" that the comments turn into "// why is this here?" and the variables go from "nDBEntryCount" to "temp" and the code becomes an ugly mess.

The real trick is DESIGNING the application in such a way that it can grow gracefully, and STAY beautiful. And that's really tough - knowing what sorts of features and requirements the future will hold is difficult. A big part of this is the language itself - I love assembly languages, and I could write some really clever and beautiful assembly code. But when the requirements change and the code needs a new feature? There goes all the carefully timed loops and cycle counts!

Beautiful code is as much beautiful, expandable, future-proof design as it is beautiful implementation.

Re:Most code is beautiful at one point in time (1)

DittoBox (978894) | more than 6 years ago | (#20164309)

Code is pretty. Programs are beautiful.

Re:Most code is beautiful at one point in time (1)

garett_spencley (193892) | more than 6 years ago | (#20164355)

The real trick is DESIGNING the application in such a way that it can grow gracefully, and STAY beautiful. And that's really tough - knowing what sorts of features and requirements the future will hold is difficult.

You've just described why reusable code, and simplicity, is so important.

You started off hitting the nail on the head. Applications need to be designed so that they can grow with grace and retain their elegance. However, it is impossible to predict the future and I've seen so many projects where the list of "to be supported in the future" lead to so much foundation code that's only purpose was to support features that never came to pass and they became bloated. Sure they had the room to support those features, but as the requirements grew further and further away from what the designers originally thought was going to happen, the application just ended up becoming a mess.

Thus what you need to do is design everything to be re-usable and extensible. Write your functions, classes, interfaces, libraries etc. to do one thing only, and do it very well. When you start to see a block of code getting too big, break it down into smaller blocks. Design for the possibility of unlimited extension in the future without knowing what the future will demand of your project. And most importantly, keep things as simple as possible, and continue to do so as you add more features.

Re:Most code is beautiful at one point in time (1)

gmf (810466) | more than 6 years ago | (#20164701)

Yeah, you should design your code from the start in a way that allows it to grow and stay beautiful. But don't forget about refactoring. When it turns out that things don't fulfill the needs the way they are, don't just work around it by adding even more messy code. Of course, changing the structure of your code to adjust to new requirements takes time, but sometimes it's the only way keep things clean. And sooner or later you'll be glad you did it.

No. That is not a trick, that's doom. (1)

Uksi (68751) | more than 6 years ago | (#20164749)

When you're done designing your application in a way that it will grow gracefully and stay beautifully, come see me, because you'll be out of a job for not shipping the product on time.

You say that knowing the future requirements is difficult. That's the key insight: you just don't know. And unless you know, or have a good likely-to-happen general idea, you should not design it in any way other than as simple as it needs to be for right now. And if you guess, you are likely to end up with flexibility in all the wrong places.

The trick is to design simple for what you need now (easy), and then be able to expand your design to stay simple (hard).

This is difficult to accomplish because changing existing code is a no-no in software dev corps. "If it ain't broke, don't fix it" mentality dooms your project and causes you to accumulate massive design debt because of the hacks and not-simple solutions that do not touch existing code.

This design debt grows to mountain proportions, at which point everyone throws their hands up and assert that a complete rewrite is required.

The cure is to perform test-driven development, so that you are not afraid to change existing code. I can't emphasize how liberating it is to be able to come in and uproot some inflexible crap (which was good enough for a long time, but is not anymore), put in an improved design, and then know that you didn't break anything. You can roll with the punches and not waste your time designing in unnecessary flexibility.

Re:No. That is not a trick, that's doom. (1)

Uksi (68751) | more than 6 years ago | (#20164779)

I wanted to add that this is why many people become jaded in one direction or another.

For myself, the learning curve went something like this:

1) Was tight on time, decided to copy/paste code and not design in flexibility for things I thought could probably use it. Ended up taking more time than I probably would have otherwise and turning out some poor inflexible code. At this point, I swore to design everything up-front first.

2) Next time around decided that I will design, design and design. End up spending a ton of time designing with all sorts of flexibility in place, so much time that the project never got finished or really gotten anywhere. At this point, I am scarred and have no idea what the right answer is.

3) Spend the rest of the time being afraid of underdesign, and yet also being afraid of overdesign. Due to time pressure, was afraid to revisit poor design decisions (poor in retrospect), and end up churning out mediocre code that you see in your everyday company.

This is where most programmers are. They know that underdesign is bad and they can't spend all the time overdesigning, so anything that gives the impression of either is bad, even if it's the right thing. Under time pressure, most people gravitate into underdesign, writing hacky code and never coming back around to fix it.

Beautiful Code (0, Interesting)

Anonymous Coward | more than 6 years ago | (#20163879)

It's nice that the code is beautiful, but is it FUNCTIONAL?

Too many code monkeys spend hours hand-tweaking stuff, formatting stuff, forgetting it's about the FUNCTIONALITY.

Where are the Test-Case Discussions. Beautiful code needs testcases that are the same.

Another Book Written by and For Code Monkeys. Let know when the Engineering version comes out.

Re:Beautiful Code (1)

Fahrenheit 450 (765492) | more than 6 years ago | (#20164097)

Where are the Test-Case Discussions. Beautiful code needs testcases that are the same.

Perhaps in chapters 6 and 7?

atari 2600 (-1)

Anonymous Coward | more than 6 years ago | (#20163893)

atari 2600 kernels

I've become jaded (5, Insightful)

syousef (465911) | more than 6 years ago | (#20163989)

Is anyone else jaded by these books that go on and on about why a particular techique or code snippet or methodology is "right" or "beautiful" or "the way forward"?

I look at some of the code mentioned and yes it's neat. Some of the code snippets from these books (not just this one specifically) is either really obvious or makes me want to blow chunks because it's an over-complication or over-simplification just to demonstrate a technique which you know will be over-applied and end up in some set of corporate standards that sees it being misused. ...then there's some of the frameworks and methodologies out there that are generally worshiped as God's own code, but which when you try to use them turn out to be cumbersome, horrible, unintuitive messes. Years later this is suddenly "discovered" (EJBs I'm thinking of you!!!) and a whole new set of horrible frameworks goes through several iterations (Hibernate 1 vs 2 vs Spring persistence, Struts vs Spring MVC) where nothing is allowed to mature for long enough to have the major bugs ironed out.

Perhaps I'm just getting old but I'm really getting tired of all this. You want to know what makes code beautiful?

1) It does the job 100% correctly as intended.
2) It does it as simply as possible - not so simple it doesn't work, and no more complex than it absolutely needs to be...building everything in but the kitchen sink just in case is a fool's game.
3) It's readable and well documented enough that anyone who knows the language (or better yet a programmer familiar with a similar framework but not this one) understands it.
4) Its easy and quick to make changes as requirements change - that means GUI tools for GUI development (What ever happened to RAD tools being the norm in the industry!? It can take a week to make significant changes to a web page in Struts or Spring MVC, where it use to take about a day to do it for the clients developed with the RAD tools of the late 90s!)
5) It fits in well with the rest of the system. A module that works beautifully in isolation but doesn't fit in with the system can ruin the system.

All the rest is just a bunch of consultants trying to bilk you for cash.

Yes patterns can help, but they can also hurt.
Yes externalizing code into config files can make a system more flexible (but you'll pay for it in readability and tracability/debugability).
Yes aspects of the agile methodology - continual integration and test driven coding - can help but they're not the only way and there's a cost associated.
Yes Object oriented code offers things that procedural does not, but again there's a cost and your developers better understand the language constructs.

You need to look at each of the above as tools in your arsenal, not religious doctrine.

Note that my recent experience is with Java/J2EE so that's where my examples come from but I've worked on dozens of languages and frameworks.

Re:I've become jaded (2, Insightful)

RetroGeek (206522) | more than 6 years ago | (#20164145)

You forgot "working within the langauge".

I have seen examples where a person knows langiage A but is working with language B. And by God he WILL try to make language B work like language A, come hell or high water.

This is where you get "clever code". Which is un-maintainable.

Re:I've become jaded (1)

syousef (465911) | more than 6 years ago | (#20164239)

Yeah I've seen that too - I use to know a guy in Uni who originally learnt BASIC, and always had a set of #defines in a header file he'd use to make BASIC constructs work in C. What a mess!

Re:I've become jaded (1)

mrchaotica (681592) | more than 6 years ago | (#20164337)

Yes Object oriented code offers things that procedural does not, but again there's a cost and your developers better understand the language constructs.

Or, how about this: OO code is beneficial when you're trying to solve an inherently OO problem, but not all problems are OO. Some are procedural, some are functional, etc., and you're better off using the appropriate paradigm for the task.

Stupid frameworks. (5, Insightful)

mattgreen (701203) | more than 6 years ago | (#20164481)

Ugh, Java frameworks.

Somebody needs to drag the people who make these things in a room, erase their memories, and make them use what they have created. Perhaps then they can start to feel how asinine they can be sometimes. It is as if they get off on how many design patterns, random XML config files, and other "best practices" they can cram into a single framework. "We're switching to using a BuilderFactoryGatewayStrategyFacade." Thanks for the heads-up guys, we were all dying to know exactly how you implemented it! (Don't forget to scatter pattern names all over your code. People have to know you're using them!) All I want to do is integrate such and such framework in with my program. But, no, I have to read the documentation that describes the problem and how exactly to use the framework. Inevitably, they begin spouting off about how "elegant" it is that you can configure exactly which IntFactory to use by hard-coding the classname in a mandatory configuration file that is prone to getting lost at deployment time. (Remember, making objects with just the new operator is a classic beginner's mistake, don't fall prey!)

The end result is you end up with what should be a fairly simple task (like OO-relational mapping) have 400 page manuals because it ends up doing every little thing that people want to do. In the time it takes you to choose the right framework, download and install the binaries, wade through the required config files, sift through the quickstart, and actually get familiar with how it is done, you could have just written and tested the tedious JDBC code to load and unload an object from the database.

But, why do that? There's no hype around that! You're not REALLY an enterprise architect until you have twenty different config files that need to be present just to run your product! If it is an enterprise product, it shouldn't be simple to configure!

All of these products do serve legitimate needs. But the obsessive over-engineering that surrounds them and the religious fervor by which they are declared Good (despite violating the principle of least surprise at every turn) point to fear. A fear that the code you're writing just isn't good enough somehow. The fear that your code is too simple, too straightforward. A worry that that requirement you're meeting is mission-critical, and, mishandled, could threaten the stability of the entire system. This isn't usually the case. It would seem that Java's simplicity sort of drives its hardcore users mad after awhile. What it lacks in expressiveness, people try to make up for by inane configuration and extensibility instead of just sitting down and Getting The Damn Thing Done. Sure, the code is boring. The best code is anything but glamorous.

For 876344 (0)

Anonymous Coward | more than 6 years ago | (#20164191)

87362 38726 88872 61726 67672 88872 13102 91228
77798 77798 15882 13232 54060 54060 18577 00000

But also read this (0)

Anonymous Coward | more than 6 years ago | (#20164415)

http://alarmingdevelopment.org/?p=79 [alarmingdevelopment.org]

Beautiful code (0)

Anonymous Coward | more than 6 years ago | (#20164423)

Is the code that *I* write. Because I have half a chance of remembering what it does or is supposed to do.

People think their clever when they abstract systems so much your left chasing down a seemingly bottomless call stack only to find
all it does is i++;

People think their doing you a service when they leave obvious comments that have long since become wrong and outdated. The overcommenting of their work makes what should be visible in one screen span 10 screens which *greatly* improves my understanding. At the same time they leave terse local comments inside large complex routines requring very specific domain knowledge.

People think that using a goto statement *AND* leaving a comment specifically apologizing for its use somehow detracts from their own stupidity.

People think that their saving time when they spend 10 minutes writing a code generator and proceed to cut and paste thousands of lines of eearily similiar code into *YOUR* project.

People think that they should be quibbling with each other about use of indentions, braces...etc. My only response is 'jad -p' and a general sense of needing to find someone competent enough to run our HR department.

People think its acceptable to use the source control system and code comments to carry on conversations with each other while manually reformatting each others code.

At the end of the day your judged not on how beautiful your code is. Rather: Does it work, is it maintainable (v2,v3,v4..etc) and does it make the people who made the mistake of hiring you ***money***. If the answer is no to any of those questions then you suck.

IE if it takes you 2 years to write beautiful correct code that is maintainable and works perfectly AND your project is two years late to market **you still suck**

The most beautiful code I've ever seen... (4, Interesting)

element-o.p. (939033) | more than 6 years ago | (#20164425)

...looked like this:

not exp log srand xor s qq qx xor
s x x length uc ord and print chr
ord for qw q join use sub tied qx
xor eval xor print qq q q xor int
eval lc q m cos and print chr ord
for qw y abs ne open tied hex exp
ref y m xor scalar srand print qq
q q xor int eval lc qq y sqrt cos
and print chr ord for qw x printf
each return local x y or print qq
s s and eval q s undef or oct xor
time xor ref print chr int ord lc
foreach qw y hex alarm chdir kill
exec return y s gt sin sort split

Simply elegant! My younger brother sent it to me; not sure where he got it. It's Perl, by the way.

Re:The most beautiful code I've ever seen... (1)

Alaria Phrozen (975601) | more than 6 years ago | (#20164467)

Yes it's pretty and balanced and such, and I bet you could convert it to music and it would be a fine jig, but... What does it do?

Re:The most beautiful code I've ever seen... (3, Insightful)

Anonymous Coward | more than 6 years ago | (#20164615)

prints "just another perl hacker"

Re:The most beautiful code I've ever seen... (0)

Anonymous Coward | more than 6 years ago | (#20164635)

That's the beauty of it. It doesn't do anything!

Visually and Logically Beautiful (1)

MassEnergySpaceTime (957330) | more than 6 years ago | (#20164513)

I think there are two kinds of beauty in code: visual and logical. Visually beautiful code is code that is formatted well, easy to skim through, and easy to read. This includes things like defining useful variable/function names and writing understandable comments. Logically beautiful code is code that is designed to fit together well, makes a lot of sense, and leaves no confusion. It expresses its intent in the simplest and cleanest way possible.

I think getting code to be logically beautiful is much harder of the two. It takes a lot of insight to see a simpler and cleaner way of expressing the same thing. To use a math analogy, a coder might get his code to work with this:

F = (0.25 * m * x * a * 4) / x

but not realize that it can be simplified to this:

F = m * a

You can teach people how to be visually beautiful with their code, but when it comes to logical beauty, they either have it, or they don't.

Re:Visually and Logically Beautiful (3, Insightful)

Breakfast Pants (323698) | more than 6 years ago | (#20164739)

That isn't true at all. What happens in the second case when x == 0.0 ?

Obligatory comment that 90% of programmers' (1)

ClosedSource (238333) | more than 6 years ago | (#20164547)

code sucks but I (and the 90% of programmers who make this claim) are in the remaining elite 10% that are coding Gods.
Load More Comments
Slashdot Account

Need an Account?

Forgot your password?

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

Submission Text Formatting Tips

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

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

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

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

Loading...