Beta
×

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!

Ask Slashdot: What Do You Consider Elegant Code?

Soulskill posted about 7 months ago | from the link-it-if-you've-got-it dept.

Programming 373

lxrslh writes: "Since the dawn of computing, we have read about massive failed projects, bugs that are never fixed, security leaks, spaghetti code, and other flaws in the programs we use every day to operate the devices and systems upon which we depend. It would be interesting to read the code of a well-engineered, perfectly coded, intellectually challenging program. I would love to see the code running in handheld GPS units that first find a variable number of satellites and then calculate the latitude, longitude, and elevation of the unit. Do you have an example of a compact and elegant program for which the code is publicly available?"

Sorry! There are no comments related to the filter you selected.

Duff's Device (4, Informative)

smitty_one_each (243267) | about 7 months ago | (#46582153)

Duff's Device [wikipedia.org]

Re:Duff's Device (3, Informative)

Anonymous Coward | about 7 months ago | (#46582219)

Uh... that Wikipedia article shows 3 lines of code, which it describes as "straightforward":

Straightforward code to copy items from an array to a memory-mapped output register might look like this:

do { /* count > 0 assumed */
        *to = *from++; /* Note that the 'to' pointer is NOT incremented */
} while(--count > 0);

Then this reference implementation of Duff's device:


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);
        }
}

Then this penny drops:

When numerous instances of Duff's device were removed from the XFree86 Server in version 4.0, there was an improvement in performance

Re:Duff's Device (5, Funny)

