Slashdot Mirror


Ask Slashdot: What Do You Consider Elegant Code?

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

68 of 373 comments (clear)

  1. Duff's Device by smittyoneeach · · Score: 4, Informative
    --
    Get thee glass eyes, and, like a scurvy politician, seem to see things thou dost not.--King Lear
    1. Re:Duff's Device by Anonymous Coward · · Score: 3, Informative

      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

    2. Re:Duff's Device by DpEpsilon · · Score: 5, Funny

      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.

    3. Re:Duff's Device by Anonymous Coward · · Score: 2, Insightful

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

    4. Re:Duff's Device by Phoeniyx · · Score: 2

      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.

    5. Re:Duff's Device by gweihir · · Score: 5, Insightful

      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.

      --
      Most ACs are not even worth the keystrokes to insult them. Be generically insulted by this and ignored otherwise.
    6. Re:Duff's Device by DpEpsilon · · Score: 2

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

    7. Re:Duff's Device by Anonymous Coward · · Score: 2, Insightful

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

    8. Re:Duff's Device by BasilBrush · · Score: 4, Insightful

      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.

    9. Re:Duff's Device by Viol8 · · Score: 5, Insightful

      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.

    10. Re:Duff's Device by Anonymous Coward · · Score: 4, Insightful

      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.

    11. Re:Duff's Device by jythie · · Score: 2

      yeah, programming would probably benefit from people stopping and asking 'if I did not already know the context and answer, would this piece of code still make sense?', which given how often people have trouble reading their own stuff from a few years ago, the answer is often 'no'.

    12. Re:Duff's Device by 3dr · · Score: 3, Insightful

      It's just optimizers all the way down.

    13. Re:Duff's Device by DpEpsilon · · Score: 2

      Fair Enough. I kinda went for the rhetorical interpretation of "Is this a joke?", but I can see now that it didn't warrant a "woosh".

  2. Linux kernel by Xouba · · Score: 2

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

    1. Re:Linux kernel by Anonymous Coward · · Score: 5, Insightful

      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.

    2. Re:Linux kernel by gmack · · Score: 5, Insightful

      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.

    3. Re:Linux kernel by Greyfox · · Score: 4, Insightful
      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 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!

      --

      I'm trying to teach myself to set people on fire with my mind... Is it hot in here?

    4. Re:Linux kernel by gmack · · Score: 2

      1 Handles errors gracefully.

      This statement always hits me as mind numbingly stupid. In general try / catch and other error managing statements are for the lazy that don't want to understand the environment and inputs well enough to write the proper code to manage them. You want rock solid code that will last for years, eliminate the errors, don't "handle them gracefully". The only exception to this rule should be when the native environment forces it upon you or there is a lack of some proper check "doesThisReallyExist()".

      By errors I meant where paths and files don't exist, the user or external software sends bad info or someone runs or the machine runs out of resources. Case in point: someone edited one of our databases in a place I used to work and some software crashed hard when it grabbed a NULL value from the database leaving me to check the core dump to discover the problem.

      2. Only reinvents the wheel when there is a measurable benefit in doing so..

      I learn more reinventing the wheel and there is no substitute to working with code you are sure of and know how it's going to perform.

      I agree with the rest.

      I can see wanting to learn.. I can't see duplicating system libraries in a project. Some libraries (Libc in particular) have whole groups of programmers who are rather good at squeezing every last drop of speed out of the implementation, there are also things such as leap year handling that look simple but end up being harder than they look.

    5. Re:Linux kernel by TsuruchiBrian · · Score: 2

      You want rock solid code that will last for years, eliminate the errors, don't "handle them gracefully".

      Good luck writing code that eliminates the possibility that a read on a filehandle produces an error, so you no longer have to handle errors at all.

      I learn more reinventing the wheel and there is no substitute to working with code you are sure of and know how it's going to perform.

      It's great to learn, but you shouldn't be putting your homework problems into production software.

      There is a substitute for using only your own code that you are "sure of how it's going to perform". It's called using a good framework and libraries. If you aren't going to trust any 3rd party code, why not write your own compiler and kernel too? It pretty ridiculous to write code in a way that assumes only you yourself can write good code in 2014.

  3. Is this a request for optimal code design... by korbulon · · Score: 3, Insightful

    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?

    1. Re:Is this a request for optimal code design... by mwvdlee · · Score: 3, Insightful

      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.

      --
      Slashdot social media options: AIM, ICQ, Yahoo, Jabber and Mobile Text. Why no MySpace?
    2. Re:Is this a request for optimal code design... by lxrslh · · Score: 2

      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.

    3. Re:Is this a request for optimal code design... by DutchUncle · · Score: 2

      And you didn't post IBM Assembler macro language?

      The BAL Macro language could do things that C++ template functions can't. You could test *all* of the attributes of a parameter, from datatype through number of characters in the name, and vary the generated code accordingly - amazingly powerful levels of abstraction when used properly.

  4. Writing Code is like Explaining Things by DpEpsilon · · Score: 2

    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.

  5. Knuth's TeX and Metafont by bre_dnd · · Score: 5, Insightful
    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.

    1. Re:Knuth's TeX and Metafont by bre_dnd · · Score: 2
      I live in the UK, about an hour away from London. I have been to New York, but only once.

      London has existed for over a thousand years. It has just grown organically. All recent services (such luxuries as underground, trains, ringroads, mains water, electricity, sewers, communication lines) have been retrofitted on that base -- and it shows. The roads are the wrong size for the amount of traffic -- trains clash and are overfull, high rise offices are planned but foundations have to carefully avoid all the tunneling below.

      New York, in it's current form, is a lot younger than that. A lot of the concepts "we might want sewers" / electricity / rail, to some extend, could be taken into account when the city grid was being laid out. It's a lot easier to build sewers / underground trains before high rise buildings have gone up on top.

      Back to the software world -- if you've got code that was pre-Web / pre-Internet but needs to be brought into the 21st century, inevitably things won't fit. I've worked on some banking code which had punchcard assumptions shine through. Some of that code is 40 years old. You could call it crufty, some would call it rock-solid.

  6. I write spaghetti code by Big+Hairy+Ian · · Score: 4, Insightful

    Just like everyone else

    --

    Build a Man a Fire, and He'll Be Warm for a Day. Set a Man on Fire, and He'll Be Warm for the Rest of His Life.

    1. Re:I write spaghetti code by gander666 · · Score: 2

      Truer words have never been said.

      --
      Suppose you were an idiot and suppose you were a member of Congress ... but I repeat myself. - Mark T
  7. Code I consider 'elegant'. by Asteconn · · Score: 5, Insightful

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

    1. Re:Code I consider 'elegant'. by Slashdot+Parent · · Score: 2

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

      This is a good barometer.

      When I write code, my goal is to create an accurate design with the proper abstractions that will make the complex business problem look like it was trivial to solve. The easier that I made my job look, the higher the quality of my deliverables, in my mind. The next person to look at my code should say, "Of course he solved the problem that way. I would have done the exact same thing."

      By the way, given the sheer volume of WTFs I encounter, the next person to look at my code probably only thinks that he would have done the exact same thing. But that's OK. WTFs are Consultant Welfare.

      --
      They don't grade fathers, but if your daughter's a stripper, you fucked up. --Chris Rock
    2. Re:Code I consider 'elegant'. by Tablizer · · Score: 2

      Some engineers consider code "elegant" if it's factored to the smallest possible form, which generally means all repetition possible is factored out.

      But such code has at least two problems. First, is that it may not be easy for a good portion of developers to read and understand. Factoring out all possible duplication often results in a lot of indirection (reference levels), and indirection can slow down and complicate reading because you have lots of small parts referencing (using) lots of other small parts.

      Second, future changes may not follow along the grain of the existing high factoring. The future patterns of change or similarity won't necessarily follow the past patterns. There are more "tight knots" to untangle in order to rework the code for a given change. Tight factoring means you have to do a lot of UN-factoring when you need to add changes that don't fit the existing factoring patterns.

      A certain amount of duplication is probably the ideal. Both too much or too little factoring creates problems. It's the skilled developer that finds the Goldilocks range of factoring. Often only experience and familiarity with the domain can bring about that ability.

      I've learned this the hard way: experience and past design mistakes, NOT because I am smarter. I do make it a personal mission to remember and learn from failures, though, both my own and others'.

  8. Re:Complete Spectrum Rom Disassembly by Anonymous Coward · · Score: 4, Informative

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

  9. Elegance only exists in textbooks by petes_PoV · · Score: 5, Insightful

    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

    --
    politicians are like babies' nappies: they should both be changed regularly and for the same reasons
    1. Re:Elegance only exists in textbooks by JaredOfEuropa · · Score: 4, Insightful

      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.

      --
      If construction was anything like programming, an incorrectly fitted lock would bring down the entire building...
    2. Re:Elegance only exists in textbooks by gstoddart · · Score: 3, Insightful

      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.

      --
      Lost at C:>. Found at C.
    3. Re:Elegance only exists in textbooks by ktrammel · · Score: 2

      I appreciate this comment. I write code for a hospital. I'm curious how many other programmers here have had the experience of trying to adapt the logical constraints of programming with the ad hoc conditions of health care? I find that your comment about tidy algorithms existing only in books is apt. In the health care milieu, there are very few "tidy problems," precious few systems which lend themselves to discreetly quantifiable logic. There are always multiple exceptions. New decision loops continually intrude on any system so that you have to leave room for the end user to make spontaneous decisions. The same is often true in business programming (especially because of something like tax accounting), and health care combines both the often non-intuitive complexities of business accounting (esp. with regard to insurance claims) with its endless exceptions and special cases, with the impossibly human conditions of point-of-care decision making. I wrote a program to manage insulin therapy administration and the flow diagram looked like a plate of spaghetti. The program works quite well and has improved outcomes, but I always ask myself, how well does it accommodate the incredible complexity and the always threatening presence of the intuitive imperative in patient care? What about that looming black swan? Honestly, I'm not entirely comfortable with it. However, we continue to press for enveloping medicine with highly discreet logical structures. There's no proper accommodation for this even through fuzzy logic, that I can see anyway.

      My personal experience is that healthcare requires continual expansion beyond present understanding. Any current logical framework is going to be inadequate as experience reveals deeper causation. But I digress. I just wanted to lend support from my own personal experience as a programmer to the idea that elegant code is at times a luxury of academia, an ideal, more than a quality of the practical application of programming methods. It is valuable as an ideal, though. That elegance isn't always possible doesn't mean you can't still structure and comment and plan carefully so that the code you write is intelligible to others, and to your future self when you have to make the inevitable modifications. And the ideals of elegant solutions can always be a useful guide. If that kind of coding is elegant, then elegance is still possible in any context. But I'm honestly not confident that some practical applications allow for elegant implementation of the logical constructs of code. It is too constraining for some applications, such as healthcare.

      Another demonstration in support of that view is that the many vendor applications with which I work, often in attempts to integrate them with each other, are fraught with bugs and failure points. But that's not even the most significant issue. The real problem is the work-arounds required by the end-user by such applications just to get their jobs done. And I'm talking about major vendors, like McKesson, with huge resources and vast amounts of invested time. While their applications may be enormous and sophisticated, and expensive, in the healthcare environment they require constant care, constant work to make them work, if that makes sense. This problem is transferred over to the development of code that integrates with these systems. So, to my mind, elegance isn't possible in every instance of a practical programming. I used to write simulations of mathematical and physical systems for fun -- that allowed for elegance. But those are highly structured, highly ideal contexts. It is at the opposite end of the spectrum.

  10. GPS code by tlambert · · Score: 3, Informative
  11. Elegence? by Wowsers · · Score: 2

    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.

    --
    Take Nobody's Word For It.
    1. Re:Elegence? by pr0nbot · · Score: 2

      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.

  12. The pinnacle of elegant code by igomaniac · · Score: 5, Funny
    --

    The interactive way to Go -- http://www.playgo.to/iwtg/en/
  13. Duffs Device is clever - its not elegant by Viol8 · · Score: 4, Insightful

    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.

    1. Re:Duffs Device is clever - its not elegant by TsuruchiBrian · · Score: 2

      Nope, it's abstractions all the way down....

  14. Minimise state by famebait · · Score: 5, Interesting

    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.

    --
    sudo ergo sum
    1. Re:Minimise state by famebait · · Score: 2

      Caching is an optimisation that does indeed introduce state, and all the problems that comes with it in full.

      Like all optimisation, it constitutes buying performance in exchange for increased complexity (of some sort). The cost of complexity is high, and the tradeoff should be qualified by a solid cost-benefit anaylis, and by extension pertain to a demonstrably real performance problem.

      That said, I certainly accept that 'true' changing state can be part of a good model, and I don't consider that caching. Just keep it under control, make sure it actually delivers value, and don't sprinkle it around lightly.

      --
      sudo ergo sum
  15. It's always elegant at first by GrahamCox · · Score: 3, Insightful

    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.

  16. Elegant code is like a great teacher. by Balinares · · Score: 5, Insightful

    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.

    --

    -- B.
    This sig does in fact not have the property it claims not to have.
  17. Re:Comment your damn code by bre_dnd · · Score: 5, Insightful
    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.

  18. I'm a style prude by CockMonster · · Score: 2

    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.

  19. Elegant code is.... by Lumpy · · Score: 2

    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.

    --
    Do not look at laser with remaining good eye.
  20. Read "Clean Code" by Jahta · · Score: 2

    If you follow the principles and practices in Clean Code: A Handbook of Agile Software Craftsmanship: Robert C. Martin you won't go far wrong. It also includes a worked through example of refactoring a piece of bad code into clean code.

  21. Re:GPS? Are you kidding? by jonwil · · Score: 4, Informative

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

  22. Re:GPS? Are you kidding? by arglebargle_xiv · · Score: 3, Insightful

    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.

  23. My personal "law" by acroyear · · Score: 3, Insightful

    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.

    --
    "But remember, most lynch mobs aren't this nice." (H.Simpson)
    -- Joe
  24. Re:GPS? Are you kidding? by exploder · · Score: 5, Funny

    As someone who got lost somewhere deep in a single sentence (which consumed three whole screen-width lines) that spent nearly 100 words on a dependent clause (which itself contained two parenthetical clauses) before even getting to the subject (I was starting to wonder if there would be one at all) I question the value of your comments on the topic of elegance...

    --
    Yo dawg, I heard you like the Ackermann function, so OH GOD OH GOD OH GOD
  25. Re:Ideals vs Reality by BasilBrush · · Score: 2

    I'll take a guess that readability is no more important in your code style than your prose.

  26. FORTH by Giant+Electronic+Bra · · Score: 4, Interesting

    A complete highly extensible interpreted language with a built-in editor, macro assembler, etc in under 10k lines of code which did everything any modern scripting language does, except they all require at least 200KLOC to do it in.... This is the most elegant piece of software ever written, bar none. It isn't even a contest.

    --
    "Malo periculosam, libertatem quam quietam servitutem." -- Jefferson
  27. Elegant code is... by plasticsquirrel · · Score: 2

    Elegant code is...

    • Simple -- leveraging the "natural" way to use the programming language
    • Compact -- not cluttered with special cases and boilerplate
    • Logical -- like secondary documentation, acting as a clear description of how to solve a problem
    • Modular -- functions or classes should be clearly grouped as modules
    • Easy to understand -- not full of stupid hacks and "clever" tricks
    • Reasonably efficient -- performing reasonably well, not at the expense of simplicity
    • Maintainable -- any decent programmer could pick up the code without fear and trepidation
    • Commented -- some comments should be present, but not too much
    • Correct -- it should do what it is meant to do, and only this

    There are also some languages that I view as inherently elegant, and others that I consider not to be so. C, Python, and Ruby all allow breathtaking elegance in their own way. C with its spartan manner of managing the machine, Python with its ridiculously readable pseudocode-like syntax, and Ruby with its pure object system and powers of abstraction. On the other hand, some other languages like C++, Java, Haskell, Javascript, PHP, BASIC, and Erlang will never be languages that lend themselves to true beauty and elegance. All of those languages either have serious flaws, or they do not allow programmers to express their ideas eloquently in code. In a good language, your ideas should pop out as the most important thing, not the language itself.

    --
    Systemd: the PulseAudio of init systems
  28. Re:Comment your damn code by TuringTest · · Score: 2

    since the comment is not executed, there is no guarantee that it reamains correct

    As the purpose of comments is to explain *why* a part of code was created (and why it was written in that particular way), it not being executable shouldn't matter much, as completely repurposing a bit of code rarely happens. (Generalizing it yes; abandoning the original purpose of a routine or function is uncommon).

    The best comments are those targeted for the programmer reading them, not the machine that must execute the code; and letting fellow programmers know why you needed that piece of code in the first time is invaluable, even if what the code does changes over time.

    --
    Singularity: a belief in the "God" idea with the "demiurge" relation inverted.
  29. Elegant code != Good code by cjjjer · · Score: 2

    Most of your so called *elegant code* I have seen is either difficult to maintain or performs poorly due to the original developer trying to be a fancy pants. I can count the times on one hand that I have ever said "whoa" when looking at a piece of code.

  30. I am one of those guys by Anonymous Coward · · Score: 5, Insightful

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

  31. Microsoft just did... by kaychoro · · Score: 2

    Take a look at MS-DOS source... that'll be elegant and bug free.

    --
    //TODO: create a signature
  32. Re:Elegant Code? by Buchenskjoll · · Score: 2

    Well, it looks like we're not all racist bastards.

    --
    -- Make America hate again!
  33. Re:conditional operator by gnasher719 · · Score: 2

    Does anyone else hate the conditional operator. It replaces six lines of code with one line...

    My first boss complained that a page of my code was harder to read than a page of his code. I told him that one page of my code was a lot easier to read than the six pages of code he wrote to accomplish the same thing.

  34. Postfix by andawyr · · Score: 2

    Fantasic example of code written in a procedural language (C) in an object-oriented way,with clear separation of responsibilities.

    http://www.postfix.org/

    The framework that Wietse created to structure Postfix is, from my perspective, a thing of beauty. I don't doubt that this has been done elsewhere, but Postfix is the first real example that I came across of a somewhat-large application structured in a very clean and understandable way.

    Well worth spending some time perusing the code.

  35. A tour guide w/"Programming Pearls" (not Perl) by Fubari · · Score: 2

    I'll recommend a tour guide in the form of John Bentley's Programming-Pearls-2nd-Edition.
    His Programming Perls book does a nice job of putting interesting algorithms and design forces into context and helps the reader understand the pros & cons thereof. Part of the problem with just wandering around looking at things is you don't see the history and decisions that were made leading up to the result; understanding "what" isn't nearly as important as "why".

    Also, the book isn't related the the Perl language; instead it uses Pearl as a metaphor for a small yet beautiful treasure.

    Anyway, check out the Amazon reviews to see if it is worthwhile (I have no vested interest here; I just stumbled across this in a real book store some time ago and found it a satisfying read).

  36. Google My Tracks by aoteoroa · · Score: 2

    Since you are looking for an open source GPS application take a look a My Tracks android application for tracking, location, speed, altitude over time.

    I can't speak to how well it's coded, but the application design is simple, and elegant

  37. definition by whitroth · · Score: 2

    I have long said I preferred elegant to clever code. When I get a phone call on Friday, at 16:15, or 02:00 some night, I want to leave on time, or go back to sleep that night, *NOT* spend hours figuring out how this bit of cleverness is broken, or how someone's "the code's more compact!" is suitable for entry in the Obfuscated C contest.

    But to write elegant code, you need to a) know what you're trying to accomplish; b) tell your manager, or whoever, that no, you can't make that kind of major change without their $$$ signoff on a change to the schedule, complete with specing out the change, and its affects on everything else; c) having the time to write, test, and debug the code, and this does *NOT* include drinking a six-pack of Mountain Dew a day, and doing 80+ hour weeks.

    Yes, I *have* had jobs like that. And 70+ or 80+ hour weeks result in a *lot* less "productivity" than the old 40-hour week (and try looking up where that number came from... the name Ford may surprise you in that....).

                                mark "as opposed to managers w/ MBA, who think that you can point and click a good system"