Want to read Slashdot from your mobile device? Point it at m.slashdot.org and keep reading!

 



Forgot your password?
typodupeerror
×
Programming

Ask Slashdot: What Do You Consider Elegant Code? 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?"
This discussion has been archived. No new comments can be posted.

Ask Slashdot: What Do You Consider Elegant Code?

Comments Filter:
  • by korbulon ( 2792438 ) on Wednesday March 26, 2014 @05:13AM (#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?

  • by bre_dnd ( 686663 ) on Wednesday March 26, 2014 @05:18AM (#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.

  • by Big Hairy Ian ( 1155547 ) on Wednesday March 26, 2014 @05:20AM (#46582191)
    Just like everyone else
  • Re:Linux kernel (Score:5, Insightful)

    by Anonymous Coward on Wednesday March 26, 2014 @05:21AM (#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.

  • by Asteconn ( 2468672 ) on Wednesday March 26, 2014 @05:22AM (#46582205)
    I consider code elegant if I can read it and understand it on the first try, personally.
  • by petes_PoV ( 912422 ) on Wednesday March 26, 2014 @05:26AM (#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

  • Elegant code is... (Score:1, Insightful)

    by Anonymous Coward on Wednesday March 26, 2014 @05:27AM (#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.

  • by mwvdlee ( 775178 ) on Wednesday March 26, 2014 @05:31AM (#46582251) Homepage

    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.

  • by Viol8 ( 599362 ) on Wednesday March 26, 2014 @05:51AM (#46582321) Homepage

    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:Duff's Device (Score:2, Insightful)

    by Anonymous Coward on Wednesday March 26, 2014 @05:53AM (#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.

  • by GrahamCox ( 741991 ) on Wednesday March 26, 2014 @06:15AM (#46582391) Homepage
    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.
  • by Balinares ( 316703 ) on Wednesday March 26, 2014 @06:16AM (#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.

  • by bre_dnd ( 686663 ) on Wednesday March 26, 2014 @06:26AM (#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.

  • by JaredOfEuropa ( 526365 ) on Wednesday March 26, 2014 @06:32AM (#46582463) Journal
    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.
  • Re:Duff's Device (Score:5, Insightful)

    by gweihir ( 88907 ) on Wednesday March 26, 2014 @06:50AM (#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.

  • Re:Duff's Device (Score:2, Insightful)

    by Anonymous Coward on Wednesday March 26, 2014 @07:07AM (#46582573)

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

  • by arglebargle_xiv ( 2212710 ) on Wednesday March 26, 2014 @07:16AM (#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].

  • My personal "law" (Score:4, Insightful)

    by acroyear ( 5882 ) <jws-slashdot@javaclientcookbook.net> on Wednesday March 26, 2014 @07:21AM (#46582623) Homepage Journal

    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.

  • Re:Duff's Device (Score:5, Insightful)

    by BasilBrush ( 643681 ) on Wednesday March 26, 2014 @07:42AM (#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.

  • Re:Duff's Device (Score:5, Insightful)

    by Viol8 ( 599362 ) on Wednesday March 26, 2014 @08:07AM (#46582839) Homepage

    Wish I had mod points. In seems to be a badge of honour for some coders to make their code as obfuscated as possible. I'm not sure who they're trying to impress but it sure as hell isn't the poor maintenance coders a few years down the line.

  • Re:Linux kernel (Score:5, Insightful)

    by gmack ( 197796 ) <gmack@@@innerfire...net> on Wednesday March 26, 2014 @08:14AM (#46582877) Homepage Journal

    I strongly disagree with this. While I admit that elegant code can have ugly portions refactoring will often be an improvement but the trick is to learn when refactoring will help and when it will be a waste of time. The worst programmers I know are the ones who say that "I don't have time to go back through my code". I have cleaned projects where the original coder did the same thing three different times or reinvented the wheel when there were better libraries. In fact, I have been also guilty of this and even in my own projects I have come across places where the requirements changed out from under me mid project or I simply see better ways of doing things as I gain experience.

    Elegant code:
    1 Handles errors gracefully
    2. Only reinvents the wheel when there is a measurable benefit in doing so.
    3. Has consistent naming conventions.
    4. Has comments around ugly code explaining why it is ugly.
    5. Compiles (or runs if interpreted) without warnings.

  • by gstoddart ( 321705 ) on Wednesday March 26, 2014 @08:48AM (#46583101) Homepage

    At the code level, elegance means readability and ease of understanding what is being done

    And maintainability. People often forget that one.

    I once had a co-worker who wrote a component he thought was elegant, because it had a nice lovely modelling and abstraction and matched how he thought the problem should be solved.

    The problem was, his solution was rigid, brittle, and kinda wrong. The things he turned into elegant objects didn't behave that way, and the things he didn't were the actual meat of the problem.

    Every time he had to fix a bug or add a change, he spent time trying to understand how his code worked, where he'd have to make changes, and then bitching about how the change violated his nice 'elegant' code.

    On another project, he was writing a component which consumed stuff from a component I and another co-worker had built (they were built concurrently).

    By the time we were ready to do integration testing, his nice elegant code had been built on the assumption we would implement all of the semantics for his part (which we couldn't possibly have known). He had structured his code in such a way as to be 'elegant' as long as the library he was using had behaved in a way that nobody would have modeled unless it had been written to precisely implement his semantics.

    And, again, his 'elegant' code was rigid, brittle, and wrong and had to be significantly changed to work with an interface he knew about in advance, because we'd agreed upon it before writing both pieces.

    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.

    And if you start with a terrible object model and then write elegant code around that terrible object model, you get the exact opposite.

    And then don't get me started on trying to make your 'elegant' code go faster because you've created more work with how you've structured your code.

    Once had a coder tell me we shouldn't optimize because computers are Really Fast and we probably can't do any better. Then I threw away a large chunk of his code and replaced it with something which wasn't doing silly things, and we got a giant speedup.

    Some people get so damned focused on writing what they think is 'elegant' code that it is neither useful to the task, well written, nor maintainable.

  • Re:Linux kernel (Score:5, Insightful)

    by Greyfox ( 87712 ) on Wednesday March 26, 2014 @09:30AM (#46583397) Homepage Journal
    Ooh, I like this list! My usual MO is to (try to) write reusable libraries for most of my project and glue the library code together with a main program that does as little extra processing as possible on the library objects. If I'm writing a library, I like to add the extra criteria that it to be easy for a programmer to pick up and use. The actual library code can be absolutely hideous but if it gets the job done and the interface is easy to use I'm not going to complain about it.

    I've been coding for the fun of it again in my spare time, and have a fair bit of code up on GitHub [github.com] now. I've only been seriously using C++ for the last couple of years, and you can see a bit of a progression from my early code (fr_demo) to more recent code like the data library and resumetron. Stuff like cppxml which I use frequently gets updated more often than the old demo code.

    I particularly like my factories. I have a relative going through a CS program right now and he's had some questions on a couple of his assignments and got a look at a piece of code with data readers provided by his professors. They always look like C code that was written 15 years ago. I know this because I also very recently was digging through some C code that was written 15 years ago. I like to think they're doing that on purpose, but they're not. So his introduction to design patterns could have been a nice clean data factory that requires three lines of code to write, but instead it's the singleton pattern, which every design review board on the planet will now reject immediately after the word leaves your mouth, whether it's actually justifiable or not.

    One of these days real soon now I'm going to need to go back and replace all my std::string throws with std::logic_errors or other appropriate std::exception errors, and I'm kicking around the idea of building up a simple rest server around my old socket server code one of these days. That sounds like fun to me!

  • by Anonymous Coward on Wednesday March 26, 2014 @09:44AM (#46583495)

    ...I'm not sure who they're trying to impress but it sure as hell isn't the poor maintenance coders a few years down the line.

    I write simple code. I am primarily a C/C++ coder and in the "Obfuscated 'C' contest", I wouldn't even make the cut.

    My code was described as very "simple" in a patronizing tone. My code works, has very very few bugs, it is done on time, and looking back at it after year, you can see exactly what it's doing - even without reading the many many comments.

    I was treated as the dullard of the team. It's like if you don't use all the tricks and shortcuts, somehow you don't really know the language that you are programming. And if your code is too easy to understand, then you are not as smart or good.

    I started in this business in 1992 and I have never been in a shop that did not have the attitude.

  • Re:Duff's Device (Score:4, Insightful)

    by Anonymous Coward on Wednesday March 26, 2014 @09:57AM (#46583589)

    Many moons ago I refactored a complex function by a much respected 'Master Programmer'. "It's going to take you a good few years before you're at his level", they told me. After I had finished refactoring his function, a page and a half of heavily nested if/else statements had boiled down to a single CASE statement, 4 lines long, doing the exact same thing that his original code did.

    In my book, this guy wasn't a Master Programmer at all. He overcomplicated things. His code was unmaintainable to anyone but him - and evidently he had a pretty hard job maintaining his own code.

    Elegant code is code that correctly solves a particular problem in the simplest possible way. Bonus points if minimal CPU/Memory resources are used to achieve that.

  • Re:Duff's Device (Score:4, Insightful)

    by 3dr ( 169908 ) on Wednesday March 26, 2014 @03:25PM (#46586877)
    It's just optimizers all the way down.

Old programmers never die, they just hit account block limit.

Working...