DpEpsilon (2538466) | about 7 months ago | (#46582271)

When numerous instances of Duff's device were removed from the XFree86 Server in version 4.0, there was an improvement in performance

Personally, I blame the compiler for failing to optimize properly.

Re:Duff's Device (2, Insightful)

Anonymous Coward | about 7 months ago | (#46582323)

Is this a joke? The reason Duff's Device is no longer any faster is because the modern compiler is able to optimize properly.

Re:Duff's Device (1)

DpEpsilon (2538466) | about 7 months ago | (#46582559)

Woosh.

Re:Duff's Device (2)

DpEpsilon (2538466) | about 7 months ago | (#46582569)

Sorry, I really didn't think anyone would take that seriously.

Re:Duff's Device (0)

Anonymous Coward | about 7 months ago | (#46582625)

Is this a joke? The reason Duff's Device is no longer any faster is because the modern compiler is able to optimize properly.

Is this a joke? The statement was that it became *faster* by removing multiple instances, not that the speed remained the same.
The reason for the speedup can be attributed entirely to instruction cache and branch prediction or loop optimized branching. Those are optimizations in modern CPUs that computers in the 80's didn't have.
Even modern compilers typically don't do loop unrolling unless the length in known since that introduces extra overhead that slows down the operation for short iterations, at most the compiler will look at the division and modulo and use a single instruction for both if such an instruction is available, or replace with and/shift if it is a power of 2.
The speedup noticed by removing duff's device has nothing to do with the compiler, it's just that processors have been optimized to better deal with loops.

Re:Duff's Device (2, Insightful)

Anonymous Coward | about 7 months ago | (#46582573)

Manual optimizations such as Duff's Device usually prevent the compiler from doing automatic optimizations because the effects of the code becomes obscured.

Re:Duff's Device (1)

DrJimbo (594231) | about 7 months ago | (#46582447)

According to the reference, the reason for the speed improvement had to do with the vastly different CPU architecture and specifically with getting more cache misses due to an increase in the size of the code base because of the unrolled loops.

It seems rather silly to imply that Duff's device is no longer elegant merely because it does not apply to current CPU architectures.

*CRAP*FLOODING? NO. DINGLEBERRY! (-1)

Anonymous Coward | about 7 months ago | (#46582525)

So a little while ago I felt like I had a great big healthy shit coming on. I mean it makes sense. I have been adding more fiber to my diet lately. So I sat on my white porcelain throne and then ... *unghhnhhghhghh* *PLOP* Ah. Wow that was a big one. Damn it this is a big, wide, long log. It'll probably fold in half and get stuck and clog the fucking toilet. Again. Ah well. I will deal with that if and when it happens.

It was such a wide turd-log with such girth though. Amazing that my otherwise virgin asshole can expand that wide. Hmm that could be a problem. So I start to wipe. Damn it this could take a while. I got feces smeared on the sides of my ass cheeks from the girth of that turd. I wipe some more and ... oh no. I feel something knotty. Yup, what I feared from this turd has come to pass. I have lots of hairs around my asshole. I suppose most men do. Nature's way of saying "I love you! But not that much."

There it is. I can feel it through the single ply paper. A great big DINGLEBERRY. Naturally I try to awkwardly grab it with a folded sheet of toilet paper and dislodge it. I pull. Ouch. I pull harder. OUCH. Wow during its brief passage past the asshair, this turd-let really securely managed to get caught on some ass hairs. I can't just pull the dingleberry out without ripping the hairs right out. I have no idea if that caries the possibility of breaking the fecal encrusted skin and leading to an infection or what, but I know it would hurt so I want other options. I try gathering lots of sheets of toilet paper. I repeatedly wipe the same area over and over, hoping to wear this fucker down. I manage to whittle it down a little but this is taking far too much time. This turd is really determined to stay in its new home!

I can't very well pull my underpants back up now, that would get them all shitty and smelly. If I wanted to smell bad all the time I would let myself get fat. Maybe some water will help. I awkwardly reach for the faucet, turning it to a slow stream, and wet some toilet paper, making a mental note to disinfect the faucet handle later. I can't see the damned thing but judging from the brown stains appearing on the sheets of toilet paper, I am at least making progress. Now my hands are wet and shitty smelling and I am thinking this better be worth it. I use a dry sheet to feel for the dingleberry again. It did shrink but it's still there, dangling from my ass hairs, mocking me. WTF have I been eating lately to produce such a persistent turd? Nature does abhor a vacuum, which is why lots of gas has entered my bowels where the big turd-log recently was. I enjoy a nice after-defecating loud fart while I wonder what to do next. I chuckle because when the fart is your own, you don't think it stinks but you know somebody else would evacuate the area. Ok time to stop laughing, this is a serious predicament.

I toy with the idea of getting some scissors or something to try and cut the dingleberry out. Then I consider this is a sensitive area, I cannot see what I am doing, and it's too close for comfort to my cock and balls to be wielding a bladed item. I am starting to get angry. I am starting to not care anymore about the consequences of just yanking the damned thing out. I tried the easier ways and they failed. Fuck it, I have places to be and things to do. I can't very well spend all day in the bathroom playing a not-so-fun game with a turd. I double up on toilet paper and get a good secure grip on the dingleberry. Okay fucker, you're going DOWN. *YANK* Yeouch, fuck that hurt as much as I thought it would. And there it is, in my hand, nestled in the folds of toilet paper: my dingleberry! Ha ha ha, you won the battle, dingleberry, but I just won the war! I rub my sore ass cheek. Then I ceremoniously plop that fucker in the toilet bowl, to briefly swim with his big brother log. Oh man, you never heard such a satisfying flushing sound in your life. I rub some aftershave around my ass hairs just to make sure, better to smell funny than to get some kind of infected pimples or something.

I was careful. But not careful enough. Never careful enough. It was no trivial task to scrub the fecal matter completely off my hands and especialy, from under my fingernails. I find it useful to use a bar of soap and dig my nails in it. Repeatedly. I think all the turd particles are gone now. If I eat with my hands and get sick later I will at least know why, but it hopefully will be okay. Man. What an ordeal. Anyone who ever fought against a dingleberry knows how persistently they can cling to life next to your asshole.

So I watch this mixture of feces and paper swirl around the flushing toilet bowl. Sure enough, the very middle of the log gets sucked toward the drain. Not good, not good. It folds in half and the two halves at once is too wide to fit through the toilet. Great. Now my toilet is clogged. But the water continues to rise. Oh man, this doesn't look good. Quick, where the fuck did I put my plunger?!

... the saga continues ...

Re:Duff's Device (4, Insightful)

BasilBrush (643681) | about 7 months ago | (#46582725)

It's not elegant because it's a dirty optimisation taking advantage of two inadequacies of C: The horrendous fall through behaviour of switch statements, and the lack of a requirement for proper nesting of control blocks.

The original code is far more elegant than DD.

Put it another way, the only reason for using DD rather than the original is that it was quicker on non-optimising compilers. Not that it was graceful, nor stylish, nor simple.

The fact that it's slower than the original code now makes it even less of a qualifier. It's now an optimisation failure. Something that needs to be removed to optimise.

Duffs Device is clever - its not elegant (4, Insightful)

Viol8 (599362) | about 7 months ago | (#46582321)

IMO elegance comes with simplicity and duffs device actually makes the simple fairly complex, at least from a syntactic point of view. Mind you, compared to the unintelligable contorted rubbish calling itself C++ that I've had to debug over the years its a masterclass in clarity. Anyone who suggests building a framework for any project that is going to take less than a week should be shot on the spot.

Re:Duffs Device is clever - its not elegant (0, Redundant)

Joce640k (829181) | about 7 months ago | (#46582395)

Mode Parent Up.

There's nothing "elegant" about DD.

Re:Duffs Device is clever - its not elegant (1)

Bongo (13261) | about 7 months ago | (#46582409)

Time. Good point. Many building architects defend bad designs with, "but that's all the time we had."

Either the original developers have time to iterate to a cleaner design, or the maintainers have to do it, or the original developers had lots of experience with similar frameworks that they already have better designs in mind—acquired over time.

Re:Duff's Device (1)

JaredOfEuropa (526365) | about 7 months ago | (#46582379)

That's a neat trick, but is it elegant? To me, elegance at code level means succinct and readable code. Optimizing for performance usually comes at a lower level of readability.

Look at the examples from that article:

do { /* count > 0 assumed */
*to = *from++; /* Note that the 'to' pointer is NOT incremented */
} while(--count > 0);

Compared to Duff's optimization:

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);
}
}

(for the life of me I can't figure out how to indent those code snippets properly here).

From which of the two is it easier to understand what the code snippet does, and which is easier to debug? To me, those are two important outcomes of elegant coding.

Re:Duff's Device (1)

StripedCow (776465) | about 7 months ago | (#46582705)

To me, elegance at code level means succinct and readable code. Optimizing for performance usually comes at a lower level of readability.

Therefore, first write the code in the most elegant way.

Then, write an optimizer that optimizes that code. Of course, the optimizer itself should be elegant, but it need not be efficient.

Re:Duff's Device (1)

gnasher719 (869701) | about 7 months ago | (#46582389)

If you call that "elegant", I wouldn't want to see your own code. I'd submit it to thedailywtf.com if it wasn't that old.

Re:Duff's Device (2)

Phoeniyx (2751919) | about 7 months ago | (#46582489)

There is nothing elegant about this. It's complicating something much more readable. Granted, elegance is related to simplicity, readability, AND efficiency - among others.. However, efficiency should not trump the other attributes - that's the job of the compiler. It's best not to confuse the roles of the two: the programmer and the compiler.

Re:Duff's Device (5, Insightful)

gweihir (88907) | about 7 months ago | (#46582519)

Fail. Elegant != Complicated.

This is a common fallacy which makes many programmers think they are great but they are really are abysmally bad. Code has to be readable! Here is something that gives the idea:

    There are two ways of constructing a software design: One way is to make it
    so simple that there are obviously no deficiencies, and the other way is to
    make it so complicated that there are no obvious deficiencies. The first
    method is far more difficult. --Tony Hoare

Most programmers considering themselves "good" fail this test and go for the second option.

Linux kernel (2)

Xouba (456926) | about 7 months ago | (#46582173)

The Linux Kernel is a fine example of public mammoth project with strict style guidelines, and ones that are quite elegant IMHO.

Re:Linux kernel (5, Insightful)

Anonymous Coward | about 7 months ago | (#46582201)

The common definition for elegant code is. "Anything not written by someone else."
In general code tends to be an ugly patchwork until you refactor it, introduces a couple of bugs, fixes the bugs and ends up in the starting position. The big change is that you now realize why the "ugly patches" were an elegant solution to the problem.

Or to phrase it differently; elegant code is code that has enough comments to explain why it isn't possible to make it simpler.

Re:Linux kernel (1)

Anonymous Coward | about 7 months ago | (#46582231)

The Linux kernel is a great example of how elegant code can really be when readability and maintainability are given importance. Incredibly complex, highly optimized, yet so laughably readable that anyone can dive in and make sense of it.

Re:Linux kernel (1)

MtHuurne (602934) | about 7 months ago | (#46582585)

Code quality in the Linux kernel varies a lot per individual driver or subsystem. Many interfaces are under-documented: you have to read the implementation code and make an educated guess at what the intended interface was. And a lot of the error handling paths contain bugs, since those are rarely exercised when testing manually.

The Linux kernel might seem elegant if you just read the code superficially. Once you start making changes and have to know exactly how it works, you'll see the problems that many parts of the kernel code have. While there is certainly a lot worse code out there, I wouldn't use the kernel as a shining example of elegant code.

There is one thing I learned from the Linux coding style though: avoiding typedefs and just writing "struct blah" in full helps make code accessible to new readers: the less indirections, the sooner you find what you're looking for. The same thing holds for avoiding typedef aliases for integer types and using macros sparingly.

Re:Linux kernel (-1)

Anonymous Coward | about 7 months ago | (#46582469)

The Linux Kernel is far far FAR from elegant. It's horrid. It's among the worst code I've ever seen.

Is this a request for optimal code design... (3, Insightful)

korbulon (2792438) | about 7 months ago | (#46582175)

or is the OP requesting us to hunt down a piece of code that fulfills his project specs (and does it elegantly, gosh darnit!)?

Is the OP's real name Tom Sawyer?

Re:Is this a request for optimal code design... (3, Insightful)

mwvdlee (775178) | about 7 months ago | (#46582251)

The request is oddly specific.
It might be more prudent to ask for particularly nice before- and after refactoring examples in general.

I love the elegance of object oriented parser frameworks (disclaimer; I've made several myself), but that elegance is rather in the model than the code.
Elegance purely in code I can only really remember seeing in small functions and snippets. Mostly elegance seems to be in the structure and interaction between functions or objects.

Re:Is this a request for optimal code design... (1)

Joce640k (829181) | about 7 months ago | (#46582377)

The request is oddly specific.

Yes. Very odd...

Almost like a code request.

The correct thing to do would be to find one then add a very sneaky flaw. Find out if all he really wanted was to "read" it.

Re:Is this a request for optimal code design... (1)

bertok (226922) | about 7 months ago | (#46582465)

It might be more prudent to ask for particularly nice before- and after refactoring examples in general.

Seconded!

I once saw a Java class with pages of complex multi-threaded code to update the horizontal offset of the ticker in a GUI. Not counting the usual minimum content of a class file, I replaced it with a single line along the lines of "return velocity * getCurrentTime();". So satisfying! 8)

Re:Is this a request for optimal code design... (2)

lxrslh (652069) | about 7 months ago | (#46582471)

or is the OP requesting us to hunt down a piece of code that fulfills his project specs (and does it elegantly, gosh darnit!)?

Is the OP's real name Tom Sawyer?

OP Here: I am a retired Assembler 360 programmer. I have no project needs or other reason for my specific example, which was merely an example of what I suspect/hope is an elegant program. I could be wrong about that. Feel free to discard your understandable cynicism.

Re:Is this a request for optimal code design... (0)

Anonymous Coward | about 7 months ago | (#46582491)

it was an example... the actual request is for any example of elegant code...

Re:Is this a request for optimal code design... (1)

Chrisq (894406) | about 7 months ago | (#46582645)

or is the OP requesting us to hunt down a piece of code that fulfills his project specs (and does it elegantly, gosh darnit!)?

Is the OP's real name Tom Sawyer?

Do we have to pay to join in?

Writing Code is like Explaining Things (2)

DpEpsilon (2538466) | about 7 months ago | (#46582179)

Writing code can be like explaining something or teaching. You can give an explanation that is logically correct but difficult for a human to follow. Programmers tend to neglect this in their code because it can be difficult to construct something that reads well and even if it doesn't read well, it can still be executed by a computer.

I like to think that if code is 'elegant', it can be read well after at most after brief explanation of how the algorithm is supposed to work, because code alone is sometimes difficult to interpret.

Re:Writing Code is like Explaining Things (1)

DpEpsilon (2538466) | about 7 months ago | (#46582181)

I wish I had something I think is elegant but most code I try to read tends to be a bit of a grind.

Knuth's TeX and Metafont (5, Insightful)

bre_dnd (686663) | about 7 months ago | (#46582187)

Interesting code, serves a real purpose, solves a real problem.

A lot of "real world" code out there has not been designed, it has grown, and that's part of the problem. Think of cities that have grown (London?) rather than be designed according to some grand master plan (New York?) and major reengineering exercises need to be undertaken (in the case of London, as one example, sewage pipes were fitted in underneath). Inevitably there's some shortcuts taken or real reasons that you could not quite do the best job.

Codewise, the oldest running code probably lives in the banking system or the telephony system. Typically code that has grown over time and can't just be shut down for an upgrade -- "what do you mean close the bank for a week?". Now whatever code runs there has been kept running (bodged?) for decades, but pretty it probably isn't.

Re:Knuth's TeX and Metafont (1)

korbulon (2792438) | about 7 months ago | (#46582449)

In a way these codebases evolve a lot like DNA, and for pretty much the same reasons. So you end up with a lot of patches and hacks, as well as code sediment: stuff that's basically obsolete but would be too painful to remove. Something about the dirty and relentless nature of reality.

Re:Knuth's TeX and Metafont (1)

lxrslh (652069) | about 7 months ago | (#46582513)

Interesting code, serves a real purpose, solves a real problem.

.....

Codewise, the oldest running code probably lives in the banking system or the telephony system. Typically code that has grown over time and can't just be shut down for an upgrade -- "what do you mean close the bank for a week?". Now whatever code runs there has been kept running (bodged?) for decades, but pretty it probably isn't.

It did occur to me that the code running an AT&T 5ESS switch or its current equivalent "should" have those attributes we would hope for, but it might also have become massively over-grown with cruft, not to mention being too large to be grasped by a mere mortal.

Re:Knuth's TeX and Metafont (0)

Anonymous Coward | about 7 months ago | (#46582699)

Did you just claim that New York is more elegant than London?

I almost wish I had an art degree so that I would find it worthy of my time to write an essay to argue against that.

I write spaghetti code (4, Insightful)

Big Hairy Ian (1155547) | about 7 months ago | (#46582191)

Just like everyone else

Re:I write spaghetti code (0)

Anonymous Coward | about 7 months ago | (#46582331)

This. Even true for those who would never admit.

Original MacPaint and QuickDraw code (1)

Anonymous Coward | about 7 months ago | (#46582195)

http://www.computerhistory.org/atchm/macpaint-and-quickdraw-source-code/

GPS? Are you kidding? (1)

Anonymous Coward | about 7 months ago | (#46582199)

The GPS code I've seen was horrible and I worked for one of the major GPS players for several years.
Originally written in FORTRAN and later automatically converted to C. Utter crap basically.

The mathematics behind GPS is really interesting and quite involved. The implementations are crap.

For another example of a well written large project, try gcc.

Re:GPS? Are you kidding? (4, Informative)

jonwil (467024) | about 7 months ago | (#46582587)

As someone who has a copyright assignment on file with the FSF for GCC and actually tried to write an implementation of the Visual C++ __declspec(thread) keyword for GCC-on-windows (i.e. proper OS-provided thread-local-storage support) and got lost somewhere deep in the code that actually converts the intermediate representation into assembler (I needed to do stuff to it so it would correctly access the thread-local-storage data when an access to a thread local variable was made) I question your statement that GCC is well-written, elegant or easy to understand...

Re:GPS? Are you kidding? (3, Insightful)

arglebargle_xiv (2212710) | about 7 months ago | (#46582609)

The GPS code I've seen was horrible and I worked for one of the major GPS players for several years. Originally written in FORTRAN and later automatically converted to C. Utter crap basically. The mathematics behind GPS is really interesting and quite involved. The implementations are crap.

Saved me from writing the same thing. The GPS code I've seen, written by engineers and not programmers, was an incredibly hacked-together, barely-functional set of kludges to implement a lot of very elegant mathematics.

For another example of a well written large project, try gcc.

Another example that's at least as elegant as gcc is OpenSSL [peereboom.us] .

Re:GCC? Are you kidding? (1)

u38cg (607297) | about 7 months ago | (#46582713)

See subject...........

Code I consider 'elegant'. (5, Insightful)

Asteconn (2468672) | about 7 months ago | (#46582205)

I consider code elegant if I can read it and understand it on the first try, personally.

Complete Spectrum Rom Disassembly (1)

Anonymous Coward | about 7 months ago | (#46582211)

As a teenager I had a copy of 'The Complete Spectrum Rom Disassembly' which, as you'd expect, was commented Z80A code for the Sinclair ZX Spectrum. It was a fascinating example of elegant and optimised code. Shame I lost the book (and it seems to be out of print).

Re:Complete Spectrum Rom Disassembly (4, Informative)

Anonymous Coward | about 7 months ago | (#46582221)

ftp://www.worldofspectrum.org/pub/spectrum/books/CompleteSpectrumROMDisassemblyThe.pdf

Re:Complete Spectrum Rom Disassembly (0)

Anonymous Coward | about 7 months ago | (#46582241)

You mean this, found at the top of a Google search: ftp://www.worldofspectrum.org/pub/spectrum/books/CompleteSpectrumROMDisassemblyThe.pdf

Re:Complete Spectrum Rom Disassembly (0)

Anonymous Coward | about 7 months ago | (#46582301)

Yep - exactly that. Not my original copy with my own notes in it though :-(

Re:Complete Spectrum Rom Disassembly (1)

Joce640k (829181) | about 7 months ago | (#46582387)

I don't recall it being particularly "elegant"....

Re:Complete Spectrum Rom Disassembly (0)

Anonymous Coward | about 7 months ago | (#46582577)

Me too, this was my first computer book and I read it end to end. When I was through I could machine code in hex. Oh the fond memories.

Elegance only exists in textbooks (5, Insightful)

petes_PoV (912422) | about 7 months ago | (#46582225)

Most code will not fall into the "elegant" category. The reason is that real-life software has to deal with exceptions, language crocks, patches/modifications and bug-fixes. It is also subject to the constraints, limitations and ugliness of whatever it has to run on and interface with (no program is an island entire of itself Every program is a piece of the continent, A part of the main() [ John Dunne] ).

Therefore the only place you'll find elegant code is in a book about algorithms, where the idea is presented in isolation and not subject to the practicalities of real-world environments

Re:Elegance only exists in textbooks (1)

twdorris (29395) | about 7 months ago | (#46582349)

Most code will not fall into the "elegant" category. The reason is that real-life software has to deal with exceptions, language crocks, patches/modifications and bug-fixes.

And those damn users. I can write what I (and seemingly others) consider "elegant" code. But that's usually only possible down in the bowels of a microprocessor where you have known constraints and no meat bags randomly typing shit at you that you have to parse and decipher and then present a myriad of exception messages back to, etc., etc.

Re:Elegance only exists in textbooks (1)

korbulon (2792438) | about 7 months ago | (#46582423)

"The program isn't debugged until the last user is dead."

Re:Elegance only exists in textbooks (1)

StripedCow (776465) | about 7 months ago | (#46582383)

Yes, but try to explain that to a manager, or to a user!

Re:Elegance only exists in textbooks (4, Insightful)

JaredOfEuropa (526365) | about 7 months ago | (#46582463)

At the code level, elegance means readability and ease of understanding what is being done, it's not about the code lines being pretty or poetic. If you have to use a crappy workaround or do some non-obvious API calls because the API you code against is crap, you add comments to explain what you're doing, and try to contain each "hack" to one function or method (rather than designing your objects around them). That way, you can keep your code readable and understandable, and elegant.

At the data / object model level, there are good real-world examples of elegant coding. At this level, elegance affords the ability to make smaller changes or bug fixes without having to resort to major refactoring or adding a lot of messy code in many different places in your program. At this level, elegance also works to isolate the overall program from ugly interfaces / APIs.

Elegant code is... (1, Insightful)

Anonymous Coward | about 7 months ago | (#46582233)

To me elegant code is code that has constant execution time, is readable at a glance and accomplishes it's function with little to no side effects. The last part seems to be almost impossible for most modern programmers, understandable when they never drop any farther than an abstraction on top of an abstraction.

Re:Elegant code is... (1)

ziggystarsky (3586525) | about 7 months ago | (#46582435)

If you say "has constant execution time", you mean it's not allowed to use functions and other control flow constructs, right? Because only then you might get close to "constant execution time", when also abstracting away the rest of the system the code is running on.

Most non-trivial code has non-constant execution time. And IMHO only non-trivial code can receive the tag "elegant", for if the task is trivial, there's no room for doing anything interesting.

IMHO, Haskell is a language that enables writing very elegant code. But estimating the execution time of a Haskell program is extremely difficult, not only because it has a lazy execution model.

But we can agree on the "no side effects" thing, better calling it referential transparency. Call the same code with the same arguments to obtain the same result every time.

Mutually exclusive (1)

mansie (1601275) | about 7 months ago | (#46582267)

I find 'elegant code' and 'finished project' to be mutually exclusive.

Comment your damn code (0)

Anonymous Coward | about 7 months ago | (#46582281)

Seriously. If you comment well (things that others will understand easily, not just ways to remind yourself of what the code does) it doesn't matter how "elegant" the code is.

Also, sometimes "elegant" code is worse performance wise. It might be considered more elegant to use a for loop, but faster to merely paste the results of the loop directly into the program so it doesn't have to run the loop every time it runs. (Of course, this does increase the size of the program though, so there are always trade-offs.)

To summarize - Comment, comment well, and write efficient code. The end result is what matters? not the elegance of the code, and if someone does have to continue your project, the comments will make it possible.

Re:Comment your damn code (0)

famebait (450028) | about 7 months ago | (#46582297)

All comments are lies.
Write readable *code*

Re:Comment your damn code (1)

mwvdlee (775178) | about 7 months ago | (#46582339)

Agreed. I'll allow javadoc-like comments that help to document a public interface, but if you write comments to explain an algorithm, you're probably making a mistake.

Re:Comment your damn code (5, Insightful)

bre_dnd (686663) | about 7 months ago | (#46582439)

I respectfully disagree.

I've written code that computes a CRC. It's been done before. The naive/reference implementation works but isn't fast. The optimized version, and how the heck that came about from the naive implementation to those magic few lines of code, looks nothing like it. Now rather than you glazing over "what the?", I figure that *if* you have to overhaul this code, you'd like to know *why* this code looks like it does. So I explained why. In the code. In a full page of comments.

Re:Comment your damn code (1)

famebait (450028) | about 7 months ago | (#46582589)

I was intentionally overstating it a bit.

There are of course cases where comments are warranted, and properly justified optimizations may be just such a case. The others also usually fall under the broader umbrella of "exceptions" to how things might normaly be done. Just don't use it as an excuse to make the code less clear than it could be given the perfomance constraints, and beware of premature optimisation, which is a prime cause of brittle and unreadable code, with frequently no real benefit to offset the cost.
And always consider if you could say some of it with code too.

As a general rule, though, I still think it is wise to keep in mind that since the comment is not executed, there is no guarantee that it reamains correct, if ever it was.
I sometimes make a hobby out of trying to find at least one error in every comment I see. It doesn't always pan out, but tre percentagewhere it does is both staggering and frightening - I warmly reccommend the practice to everyone.

Elegence? (2)

Wowsers (1151731) | about 7 months ago | (#46582289)

I don't know if it counts as "elegant code", but I find it really useful that code is fully commented. Speaking for myself, it's useful to come back months or years after originally writing code, and knowing why I wrote such a routine the way I did, and what it does, making changes easier and quicker.

Re:Elegence? (2)

pr0nbot (313417) | about 7 months ago | (#46582437)

My rule of thumb is, "if the first implementation of this didn't work, and I had to change it, then it needs comments" on the principle that if the "obvious" solution turns out not to work, then the problem is not as obvious as I'd thought.

The original (1)

Mantrid42 (972953) | about 7 months ago | (#46582299)

Mel.

Ideals vs Reality (1)

MakubeX (1708572) | about 7 months ago | (#46582307)

Ideally, with the OP satellite example, you think one loop would be gathering a list of satellites objects (or structs) and then in a different loop there would calculations for the various attributes of each satellite, ideally with descriptive variable names being initially declared 'double longitude =0" and brief comments above for loops such as "//Determines individual satellites per unique GPS frequency However, I've come to accept that people are just different, people are going to code in the manner they are accustomed to, with very few comments. I've come to accept that reading others people's code is just going to suck. If I know the intent of the class and the variables/functions are self-descriptive, I'll be fine. If some names their variables "a1" "a2" "b1", and they are all different data types... then I'm going to have a bad time. But again, I've accepted this. What I can't accept is people coding inefficiently. I'm not even worried about space complexity (within reason), I'm talking about run-time complexity. If you have 3 inner for loops for something that could be done in linear time, I'm going to be sad. If I fix it and try to use this chance as a teaching moment (we all should want to be better) and you shrug and tell me that correctness is all that matters... then I'll stab you. The best algorithm isn't always obvious, and while I don't expect many of us to employ dynamic programming concepts... if we can't get people to agree on a coding style (since that is preference), the least we can do is agree that we don't want our code to completely suck. I mean if you have a O(n^3) subroutine, you should ask yourself if that is really the best you can do, at least think about it. /rant over

The pinnacle of elegant code (5, Funny)

igomaniac (409731) | about 7 months ago | (#46582313)

Minimise state (5, Interesting)

famebait (450028) | about 7 months ago | (#46582327)

You always have to keep in mind that code will be changed by serveal peopale, and your 'elegant' intention may not be understood or followed through by the next guy. So go for simple rules of thumb that not only keep your code readable and clear, but can accommodate future change while ramaining so.

My number one rule for keeping code both readable and robust is this: Reduce state.

I don't mean everything needs to be purely functional, but consider state a general liability to both correctness, readability, testability and maintainability. Less is more..
* Whatever state you have should be focused and serve to explain/model the actual problem domain, not just 'keep stuff for later'.
* Keep state as local as possible - most code is litered with instance variables that should have been locals and params.
* Just because an object _can_ bundle state with its functions doesn't mean it _should_.
* If it can be done in a static method and still make sense, do so.

Re:Minimise state (1)

StripedCow (776465) | about 7 months ago | (#46582535)

In general, the best you can do in terms of simplicity is to write code that computes the result (e.g., the "current" observable state of an interactive program) from scratch at every instant. However, this would make the code needlessly slow. You are then forced to cache stuff, etc., and things become ugly...

Re:Minimise state (0)

Anonymous Coward | about 7 months ago | (#46582575)

Reduce state.

Amen! But its changing state that matters.

Recently, I've found all my objects falling into one of two categories:

  1. Immutable after construction
  2. Causes problems

Re:Minimise state (0)

Anonymous Coward | about 7 months ago | (#46582635)

s/state/invariants/g

IMHO (1)

KinkyClown (574788) | about 7 months ago | (#46582335)

There is only one programming language that actually makes the code really nice to read; hence making the code elegant: it's called Whitespace (http://compsoc.dur.ac.uk/whitespace/)

It's always elegant at first (3, Insightful)

GrahamCox (741991) | about 7 months ago | (#46582391)

New code is always elegant at first. But invariably it doesn't work properly, and by the time you have got it to work, it's no longer elegant.

Re:It's always elegant at first (1)

Lumpy (12016) | about 7 months ago | (#46582539)

This depends. if there is no idiot manager breathing down the neck and allows the programmer to take the needed time to test, rewrite, test, rewrite... then the output is good code.

Loser managers that cut in half or worse in third the time it takes to actually write good code cause most of the horrid crap you see out there. I guarantee that everything written by Bioware is an unholy mess. The sheer number of bugs I see in every one of their releases means they dont care about good code, they care about the fact it compiled.

Re:It's always elegant at first (1)

asylumx (881307) | about 7 months ago | (#46582669)

allows the programmer to take the needed time to test, rewrite, test, rewrite...

Real developers ship. You are working for a business; you are not doing an academic study.

The sheer number of bugs I see in every one of their releases means they dont[sic] care about good code

And here we have another problem. You think that good or elegant code means bug-free. It doesn't. There's lots of pretty code out there that doesn't do what it's supposed to do.

Elegant code is like a great teacher. (5, Insightful)

Balinares (316703) | about 7 months ago | (#46582393)

Maybe you've been lucky enough to have that once in a lifetime great teacher. The kind of teacher who somehow explains stuff in such a way that everything makes sense to you; things follow logically from one another and it all seems obvious when he explains it. (And you may not even realize it until he falls sick and the substitute trying to explain the exact same stuff leaves you confused and baffled.)

Elegant code has the same property of apparent obviousness. You read it and just nod because it makes sense and flows logically. There isn't one single way to achieve this, of course. It's not about functional vs. imperative vs. object oriented, but how you employ them for clarity.

Needless to say, such clarity is a very hard property to achieve, and a lifetime of experience will only let you approach it asymptotically. It's still worth the attempt, though.

Re:Elegant code is like a great teacher. (1)

Michele Filannino (3593573) | about 7 months ago | (#46582479)

Well said!

Teams can't do elegant code. (0)

Anonymous Coward | about 7 months ago | (#46582443)

All of my code is elegant and bug-free, but proprietary, so I can't share it with you.

Isn't it obvious? (0)

Anonymous Coward | about 7 months ago | (#46582457)

Malbolge.

Modula-2 first compiler source code (0)

Anonymous Coward | about 7 months ago | (#46582459)

Modula-2 first compiler source code: http://www.cfbsoftware.com/modula2/

Most python code is elegant (1)

Greg Allen (3008951) | about 7 months ago | (#46582485)

but in the pictured code, it should be def are_connected(...): return self.filter(...) or self.filter(...)

As little as possible (0)

Anonymous Coward | about 7 months ago | (#46582505)

Elegant code gets the job done with as little code as possible, also preceding individual lines to do as little as possible.

In general, the more your code does the harder it is to understand. So doing less leads to fewer bugs.

Re:As little as possible (0)

Anonymous Coward | about 7 months ago | (#46582723)

So elegant code is APL? I don't think so...

I'm a style prude (2)

CockMonster (886033) | about 7 months ago | (#46582507)

The first thing I look at when looking at interview candidates code is their style. I don't care particularly if it's not the same as mine, but I do care if there's no consistency to their own style. I'm talking about hurried formatting, trying to squeeze everything into the least number of lines, mixed naming conventions, bad spelling in comments, even down to things like inconsistent spacing. Maybe I'm a prude but if I'm going to be looking at this person's coding output all day it better at least be readable. That Linux managed to maintain a consistent coding style with so many contributors is an admirable feat. As for beautiful algorithms, I quite like the simplicity of Dijkstra's shortest path.

Code that explains itself (1)

Karmashock (2415832) | about 7 months ago | (#46582515)

Elegant code is code you can look at and understand what its doing and then audit easily.

That is the real point of elegant code. You ACTUALLY know precisely what it is doing. No guess work. The best code can be understood with a casual glance and any mistake in the code stands out brightly because the pattern and elegance of the code is beautiful in its way. And any imperfection is ugly.

Elegant != performant (0)

Anonymous Coward | about 7 months ago | (#46582521)

Why should embedded code be elegant? It isn't written for people.

Sieve of Eratosthenes (in Clojure) (0)

Anonymous Coward | about 7 months ago | (#46582527)

(defn sieve [s]
    (cons (first s)
                (lazy-seq (sieve (filter #(not= 0 (mod % (first s)))
                                                                  (rest s))))))

Elegant code is.... (2)

Lumpy (12016) | about 7 months ago | (#46582531)

Code that does the job in the simplest possible way. This means that the writer went through several prototypes before they settled on the code they liked instead of the normal..."it works SHIP IT!"

No obfuscated crap, it's clear simple and concise.

Paint .NET (1)

aojensen (1503269) | about 7 months ago | (#46582583)

I find the source code for Paint .NET to be a good example of well written code (at least for a GUI driven application in a modern OO language).

language of the heart most useful digits (0)

Anonymous Coward | about 7 months ago | (#46582591)

thanks again moms...

My personal "law" (3, Insightful)

acroyear (5882) | about 7 months ago | (#46582623)

Code written to do one thing is inherently elegant.

No code ends up ever having to do one thing.

The job of requirements gathering is to determine what are the constants and what are the variables. In the case of, say, GPS, the constants should be the protocol of the satellites, the max and min # of sat's that can be found at any given time, the grid representation of the earth, and the system clocks.

Nice and easy, right?

Now change all of those to a variable: you have satellites speaking to you in different protocols based on their age. You end up with only one sat connection so no triangulation due to mountain or building blockage. The grid representation of the earth is inherently distorted at the north and south extremes (and whenever you're above 5,000 feet). Oh, and the you forgot to time-distort your own clock for the rotation of the earth, so a tiny offset is being caused by General Relativity.

Suddenly code that was nice and simple is now full of ifs and switch loops and complex adjustments and bits of guess work and comments that say "oh, well, we'll just have to ignore that last part...but we'll only be off by 30 feet or so".

The first bug in software happens when something that was presumed in the requirements to be a constant has to be changed into a variable. Every bug that follows is a result of trying to fix that first bug.

Because of that requirements problem, no working production code can ever be elegant.

It exists, but you can't see it. (1)

140Mandak262Jamuna (970587) | about 7 months ago | (#46582629)

There is an instance of elegant code that solves a real life engineering problem that beats the competition by orders of magnitude in speed, resource usage, robustness and accuracy.

Unfortunately my employer thinks it belongs to the corporation, because they paid me something they call salary to me when I wrote it. They would not let me show it to you all. But this much I can tell you. The key to writing such wonderfully elegant code is to avoid exaggeration, stay away from bragging, and most importantly eschew snark.

Real-world code isn't elegant (1)

Anonymous Coward | about 7 months ago | (#46582649)

Having written a lot of code, the key point is that real-world code handles exceptional conditions, platform bugs, hardware weirdness, language ad-hockery, third-party libraries and their quirks, and so on. Any code useful enough to do anything worthwhile isn't going to be elegant. Code is ugly because it's an accretion of handling weird and exceptional conditions. Plus there's all the strange logic you have to add for edge cases and weird conditions in your own business logic - do this 99% of the time, except when some weird thing happens, then do something else. Throw in multi-threading, and you add another layer of checking to see if objects are null. I think most Android code is "if this object is not null, do something" to deal with its insanity-inducing asynchronous nature. Or setting and checking flags so one asynchronous bit of code can flag a condition another method has to deal with when it is called asynchronously later. By the time you get through writing something that really works, it's a nightmare. I often can't figure out what my own code is supposed to do. I write a lot of comments that explain why code works the way it does.

Read a LISP textbook or something to see elegant code. Most elegant code is far removed from the real world.

Of course (0)

Anonymous Coward | about 7 months ago | (#46582651)

10 PRINT "HELLO WORLD"
GOTO 10

Load More Comments
Slashdot Login

Need an Account?

Forgot your password?