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

373 comments

  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 JaredOfEuropa · · Score: 1
      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.

      --
      If construction was anything like programming, an incorrectly fitted lock would bring down the entire building...
    5. Re:Duff's Device by gnasher719 · · Score: 1

      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.

    6. Re:Duff's Device by DrJimbo · · Score: 1

      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.

      --
      We don't see the world as it is, we see it as we are.
      -- Anais Nin
    7. 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.

    8. 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.
    9. Re:Duff's Device by DpEpsilon · · Score: 1

      Woosh.

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

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

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

    12. Re:Duff's Device by Anonymous Coward · · Score: 0

      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.

    13. Re:Duff's Device by StripedCow · · Score: 1

      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.

      --
      If Pandora's box is destined to be opened, *I* want to be the one to open it.
    14. 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.

    15. Re:Duff's Device by Anonymous Coward · · Score: 0

      Duff's Device

      Elegant?

      That's a hack.

      I've seen more elegance drop out of the south end of a northbound cow.

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

    17. Re:Duff's Device by Anonymous Coward · · Score: 0

      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.

      ...

      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.

      In my experience elegant source code (1) uses descriptive yet concise names for variables and functions/methods/procedures, (2) each function/method/procedure is documented with a header block immediately preceding it, (3) a competent computer programmer / software developer / software engineer can read through the source code and understand it; this person need not be an expert in the particular language, and (4) the source code is maintainable and extensible. In fact using language specific idioms often detracts from producing easily maintainable source code.

      On a related note, a troubling attitude towards highly-competent computer programmers prevails throughout many organisations especially from the very people who could not code Fibonacci's Sequence or a utility to replace hard-coded passwords with a variable name within say a Unix shell script. I have worked with such people throughout my IT career. I would not have hired any of them. Anyone working in IT should be able to create a script for whatever operating system is deployed in the organisation, particularly for those systems which they are responsible. In one workplace I constantly hear the derision "oh you just wrote a script...that's easy" from people. Many of the Unix shell "scripts" contained 2500+ lines of code (excluding the lines of comments). I quoted the word 'scripts' because they placed such emphasis on the term themselves as a put-down.

    18. Re:Duff's Device by Anonymous Coward · · Score: 0

      No it's brainfuck,
      it's got all the elements: great name, small, and only the people who know wtf they're doing can read it (sort of)
      http://en.wikipedia.org/wiki/Brainfuck
      otherwise i'd go with machine language ( http://www.atariarchives.org/mlb/introduction.php ) or if you really have to assembler...

    19. Re:Duff's Device by beelsebob · · Score: 1

      Uhhhh... no.

      That's in no way elegant. It's overly complex "clever" code, that doesn't simply state to a human what is going on. Add to that that modern compilers will do a better job of optimising the elegant implementation, and this is probably the least elegant code you could ever write.

    20. Re:Duff's Device by Anonymous Coward · · Score: 0

      I totally agree, the art of coding is the art of simplicity. When you can create a recursive function, do it, although a little more thinking is involved, the ability to read and understand the logic is much easier.

      Sometimes having a million interfaces and layers doesn't make code more elegant than an old fashion static function. ;) Think about it..

    21. Re:Duff's Device by jythie · · Score: 1

      What makes the entire 'elegant' debate rather futile is how readable a piece of code seems is highly dependent on the person reading it and the stylistic patterns they follow.

    22. Re:Duff's Device by beelsebob · · Score: 1

      Duff's device never was elegant. It was always a very dirty hack to trick the compiler into generating something you wanted it to. The elegant solution is to state exactly what you want to happen in as clear a way as possible.

    23. Re:Duff's Device by nitehawk214 · · Score: 1

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

      Speaking of elegant code... proper and consistent formatting is almost as important as the functionality.

      --
      I'm a good cook. I'm a fantastic eater. - Steven Brust
    24. 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.

    25. Re:Duff's Device by PatMouser · · Score: 1

      Oh so this!

      I have had to tell cow-orkers to knock that crap off. They've got the job, and from this point on the only thing that will impress us is code that can be maintained by anyone else on the team, even if they have not set eyes on it in years.

      Programmer did:

      my $something = [];
      open my $filehandle, '<', $filename or croak "Can't read file";
      push @$something, <$filehandle>;
      close $filehandle;

      How about:

      open(my $filehandle, '<', $filename) or croak "Can't read file";
      my @something = <$filehandle>;
      close($filehandle);

      Much more succinct, gets rid of a pointless use of an array reference (seriously, it was used as an array in that function only, never passed around or returned), and at the end of the day, is far more readable.

    26. Re:Duff's Device by AaronLS · · Score: 1

      He did ask if it was a joke, which is a valid question because plenty of people on the internet make rediculously stupid statements. I don't blame him for wondering if you were serious or a joke. He clearly reallized that there was a remote possibility that you were joking, so I don't see that a "woosh" was appropriate. You could have just said you were indeed joking :)

    27. Re:Duff's Device by Anonymous Coward · · Score: 0

      >boiled down to a single CASE statement, 4 lines long

      I'm betting this Master Programmer wasn't buying you lunch after that stunt. So tell us: did you get marginalized, harassed, or fired?

    28. Re:Duff's Device by Anonymous Coward · · Score: 0

      To which I reply 001011010100100101000100101001001010100100101001001011010101010101010 and tell you to go die in a fire.

      I used to have to read binary and hex memory dumps to debug my code (1980s IBM Panvalet/TSO mainframes) and NO, THANK YOU, NEVER AGAIN. And if you want to spend the rest of your life imposing on yourself the agony of coding in machine language or assembler (self-imposed, not job -required) then you are a masochist and should seek help, NOW.

    29. Re:Duff's Device by nine-times · · Score: 1

      I'm not a programmer, but it seems to me that different programming strategies are required for different situations. In the case of someone writing a kernel or other low-level code, you may want to optimize the hell out of the code even if it makes things hard to read. The idea here is that whoever is working on the code should have a pretty good idea of what they're doing and could read the difficult code, but performance is among the top priorities. In that case, there is a certain elegance in creating code that's super-efficient even if it's apparently complex.

      However, for most other programs I would agree with you-- one of the major priorities should be to keep the code simple and easy to read, keeping in mind that you want it to be as easy as possible for another programmer to come in after you and make updates without breaking anything. In that case, I'd think of "elegant code" as something that does powerful things while being almost transparent to a neophyte.

    30. Re:Duff's Device by Grishnakh · · Score: 1

      I'm not a programmer, but it seems to me that different programming strategies are required for different situations. In the case of someone writing a kernel or other low-level code, you may want to optimize the hell out of the code even if it makes things hard to read. The idea here is that whoever is working on the code should have a pretty good idea of what they're doing and could read the difficult code, but performance is among the top priorities.

      Not necessarily. Go look at the Wikipedia page for Duff's Device (discussed in the comments above). Something that's more complex and looks like it'd improve performance may very well achieve worse performance because of the nature of modern CPUs. As stated on the Wiki page, Duff's Device worked well when it was invented because C compilers did a poor job optimizing, and CPUs were much simpler. Now, compilers are much better, and CPUs have pipelines and built-in features to handle looping better (which modern compilers are designed to take advantage of), so constructs like Duff's Device end up performing worse.

    31. Re:Duff's Device by Grishnakh · · Score: 1

      It's not just modern compilers, it's modern CPUs. Today's CPUs have many features like pipelining and branch prediction to handle loops better, and modern compilers are written to take advantage of the architecture of modern CPUs. So that clever code may have worked very well on an 80386 CPU with a circa-1990 compiler, but on a Core i7, it'll perform much worse than a truly elegant and simply-coded algorithm.

    32. Re:Duff's Device by Anonymous Coward · · Score: 0

      *wooosh*

    33. Re:Duff's Device by BronsCon · · Score: 1

      But then... who optimizes the optimizer?

      --
      APK quotes people (including myself) without context and should not be trusted. Just thought you should know.
    34. Re:Duff's Device by 91degrees · · Score: 1

      I'd be surprised if it even worked better on an 80386. Early 90's compilers weren't too bad especially with common idioms like that. Watcom 10 would convert that to a REP MOVSB I'm sure but may well miss this on something more obscure like Duffs Device.

      That specific example would have poor performance for odd numbered "count" since 32 bit CPUs are pretty much always better at 32-bit word aligned moves.

    35. Re:Duff's Device by bzipitidoo · · Score: 1

      The contempt for scripting has its uses. That contempt allowed me to use an open, if weak, language, the bash shell scripting language, rather than be forced to code in this proprietary language the company was overzealous about. I would rather have used Perl, but that would have run afoul of the rules. Company policy was that all code had to be written in that language, but as shell scripting didn't count as coding, hardly anyone noticed, and no one made a fuss. Strangely, the proprietary language was itself something of a scripting language. At least, it was not compiled, it was interpreted. It also helped that the job of one of the scripts was to install that proprietary language, and so obviously could not be written in it since there was no way to compile the code.

      The downside was that the boss didn't consider that real programming, and by extension didn't consider me a real programmer. He was smart in some ways, but was very predujiced, arrogant, and suffered from some significant blind spots. He showed proper respect for visual problems like designing a web page, but couldn't understand that behind the scenes work can also be difficult. Thought the hard part of putting together a web page to display statistics was the visual part, and didn't properly consider that gathering all the statistics desired wasn't a simple matter of gathering information that was lying around, no that information in many cases had to be created (more like, not thrown away) by changing the configurations of the web servers and OSes to log the needed raw info, and by making new tables and routines in the databases, and then that had to be balanced against available disk space and sometimes performance.

      --
      Intellectual Property is a monopolistic, selfish, and defective concept. It is "tyranny over the mind of man"
    36. Re:Duff's Device by mrchaotica · · Score: 1

      The horrendous fall through behaviour of switch statements

      Hey, I like the fall through behavior of switch statements!

      Granted, you want a break statement for each case more often than not (and if you're using an IDE, then I think it's reasonable that it should insert one for your automatically), but there are plenty of circumstances where it's a good idea to have a group of cases that all do the same thing, or where you want to do case A and B's actions for case B, etc.

      --

      "[Regarding the 'cloud,'] ownership was what made America different than Russia." -- Woz

    37. Re:Duff's Device by Anonymous Coward · · Score: 0

      It also makes me sad that a lot of people refuse to recognize that clever (and necessary) solutions to problems can be hard to understand to some. They limit elegance by the grasp of their own intelligence. It's not even a far-reaching grasp; anything that goes a step beyond intuition seems to be disqualified, even though the underlying abstract ideas would be considered mathematically elegant. And these are the same people that complain how simple-minded managers use "lines of code" to measure programmer productivity.

    38. Re:Duff's Device by gweihir · · Score: 1

      Very, very true. Coding is not about impressing people with the complexity you can (or rather believe you can) master. Coding, like all engineering, is about finding the solution with the lowest complexity that does the job well. If it is not maintainable or hard to maintain, it is bad engineering, period.

      --
      Most ACs are not even worth the keystrokes to insult them. Be generically insulted by this and ignored otherwise.
    39. 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'.

    40. Re:Duff's Device by gweihir · · Score: 1

      Not my experience. Over the years a lot of students of different competence level had to read and modify my code (not exercises, real tasks). I universally got the comment that reading and understanding my stuff was easy. This made them much more productive and they learned more in addition. And I do not use the most "clean" style, I use 2 char indent C with compact braces. That does matter very little if you do it right. On the other hands, if you write convoluted code, no amount of "style" will help at all.

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

      "clever" is basically always not "elegant" or "clean" at all. Sure, sometimes you have to do _complicated_ stuff. Sometimes you have very tight resources. None of these justify code that is hard to read or understand. It is about making the right things explicit, only optimizing where it really has a large effect, clearly explaining why some things are done, summarizing interface or block functionality clearly, etc. You can even do OO C (yes, OO C, not C++ or ObjC) with embedded Assembler in a way that it is easy to understand and read. Of course it will never be easier to understand code than it is to understand the problem it solves, but if you have a large gap between the two, then you have failed.

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

      Well, sometimes you have to optimize. That is no excuse for bad readability. Here the tool named "comment" (almost unknown among leet coder wannabes) can play a critical role. Now, if you must do something complex and you manage to make it still relatively clear, that is of course acceptable. It can happen that you have 10 lines of code and 40 and some ASCII-Art in explanation and that the explanation takes you almost as long as the coding. You still have to do it in order to produce a good result.

      The problem is that most coders create code far more complex than needed and believe themselves to be the ueber "alpha-coders" for it.

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

      In the era this was written, compilers didn't optimize worth a damn. I totally agree it's not elegant but Duff wrote that to solve a problem that the "elegant" solution just couldn't solve. Even still, Duff's device isn't really that hard to understand if you're familiar at all with loop unwinding, especially if you've ever done it in assembler (and C isn't that much more than a semi-portable assembly language). Sometimes you have to write ugly things because the pretty structured/OO way just doesn't cut it.

      Even today, "optimizing" compilers sometimes don't. On the other hand, this doesn't occur as often as some people think. I operate on a policy of "trust your compiler, until you can't."

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

      It's just optimizers all the way down.

    45. Re:Duff's Device by laejoh · · Score: 1

      who they're trying to impress

      Larry Wall, obviously!

      ;)

    46. Re:Duff's Device by Rufty · · Score: 1

      I ran the optimizer on itself and now I've got /dev/null.c

      --
      Red to red, black to black. Switch it on, but stand well back.
    47. Re:Duff's Device by JeffAtl · · Score: 1

      Exactly. Showing up a "master programmer" that has a lot of respect with the company can be definitely be a risky thing to do.

    48. Re:Duff's Device by Darinbob · · Score: 1

      This performance depends upon the architecture and compiler. For the machines Duff used his technique was efficient. Remember that at the time compilers were still pretty basic and simple, and the processors as well were only just starting to provide high performance features. Since that time both processors and compilers have changed drastically. Basically the Duff device is doing exactly what many optimized assembly language implementations did except that it's done in pure and legal C.

      So it doesn't improve performance on today's systems, so what? It was a valid optimization except for the class of people who think no one should ever attempt any form of optimization. And on some of today's system it is still efficient code, not everything in the world is a PC supercomputer, we have plenty of 8-bit and 16-bit cpus still in heavy use, as well as 32-bit processors without caches or branch prediction where this technique would work.

    49. Re:Duff's Device by Darinbob · · Score: 1

      The problem though is that the elegant code was significantly slower by far, using the compilers and processors at that time. DD was indeed faster. The alternative would be to create an assembler library routine.

      Switch fall through is a good thing in many cases. Sure it freaks out the code purists who vastly prefer fully structured code and who will intentionally add lots of state variables merely to avoid a sinful "break" or early "return".

      And it is still not necessarily slower now than it was. It is indeed slower on some systems and compilers but not all of them.

    50. Re:Duff's Device by Darinbob · · Score: 1

      Even if that method has horrendous performance and your job is to make it as fast as possible? The solution of waiting a few decades for faster compilers and processors is not an option here.

      From a pure language stance, Duff's Device is not elegant; from a pure language stance there is no such thing as a branch delay. But for a solution to the problem of how to get a lot more performance out of the computer in a straight forward way then this was an elegant solution even though it may not be elegant code.

    51. Re:Duff's Device by Darinbob · · Score: 1

      If your project is due in a month, then you can not wait for improvements in technology. If the original loop is too slow, then the project is a failure and the code itself is "incorrect" because it takes too long. Thus Duff's Device is an elegant solution given real world constraints.

    52. Re:Duff's Device by TsuruchiBrian · · Score: 1

      Honestly I'd prefer this:

      my @something;
      open my $filehandle, '<', $filename or croak "Can't read file";
      while (my $stuff = )
      {
      ____push(@something, $stuff);
      }
      close $filehandle;

      Perl was actually my first scripting language, and I do get all the wierd perl syntax, but not everyone else does. Given that on of perl's general paradigms is to provide a lot of ways to do the same thing (unlike python), I would opt to do things in a way that more people, many less fluent in perl, would still understand, even if it takes a few more lines.

      Elegance doesn't even necessarily mean fewest lines of code. If your code is 10x as many lines of code as it needs to be, then you've clearly got a problem, but a few extra here and there that make things *more* understandable for some people is fine.

      Ultimately I don't have a problem with any of these except for the unnecessary reference.

      What might be even nicer is if the program was able to process the info as it's reading it, and get rid of the array altogether. That way it won't cause your system to run out of memory if you happen to run the script on a 2 TB file.

    53. Re:Duff's Device by TsuruchiBrian · · Score: 1

      Well to be fair, the whole thing could probably be explained by adding a comment

      // Duff's Device

      But this is because it is a well known construct (well known enough to have a wikipedia page). That doesn't mean it's ok to use it (for many of the reasons already pointed out in this thread). I just think it's ok to not to have extensive comments explaining what it's doing because of it's notoriety. YOu could do the same for "//Heap sort", "//binary search", etc.

    54. Re:Duff's Device by TomRC · · Score: 1

      Um - maybe my eyes are just skipping something - but isn't that (Wikipedia) implementation completely 'bugged'?
      I.e. it seems that it only increments the source "from" pointer, not the destination "to" pointer?

      Not to mention that the idea that "tricky" code is "elegant" is pretty much completely backwards. Coding in odd ways just to be tricky, or to minimize lines of source code for the sake of 'compactness', or pretty much any other 'clever coding' goal - tends to create buggy code that is hard to debug and hard for anyone else to understand if they need to modify it. As evidenced by the many good programmers here who looked at that "clever" code and didn't notice that it continuously overwrites the same location in memory...

      It was such 'cleverness' that led to the bad reputation of 'goto' from people writing spaghetti code. At least in the early days of programming, programmers had the excuse of slow processors and limited memory and poor compilers, to justify coming to equate 'tricky' with "clever and elegant". Unless you're coding for some ultra-tiny system, such thinking is simply obsolete, and anyone engaging in it ought to be embarrassed at their misguided priorities.

      Elegant code is functionally correct, will create a fast/efficient/compact run-time (assuming a decent compiler / interpreter and depending on settings appropriate to the project), and above all must be READABLE and MAINTAINABLE.

      Where old-time programmers abused GOTO, modern C++ programmers tend to abuse inheritance and templates, creating code that is often nearly impossible to follow even with the aid of a good development/debugging environment - let alone follow by reading the static source code. And the sad thing is, they think they're engaging in "good programming" even as they create incomprehensible, unmaintainable monstrosities.

    55. Re:Duff's Device by TomRC · · Score: 1

      OK, I missed that it was trying to implement memory-mapped I/O, because I only looked at the "Duff's Device" code.
      The rest still applies, with apologies for the ranting.

    56. Re:Duff's Device by Lotana · · Score: 1

      In my experience elegant source code (1) uses descriptive yet concise names for variables and functions/methods/procedures, (2) each function/method/procedure is documented with a header block immediately preceding it, (3) a competent computer programmer / software developer / software engineer can read through the source code and understand it; this person need not be an expert in the particular language, and (4) the source code is maintainable and extensible. In fact using language specific idioms often detracts from producing easily maintainable source code.

      Agreed. Have you ever encountered/worked with such code? Any available for viewing somewhere?

      In my entire career I have never seen any examples. Could really use some for morale boosting.

    57. Re:Duff's Device by jafac · · Score: 1

      Yes, this.

      Code is not for communicating instructions to the computer. That's what ASM is for.

      Your source code is for communicating your algorithm to other coders. (or even yourself, say, 2 years from now, when you're maintaining it).

      Writing undocumented, and obscure code, is, in my book, roughly equivalent to throwing your fast-food wrappers out of the window of your car while driving down the highway.

      --

      These are my friends, See how they glisten. See this one shine, how he smiles in the light.
    58. Re:Duff's Device by TranquilVoid · · Score: 1

      Sort of related.  If I add some meaningless drivel here then slashdot won't consider my comment to have too few characters per line.  Somewhat ironic that a story about elegant code forces code to be condensed onto less lines.

      #include <stdio.h>
      #include <stdlib.h>

      int main(int argc, char *argv[])
      {
        int i;

        switch (argc - 1)
        {
          case 0:
            printf("No args\n");
            break;

          case 1:
            printf("One arg\n");
            if (strcmp(argv[1], "hello") == 0)
            {
              printf("Hello yourself!\n");
              break;

              for(i = 0; i < 5; ++i)
              {
                case 2:
                  printf("Two args\n");
              }
              break;

              case 3:
                printf("Three args\n");
                break;

              default:
                printf("More args than I can count\n");
                break;
            }
        }

        return 0;
      }

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

    60. Re:Duff's Device by BasilBrush · · Score: 1

      but there are plenty of circumstances where it's a good idea to have a group of cases that all do the same thing

      That doesn't require fall through. Consider Pascal:

      case i of
          0 : Write('zero');
          1 : Write('one');
          2 : Write('two');
          3,4,5,6,7,8,9,10: Write('?')
      end;

      Real structure. No fall through. Neater. Less bug prone.

      or where you want to do case A and B's actions for case B, etc.

      Did you mean case A and B's actions for case A? Because assuming the implication that case A comes before case B, that's what fall through in the C language gives you. It doesn't give you what you wrote you want.

      Far better to be explicit and put the common code into a method of it's own, and call it explicitly from the cases you need, and in the place in the code you need it. Not only is that far more readable than C fall through, far less bug prone, but also is far more flexible in what you can achieve.

    61. Re:Duff's Device by romons · · Score: 1

      Duff's Device

      This is an old assembly code trick. I've seen it on microcontrollers, back to the early 80s for a fast 'strmove' routine. You know, nothing in computer science is new. The guys in the 50s and 60s discovered (nearly) every useful algorithm. See Knuth.

      I have been playing with python recently (in the last couple of years,) and have noticed what people call 'pythonic' code. Mostly, it appears to mean compressing the code into as few statements as possible, using tricks like list comprehensions. Get rid of loops, use recursion and comprehensions. I used to find recursion (particularly tail recursion) extremely elegant, but I've been burned way too many times by programmers misunderstanding code that is too complex. So, instead, my choice for elegance is code that can be understood by a monkey. Short, concise functions that don't try to do too much, but are written in a way that they are generally useful. Consistent variable naming. Lots of use of library routines instead of 'do it yourself' functions that may or may not be faster than the debugged and optimized version in the library. If I can read a program and understand it without writing anything down, that is elegant. I've seen algorithms that could make your head explode layed out in a simple, efficient way that made it nearly impossible to break it later with a bugfix. I've also seen fairly simple algorithms implemented in 10 pages of C in a single function, with comments warning that the function was too hard for mortals to understand (you know who I'm talking about, Pratt)

      --
      Go to Heaven for the climate, Hell for the company -- Mark Twain
    62. Re:Duff's Device by BasilBrush · · Score: 1

      The problem though is that the elegant code was significantly slower by far, using the compilers and processors at that time. DD was indeed faster.

      Right. But the request was for elegant code, not optimised code.

      Switch fall through is a good thing in many cases. Sure it freaks out the code purists who vastly prefer fully structured code and who will intentionally add lots of state variables merely to avoid a sinful "break" or early "return".

      Hey your welcome to your opinion. But switch fall through certainly isn't elegant.

    63. Re:Duff's Device by Anonymous Coward · · Score: 0

      Sometimes I think Application developers are like 'seagull managers' (fly into town-crap all over the place).
      they go from one startup project to another, get creds for using the new , sexy technlogy and basically
      don't learn a damn thing.
      I spent many years re-writing applications to the '3am:the program crashed and you have to figure out why"
      rule....

      spending a lot of time dong maintenance helped me to write simple, easy to understand and , where needed,
      good documentation.

      One more thing, the code should be a as flexible as possible... more dynamic structures, rather than hard coded limits, etc
      use stacks for recursion, think about the logical unit of work and how to rollback if you have a problem with database updates,
      writing the code to match the database design, etc, etc...

      Just some thoughts

  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 Anonymous Coward · · Score: 1

      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.

    3. Re:Linux kernel by MtHuurne · · Score: 1

      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.

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

    5. Re:Linux kernel by Anonymous Coward · · Score: 0

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

      Personally, i like that definition.

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

    7. Re:Linux kernel by Anonymous Coward · · Score: 0

      You've obviously never had to write a replacement library for something provided by Microsoft because they refused to acknowledge the bug existed (despite you showing them where the breakage was in the source code) and so refused to fix the bug (despite you showing them where the breakage was in the source code, plus the one line fix, plus the test cases to prove it).

    8. Re:Linux kernel by Anonymous Coward · · Score: 0

      the bsds are better, and plan 9 is really nice.

    9. Re:Linux kernel by gmack · · Score: 1

      Library bugs would equate to a "measurable benefit" to reinventing the wheel. I am not saying you should never replace a library function only that it shouldn't be your first reflex. I would only suggest that you document why you created your alternative routine in your code somewhere so someone (or possibly you years down the road) can easily spot why it was used instead of the existing library function so there is not time wasted later rediscovering the bug.

    10. Re:Linux kernel by Anonymous Coward · · Score: 0

      6. Is HEAVILY commented for the poor suffering bastard who will come after you and get stuck with your impenetrable, entangled spaghetti code.

      7. MATCHES THE GODDAMNED SPECIFICATION REQUIREMENTS.

    11. Re:Linux kernel by Anonymous Coward · · Score: 0

      Padawan, find you strange this Microsoft behavior? Much to learn about the Evil Empire have you...

    12. Re:Linux kernel by LeadSongDog · · Score: 1

      Code quality in the Linux kernel varies a lot per individual driver or subsystem

      Well, Linus uses a broader definition of kernel than is customary, referring to a monolithic (macro) kernel. If you really seek elegance in OS code, you start by looking at microkernels, stripped of all the device-dependent clutter. Harmony, for instance was a mere 20 kbyte kernel, even on 68K architectures. http://books.google.com/books?id=xvOpC0_r14wC&pg=PA100 http://www.researchgate.net/publication/234826460_Harmony_as_an_object-oriented_operating_system This led to the even more succinct MQX, which is embedded in quajjillions of devices.http://en.wikipedia.org/wiki/MQX

      --
      Oh, I'm sorry sir, I thought you were referring to me, Mr. Wensleydale.
    13. Re:Linux kernel by Anonymous Coward · · Score: 0

      Agree, the architecture is naive, lead developer writes code like a silly hacker kid from the 90's and praises "elite c hacks". All in all it is outdated by a couple of decades with no vision for the future. It will for all time be the same old garbage unix hack job it always was, just like any other unix copy.

    14. Re:Linux kernel by Juan+de+los+Palotes · · Score: 1

      6. Almost reads like plain English. The code should almost be an explanation in English of what it does; if it's not possible, comments should clarify why. Very close to the grandparent's last phrase.

    15. Re:Linux kernel by Enfixed · · Score: 1

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

      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.

      --
      Sigs are bad for you...
    16. 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.

    17. Re:Linux kernel by Anonymous Coward · · Score: 0

      Where is the step of patenting said code? Code doesn't really count unless you have a patent or patents.

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

    19. Re:Linux kernel by Altus · · Score: 1

      Wait, you get specification requirement?

      I need a new job.

      --

      "In America, first you get the sugar, then you get the power, then you get the women..." -H. Simpson

  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 Joce640k · · Score: 1

      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.

      --
      No sig today...
    3. Re:Is this a request for optimal code design... by bertok · · Score: 1

      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)

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

    5. Re:Is this a request for optimal code design... by Anonymous Coward · · Score: 0

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

    6. Re:Is this a request for optimal code design... by Chrisq · · Score: 1

      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?

    7. Re:Is this a request for optimal code design... by korbulon · · Score: 1

      Ha HA! Ya got me. .

      At this stage in the game I don't know where the cynic ends and the human begins.

      "Probably at the asshole," a voice whispers in my ear.

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

    9. Re:Is this a request for optimal code design... by Anonymous Coward · · Score: 0

      That was brilliant. Did you make that up, or are you quoting something?

  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.

    1. Re:Writing Code is like Explaining Things by DpEpsilon · · Score: 1

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

    2. Re:Writing Code is like Explaining Things by mooingyak · · Score: 1

      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.

      Similar to my thoughts. There are levels of elegance. The minimum requirement is that it does what it's supposed to, that something is non-trivial, and the code is fairly easy for anyone familiar with the language to understand. Better is when it does all that without any prior explanation of what it's supposed to do. Even better is when the something it's doing is actually quite complex, but still easily understood.

      And then there's just plain awesome, where it uses a language feature that the reader has never seen before but instantly understands because the usage makes it obvious.

      --
      William of Ockham had no beard. The most likely explanation is that it was chewed off by squirrels every morning.
  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 korbulon · · Score: 1

      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.

    2. Re:Knuth's TeX and Metafont by lxrslh · · Score: 1

      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.

    3. Re:Knuth's TeX and Metafont by Anonymous Coward · · Score: 0

      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.

    4. Re:Knuth's TeX and Metafont by mooingyak · · Score: 1

      Think of cities that have grown (London?) rather than be designed according to some grand master plan (New York?)

      I've never been to London, but I work in NY. It's almost the exact opposite of what you're saying, or maybe the middle ground that you didn't cover. Someone designed it to a master plan.... a long time ago. And then it grew. Nowadays I joke that if you're designing a city and your major highways look anything like NYC, it's time to fire the designer.

      --
      William of Ockham had no beard. The most likely explanation is that it was chewed off by squirrels every morning.
    5. Re:Knuth's TeX and Metafont by rasmusbr · · Score: 1

      The primary example of a city that has been planned is Brasilia. But it is only the central parts of Brasilia that have been planned. Most people live in the suburbs that have grown organically around the city. For cities with more than a million inhabitants we can say with some certainty that they can't be planned, because nobody can predict with enough accuracy what the needs of people, businesses and government agencies will be in the future. Planners can only vaguely grasp what the needs are at present.

    6. Re:Knuth's TeX and Metafont by DutchUncle · · Score: 1

      Think of cities that have grown (London?) rather than be designed according to some grand master plan (New York?)

      (NYC is) almost the exact opposite of what you're saying ... Someone designed it to a master plan.... a long time ago. And then it grew

      Almost all of Manhattan Island (which is only part of New York City) above 42nd street was planned out as one grid. The Upper West Side (along Central Park from 59th street northward, about 7 miles) has two subway train lines that were largely done by cut-and-cover before the buildings were built; some 10 or 12 miles of Broadway is really a causeway over the #1/2/3 train lines. The East Side, on the other hand, did not get as much service; the work to put it in now, tunneling below, has been disruptive for years!

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

    8. Re:Knuth's TeX and Metafont by Anonymous Coward · · Score: 0

      comments Comments COMMENTS!!!!

    9. Re:Knuth's TeX and Metafont by LeadSongDog · · Score: 1

      So we're looking for the C. elegans of software?

      --
      Oh, I'm sorry sir, I thought you were referring to me, Mr. Wensleydale.
    10. Re:Knuth's TeX and Metafont by Grishnakh · · Score: 1

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

      I've never been to London, but I'm somewhat familiar with NYC (I live about 15 miles away), and NYC's elegance as compared to London is plainly obvious just by looking at maps of the two. (Note: by NYC I really mean Manhattan.) The streets in Manhattan are mostly laid out according to a grid, and the only place where there's problems is at the very southern end of the island, which is probably also the very oldest. London, by contrast, seems to have very little order to its streets, which is probably because it was never developed according to a master plan the way Manhattan most was, it grew organically over many centuries.

      This doesn't mean everything in NYC is elegant; the subways for instance are a bit of a mess because they were originally all separate companies 100 years ago, each company having its own line(s), and these were later taken over by MTA and merged into a single system, but the legacy remains. However, the streets are (except for the southern tip) mostly a perfect grid, which I would call elegant. (Of course, it'd be nice if they'd clean up the streets and sidewalks sometime and make it so it doesn't stink so much in many places, but that's another issue. It'd also be nice if they closed many of the streets to car traffic and made people use public transit more, and built some better/faster subway lines while they're at it.)

    11. Re:Knuth's TeX and Metafont by Grishnakh · · Score: 1

      If you want to see a better example, take a look at the Phoenix, Arizona metro area. All the main roads are laid out along a 1-mile grid. (There's one irregularity just south of Baseline Road, where the surveyors had to throw in an offset because of the curvature of the Earth.) So all the main roads, with few exceptions (and with big exceptions in Scottsdale), fall along this 1-mile grid. Generally, the corners of main roads are used for commercial space (strip malls usually), and the central parts of these 1-square-mile blocks are used for residential areas (where the streets are different from place to place). It's an extremely easy city to navigate; if you want to know generally where someone lives, you ask them what their "cross streets" are, which is their nearest main intersection. Since there's only so many main roads in the whole metro area, it's pretty easy to memorize most of them and know exactly the location someone's referring to when they say "Rural and Warner" or "7th Street and Camelback".

      Of course, the downside to all this is that the city is the poster child for urban sprawl and you can't get anywhere without a car.

    12. Re:Knuth's TeX and Metafont by rasmusbr · · Score: 1

      Yes, but that's a kind of planning that abstracts away almost all of the details. The master plan for Phoenix might have been something like "the city shall be a grid with the following dimensions and with the following rights of way for various kinds of infrastructure". You can certainly make plans that are vague enough to give future detail planners room to adapt, yet firm enough that the detail planners can't easily plan themselves into a corner that they can't escape from.

      The sprawl is probably mainly a function of the price of vehicle fuel. If fuel had been more expensive when Phoenix was built the blocks would have been filled with higher density.

    13. Re:Knuth's TeX and Metafont by Grishnakh · · Score: 1

      The sprawl is probably mainly a function of the price of vehicle fuel. If fuel had been more expensive when Phoenix was built the blocks would have been filled with higher density.

      Of course, and it's certainly possible to go block-by-block and raze the buildings and build higher-density ones, while leaving the main roads intact. Razing most of west Phoenix and south Phoenix wouldn't be a bad idea.... (and east Mesa too).

    14. Re:Knuth's TeX and Metafont by Anonymous Coward · · Score: 0

      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.

      London: Gherkin
      New York: Chrysler Building.

      New York 1, London 0...

      for a given value of elegant...

      (disclaimer: lived 10 years in London...hate the place with a passion.)

    15. Re:Knuth's TeX and Metafont by mooingyak · · Score: 1

      Think of cities that have grown (London?) rather than be designed according to some grand master plan (New York?)

      (NYC is) almost the exact opposite of what you're saying ... Someone designed it to a master plan.... a long time ago. And then it grew

      Almost all of Manhattan Island (which is only part of New York City) above 42nd street was planned out as one grid. The Upper West Side (along Central Park from 59th street northward, about 7 miles) has two subway train lines that were largely done by cut-and-cover before the buildings were built; some 10 or 12 miles of Broadway is really a causeway over the #1/2/3 train lines. The East Side, on the other hand, did not get as much service; the work to put it in now, tunneling below, has been disruptive for years!

      I was actually thinking of 'anything Robert Moses touched', so all 5 boroughs + LI to start. I don't know how involved he was in other areas. The roads feel like they were designed to induce traffic, as if he could curtail population growth through sheer stubbornness. (stubbornness has 3 sets of double consonants. awesome).

      --
      William of Ockham had no beard. The most likely explanation is that it was chewed off by squirrels every morning.
    16. Re:Knuth's TeX and Metafont by aestrivex · · Score: 1

      But the 3 sets of double consonants are not consecutive. The only word in the english language (that I know of) for which there exist 3 consecutive sets of double consonants is "bookkeeper."

    17. Re:Knuth's TeX and Metafont by mooingyak · · Score: 1

      But the 3 sets of double consonants are not consecutive. The only word in the english language (that I know of) for which there exist 3 consecutive sets of double consonants is "bookkeeper."

      I found the consonant (not merely double letters) part kind of neat, because I can't think of any other words like that.

      --
      William of Ockham had no beard. The most likely explanation is that it was chewed off by squirrels every morning.
  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 Anonymous Coward · · Score: 0

      This. Even true for those who would never admit.

    2. 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. Original MacPaint and QuickDraw code by Anonymous Coward · · Score: 1

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

  8. GPS? Are you kidding? by Anonymous Coward · · Score: 1

    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.

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

    3. Re:Code I consider 'elegant'. by michael_cain · · Score: 1

      My standards for my own code are considerably lower. I settle for, "If I can read it and understand how it all works after not touching it for six months, that's good enough." Once upon a time I had to use APL to to handle a batch of numerical problems, and never managed to reach that bar no matter how hard I tried :^)

    4. Re:Code I consider 'elegant'. by Anonymous Coward · · Score: 0

      I agree, 'Elegant' code is that which is easy to read.

      When (efficient) code reads almost as English, I consider it 'elegant'.

      See python list compressions:
      first10squares = [x**2 for x in range(1, 11)]

    5. Re:Code I consider 'elegant'. by Solandri · · Score: 1

      "Elegant" really depends on what is most important for the task at hand. If you have gobs of CPU time and the code will need to be modified frequently in the future, then yes readability is probably most important. If you're processor-limited (e.g. 3D games), elegant = fast. The best example is probably the fast inverse square root.

  10. Complete Spectrum Rom Disassembly by Anonymous Coward · · Score: 1

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

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

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

    2. Re:Complete Spectrum Rom Disassembly by Anonymous Coward · · Score: 0

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

    3. Re:Complete Spectrum Rom Disassembly by Anonymous Coward · · Score: 0

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

    4. Re:Complete Spectrum Rom Disassembly by Joce640k · · Score: 1

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

      --
      No sig today...
    5. Re:Complete Spectrum Rom Disassembly by Anonymous Coward · · Score: 0

      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.

    6. Re:Complete Spectrum Rom Disassembly by ruir · · Score: 1

      I had it too, pity I cant find the original ones. This book is from where I learnt my Z80 and went later on to write the first Spectrum 48K emulator for Windows.

  11. 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 twdorris · · Score: 1

      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.

    2. Re:Elegance only exists in textbooks by StripedCow · · Score: 1

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

      --
      If Pandora's box is destined to be opened, *I* want to be the one to open it.
    3. Re:Elegance only exists in textbooks by korbulon · · Score: 1

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

    4. 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...
    5. 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.
    6. Re:Elegance only exists in textbooks by jellomizer · · Score: 1

      Consistently making "elegant" code is extremely difficult in real life.
      Because most code interacts with people in one way or an other.

      First we should use those Try Catch Finally types of statement which makes your code less elegant as it prevent your app from uncleanly shutting down due to bad data or input from people.
      Next we have to get code to make sure your inputs are sanitized, to really try to avoid those Trys to pass exceptions.
      Then as you gain experience coding you learn that if you make your code too tight, it makes maintenance and adding those features that wasn't part of spec much harder. So with experience you usually realize where you tight little algorithm will need to be expanded out with say some IF Statements as you could see the rules changing on you.
      Then you have the skill sets of other people on your team. If you are of a higher caliber then they are, then you really still need to lower your standards so everyone will be able to work on the project, and figure-out what you did in case you get hit by the proverbial train.
      Finally there is just basic coding ware. If the project is 80% completed, you have worked long hours, your are hungry or just have to pee at that time, or just tired or not in the right frame of mind that day. Your code may suffer as you are trudging threw coding to get the work done and your tolerance to making it elegant isn't there. (That is why often when you look back at your code that you made last year, you go what the Hell was I thinking!)

      That said you can have pieces of elegance in your code, but as your program gets bigger the overall total elegance lessons.

      --
      If something is so important that you feel the need to post it on the internet... It probably isn't that important.
    7. Re:Elegance only exists in textbooks by NandGate1 · · Score: 1

      Most of the time, yes. Especially in the web development world. However, it does exist. I used to work for a major defense contractor. Our code ran on military aircraft and had to meet very rigid standards for very good reasons. Part of the development process was doing code reviews to make sure the code met those standards. They weren't the type of group code reviews people do to help programmers improve their code, but were one person sitting down going through the code line by line and looking for problems. When doing one of these reviews, I got to a section of code that I indeed considered elegant. Not only that, but I was fairly sure I knew which person did it. When I finished the review, I sought this person out and asked him if he had done it without telling him why I wanted to know. When he confirmed my suspicions, I made sure to compliment him on doing such a great job. Code like his not only passed the review, but would be a joy to maintain. I think a lot of it is the person's mindset.

    8. Re:Elegance only exists in textbooks by hey! · · Score: 1

      Henry Ford once said, "The most beautiful things in the world are those from which all excess weight has been eliminated." Taking that as our standard for elegance, I wouldn't criticize a piece of code as "inelegant" just because it dealt exceptions, language or library quirks that have be dealt with. These are *necessary* things, not "excess weight".

      On the other hand, I *would* criticize a piece of code because the programmer failed to make it as concise and clear as it could have been. Inelegant code is a fact of life because schedule pressures are a fact of life. It's not necessarily the programmers fault, inelegant code may be the best he can do *under the circumstances*.

      But that doesn't excuse the *code* for being excessively complicated or unnecessarily obscure. It's still mediocre code, but sometimes mediocre code happens for good reasons.

      I think it's a cop out to say "real world code can't be elegant", or "elegant code is impractical", because it's not always circumstances that cause our work to fall short of what it can be. Sometimes it's us. Sometimes aren't focused or we're too tired to put the extra bit of effort and imagination it would take to render the useless fat out of our code.

      We should value elegant code, because when it comes to code "elegant" just means "simple and robust".

      --
      Post may contain irony: discontinue use if experiencing mood swings, nausea or elevated blood pressure.
    9. Re:Elegance only exists in textbooks by gnasher719 · · Score: 1

      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.

      Well, there's the difference between 'elegant' code and elegant code.

    10. Re:Elegance only exists in textbooks by gstoddart · · Score: 1

      Well, there's the difference between 'elegant' code and elegant code.

      And, in my experience those making the most noise about 'elegant' code write some of the least elegant code -- because clearly they're missing the fundamental parts about what actually makes it elegant.

      --
      Lost at C:>. Found at C.
    11. Re:Elegance only exists in textbooks by malvcr · · Score: 1

      I have more than 20 years coding, and lately I have been working with a security-oriented framework on C++.

      I must admit my primary goal was security and I have been trying to be strict on security problems usually others have and that usually are defined as weaknesses. However, you also need to work with usability and effectiveness for having something really usable.

      For me, elegant code helps you to express your needs following a very clear and understandable way, be for you in the future or for others to maintain. That code not only needs to be clear, but also needs to be secure and efficient. I do nothing inventing a beautiful piece of code that will use 100 times more CPU because it has been excessively layered, or that permits me to create beautiful pieces of crap that will leak any possible memory and to produce many different types of concurrent problems.

      Elegant doesn't mean to hide responsibilities. I don't believe in the garbage collector "for everything" philosophy, because you lost the control on what you are dealing with, even in places where it is a must to have very precise control. Elegant code is clear, having well defined preconditions and postconditions, with no surprises. Every new has a delete (everything be created must be destroyed), and your programming rules are logical and built up your understanding about the problem you are resolving.

      In a few words : elegant means you are in control.

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

    13. Re:Elegance only exists in textbooks by Anonymous Coward · · Score: 0

      The reason why you rarely find elegant code in real world is that a good specification about what is to be written and how is a rare sight in real world. Mostly you just get some generic task first and then additional tasks will be added and added and the entire job becomes practice of getting around the limitations created previously. Fully define the end goal in the first place, in detail. Figure out the interfaces, think through the processes and structures. Do all that before you write a single line of code. Once you have specified what you are going to do, doing it becomes easy. And if you rubbed your two braincells together when writing the specs it might even turn out elegant.

  12. Elegant code is... by Anonymous Coward · · Score: 1, Insightful

    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.

    1. Re:Elegant code is... by ziggystarsky · · Score: 1
      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.

    2. Re:Elegant code is... by StripedCow · · Score: 1

      He probably means code that runs in O(1).
      http://en.wikipedia.org/wiki/B...

      --
      If Pandora's box is destined to be opened, *I* want to be the one to open it.
    3. Re:Elegant code is... by exploder · · Score: 1

      I suspect he meant "consistent".

      --
      Yo dawg, I heard you like the Ackermann function, so OH GOD OH GOD OH GOD
    4. Re:Elegant code is... by Anonymous Coward · · Score: 0

      He probably means code that runs in O(1).
      http://en.wikipedia.org/wiki/B...

      Which somewhat limits the problem space he can work in.

    5. Re:Elegant code is... by Anonymous Coward · · Score: 0

      Anything that includes iteration or recursion that depends on input is by definition not O(1) - not many interesting things to write without those. Not even a program to output ("Hello, " .. username .. "!"), because its run time is O(n) of username's length.

    6. Re:Elegant code is... by DJCouchyCouch · · Score: 1

      SCLMERMCC! It's a new coding methodology, I can feel it! Just look at that name. it just rolls off the tongue.

  13. Mutually exclusive by mansie · · Score: 1

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

  14. GPS code by tlambert · · Score: 3, Informative
    1. Re:GPS code by Anonymous Coward · · Score: 0

      Oh yeah, provide the links, that really incentives op to not ask /. to google for him again.

    2. Re:GPS code by rastos1 · · Score: 1

      What should be the search terms? "elegant code" ??

  15. Comment your damn code by Anonymous Coward · · Score: 0

    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.

    1. Re:Comment your damn code by famebait · · Score: 0

      All comments are lies.
      Write readable *code*

      --
      sudo ergo sum
    2. Re:Comment your damn code by mwvdlee · · Score: 1

      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.

      --
      Slashdot social media options: AIM, ICQ, Yahoo, Jabber and Mobile Text. Why no MySpace?
    3. 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.

    4. Re:Comment your damn code by famebait · · Score: 1

      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.

      --
      sudo ergo sum
    5. Re:Comment your damn code by Bert64 · · Score: 1

      Almost always better to use a loop, a good compiler can unroll the loop if doing so would be beneficial and unless your targeting a single specific device, what's most efficient will depend on the hardware - eg a large unrolled loop might be slower if the loop is too big to fit in the cpu cache, and the unrolled loops increase the memory usage of the program which may be detrimental depending on the speed and quantity of memory etc.

      --
      http://spamdecoy.net - free throwaway anonymous email - avoid spam!
    6. Re:Comment your damn code by Anonymous Coward · · Score: 0

      Why would you have to overhaul a CRC generator? The optimization to table-driven is well known anyway. Plus, you generated that code *manually*? A CRC generator is best implemented as a metaprogram.

    7. 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.
    8. Re:Comment your damn code by Anonymous Coward · · Score: 0

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

      This is why I never comment code

    9. Re:Comment your damn code by bre_dnd · · Score: 1

      Normally a lookup table would be the way to go. There's always a why -- in this case it was a slow microcontroller with 16KByte of codespace, which was already cramped. Table won't fit.

    10. Re:Comment your damn code by volpe · · Score: 1

      That's the stupidest thing I've read all year.

    11. Re:Comment your damn code by Grishnakh · · Score: 1

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

      Most compilers these days will do this automatically.

    12. Re:Comment your damn code by Ziggitz · · Score: 1

      If your code needs a lot of comments, then your code is not easy to read by definition. Code should be written to be easily read with small functions with names that are self explanatory as to what the code is doing. Comments are great for those little exceptions and cases where the code looks daft but has a legitimate purpose that you don't want someone else to remove, but if your code is 20% or more comments, then they are either completely unnecessary or your code is not well written.

      --
      There is no memory shortage. yes I have heard of XFCE. Go away.
    13. Re:Comment your damn code by dkf · · Score: 1

      The best comments I've seen have explained why a particular string hashing algorithm was used; the algorithm used is not obvious. Or rather it's so obvious that programmers tend to think "it can't be that simple!" and go off and use a different one. Which has the same sorts of weaknesses and is slower, or avoids the weaknesses at a massive performance cost in normal deployments; the comment explains that this has already been tried and warns future programmers that repeating this particular blunder isn't worth it. (And yes, I didn't believe it the first time I read it, but I was cautious enough to performance check the code against all the "industry best practice" hashing algorithms I could find; they really are slower on our typical sample data and have the same sorts of problems.)

      Another great comment I saw was just a reference to the academic paper that the implemented algorithm had been cribbed from. Some algorithms in multi-precision arithmetic and image processing are sufficiently complicated to be things that properly qualify as Non-Obvious; you need to read the literature to comprehend what's going on.

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    14. Re:Comment your damn code by UnknownSoldier · · Score: 1

      > Why would you have to overhaul a CRC generator?

      Gee, maybe the naive implementation is SLOW; Specifically the default algorithm only processes 1 byte at a time -- if could process 4 or 8 bytes at a time we might be able to increase its throughput.

      create.stephan-brumme.com/crc32

      It is not obvious how you go

      From:

      uint32_t crc32_bitwise( const void* data, size_t length, uint32_t previousCrc32 = 0)
      {
          uint32_t crc = ~previousCrc32; // same as previousCrc32 ^ 0xFFFFFFFF
          unsigned char* current = (unsigned char*) data;
          while (length--) {
              crc ^= *current++;
              for (unsigned int j = 0; j > 1) ^ Polynomial;
                  else crc = crc >> 1;
              }
              return ~crc; // same as crc ^ 0xFFFFFFFF
      }

      To:

      uint32_t crc32_1byte( const void* data, size_t length, uint32_t previousCrc32 = 0)
      {
          uint32_t crc = ~previousCrc32;
          unsigned char* current = (unsigned char*) data;
          while (length--)
              crc = (crc >> 8) ^ crc32Lookup[(crc & 0xFF) ^ *current++];
          return ~crc;
      }

      Lastly, the problem with crc32 is that you can NOT split your data into N partitions, feed each blocks to your 4+ core machine and get a single CRC32 for all the blocks; you have to process EVERY byte linearly. Crc32 is not a multi-core / multi-threaded algorithm. Maybe the OP has a variation that IS designed for multi-core.

    15. Re:Comment your damn code by UnknownSoldier · · Score: 1

      Fixed link:

      Fast CRC32

    16. Re:Comment your damn code by Murdoch5 · · Score: 1

      I disagree with you 100%, you should have a comment almost every line or a block comment every section. I work on tons of embedded code where smart ass developers decide to not comment there code and use piss poor structure. Comments are used so everyone else can read and understand your code, if it takes me more then 1 minute to figure out what you did then you wrote bad code period.

    17. Re:Comment your damn code by Anonymous Coward · · Score: 0

      Are you kidding? Remind me never to hire you on my programming team. If you can't write meaningful comments, you shouldn't be programming.

    18. Re:Comment your damn code by Anonymous Coward · · Score: 0

      I agree with you, Murdoch5, and I think Ziggitz is deluded.

    19. Re:Comment your damn code by Ziggitz · · Score: 1

      If your developers didn't write shitty code you wouldn't need the comments. Comments are extremely useful for explaining edge cases that aren't apparent just by looking at the code so some other developer doesn't remove your changes thinking they are incorrect or explaining a configuration of an object or external service that other developers might not be familiar with. If every single line of code is unintelligible or it isn't obvious what it's doing you have way bigger problems.

      --
      There is no memory shortage. yes I have heard of XFCE. Go away.
    20. Re:Comment your damn code by Murdoch5 · · Score: 1

      Well not really, for instance it could take you 20 lines to initialize a device on a port. In that case it would be a benefit to have a block comment above the section explaining what it`s for, also it would be helpful to comment each line to explain what each value or step is for. Putting in comments doesn`t mean you write bad code, it means you want to understand it when you come back to it in a year or 10.

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

  17. The original by Mantrid42 · · Score: 1

    Mel.

    1. Re: The original by cwills · · Score: 0

      I wish I had some mod points.

      Mel's story is a wonderful example.

  18. Ideals vs Reality by MakubeX · · Score: 1

    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

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

    2. Re:Ideals vs Reality by MakubeX · · Score: 1

      It was spaced out when I typed it up, but when I clicked publish it was all crammed. I tried to edit it, but could't figure it out.

    3. Re:Ideals vs Reality by Anonymous Coward · · Score: 0

      trolling again!

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

    The interactive way to Go -- http://www.playgo.to/iwtg/en/
    1. Re:The pinnacle of elegant code by Warbothong · · Score: 1

      You may have been joking, but this one is fantastic: http://www0.us.ioccc.org/1988/...

      It calculates pi by measuring the area of an ASCII circle, which is an incredibly direct encoding of the problem. Other than that there are two lines of supporting boilerplate and a couple of braces.

    2. Re:The pinnacle of elegant code by Anonymous Coward · · Score: 0

      And how do you know that the circle is the best possible approximation to a circle at that size?

    3. Re:The pinnacle of elegant code by Anonymous Coward · · Score: 0
    4. Re:The pinnacle of elegant code by c++0xFF · · Score: 1

      On the other hand, http://underhanded.xcott.com/

      Some of the solutions people came up with to hide malicious code are quite elegant.

    5. Re:The pinnacle of elegant code by Anonymous Coward · · Score: 0

      When I compile and run that program, it prints out:

      0.25

      WTH?

  20. 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 Joce640k · · Score: 0, Redundant

      Mode Parent Up.

      There's nothing "elegant" about DD.

      --
      No sig today...
    2. Re:Duffs Device is clever - its not elegant by Bongo · · Score: 1

      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.

    3. Re:Duffs Device is clever - its not elegant by carnivore302 · · Score: 1

      I don't think that's what he meant. I think he says that anybody who manages to add complexity to something simple and straightforward (a project that would only take a week to do) by adding "beautiful" layers that provide abstractions for the sake of abstraction, should be shot. Personally, I would happily set fire to the remains after the firing squad had its turn.

      --
      Please login to access my lawn
    4. Re:Duffs Device is clever - its not elegant by Bongo · · Score: 1

      Aha, right you are, thanks. Yeah, funny thing about abstraction, somewhere somehow, there still has to be an implementation anyway.

    5. Re:Duffs Device is clever - its not elegant by 50000BTU_barbecue · · Score: 1
      "unintelligable "

      You don't say?

      --
      Mostly random stuff.
    6. Re:Duffs Device is clever - its not elegant by TsuruchiBrian · · Score: 2

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

    7. Re:Duffs Device is clever - its not elegant by Darinbob · · Score: 1

      The most elegant code then is:
            while (read_my_mind()) {
                  do_what_i_want_efficiently();
            }
      Anything else to expand upon that is premature optimization. Even if those library functions do not exist yet, to stop and write them is to engage in premature optimization. If you wait long enough (and your grandchildren wait long enough) eventually that code will be optimal while retaining its elegance. Pragmatism is for impatient losers.

      (remember, code correctness includes efficiency, since in many applications slow or late code is the same as incorrect code)

    8. Re:Duffs Device is clever - its not elegant by Darinbob · · Score: 1

      Elegant code is also code that can be understood. That means being able to be understood without months of training in "code patterns", years of experience with templates, and so forth.

      However there are things that do require lots of training to before the elegance works. Ie, mathematics, an elegant mathematical proof can not be understood by the neophyte. And in code a fixed point operator can be very elegant but is incomprehensible to most programmers.

  21. 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 StripedCow · · Score: 1

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

      --
      If Pandora's box is destined to be opened, *I* want to be the one to open it.
    2. Re:Minimise state by Anonymous Coward · · Score: 0

      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
    3. Re:Minimise state by Anonymous Coward · · Score: 0

      s/state/invariants/g

    4. Re:Minimise state by Anonymous Coward · · Score: 0

      I wouldn't consider what you cache as state. That would be along the lines of input or output data used by the program. Having cleanly defined state is pretty important, and helps make things manageable and reproducible.

    5. Re:Minimise state by BasilBrush · · Score: 1

      True. But bear in mind that one shouldn't optimise early. So if one took the idea that state is bad, one could always compute the result rather than cache for the initial implementation. Then only cache where profiling indicates there's an issue.

    6. 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
    7. Re:Minimise state by Anonymous Coward · · Score: 0

      Wow. I guess you, and all the people who modded you up, don't like object oriented programming.

    8. Re:Minimise state by Anonymous Coward · · Score: 0

      C and C++ is not dead...based on a solid cost-benefit analysis

    9. Re:Minimise state by rdnetto · · Score: 1

      So in other words, most code written in a functional programming language. e.g. Haskell

      --
      Most human behaviour can be explained in terms of identity.
    10. Re:Minimise state by famebait · · Score: 1

      No, I love objects.
      But language features should be used where they bring value, not randomly because they're there.

      First of all, I have no problem with immutable stuff, I don't even consider that state.

      Mutable object state is fine too, as long as it in fact reflects the behaviour you're modelling. But it should be pared down to that. Not absolutely religiously, but it is a good ideal to strive towards, right up there with high cohesion and low coupling.

      Many litter their objects with instance variables that do *not* model the core state of the object at all, but rather serve as a 'nifty' way to pass data to functions with less typing. This makes the object more stateful, which just makes life more difficult all around: you need to know what has happened before to predict what a function will do, and so you depend on many more places in the code to be certain that any one piece does what it should. The logic becomes less readable, more bug prone, harder to alter without introducing bugs, and harder to verify with tests. And that's not even going into thread safety and parallelization.

      Fighting all this is not fighting object orientation. If anything, some solution approaches can be considered *more* object oriented: if that param-list starts getting too long, rather than abuse instance fields as lazy params, group the params into sensible value objects, and you may find the new abstraction yields additional benefits: an avenue for better expressing function and intent, implementing validation and constraints, encasulating calculations and query logic from the client code where it only constitutes noise, into self-explanatory functions on the data object.

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

      For various reasons, functional langugaes are not always a realistic option in you project (especially if you're not starting from scratrch, but yes: there is a lot more to learn from functional programming than lambda-envy.

      --
      sudo ergo sum
    12. Re:Minimise state by rdnetto · · Score: 1

      For various reasons, functional langugaes are not always a realistic option in you project (especially if you're not starting from scratrch)

      The same could be said about elegant code. :P

      --
      Most human behaviour can be explained in terms of identity.
  22. IMHO by KinkyClown · · Score: 1

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

    1. Re:IMHO by BasilBrush · · Score: 1

      Ironically, you could have done with some whitespace around that URL.

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

    1. Re:It's always elegant at first by Lumpy · · Score: 1

      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.

      --
      Do not look at laser with remaining good eye.
    2. Re:It's always elegant at first by asylumx · · Score: 1

      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.

    3. Re: It's always elegant at first by Anonymous Coward · · Score: 0

      "Real developers ship" is the main problem why proprietary software often sucks. Quality control flies out the window when it's time to ship. Then with some awful waterfall model instead of iterative... Ouch.

      If you want quality, remove time from the equations. Make the set of features variable instead.

    4. Re:It's always elegant at first by BasilBrush · · Score: 1

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

      It's not as simple as that. Managers tend to be concerned with short term results, such as shipping the next version. But skimping on doing it properly may make future versions harder to ship.

    5. Re:It's always elegant at first by Lumpy · · Score: 1

      Only a bad developer thinks that, like in the gaming industry and desktop software industry care about shipping.

      When your code can kill or maim people, you care about it being right not shipping. Real programmers care about it being right.

      --
      Do not look at laser with remaining good eye.
    6. Re:It's always elegant at first by Anonymous Coward · · Score: 0

      That sounds like you started off right but had no idea what you were doing midstream. If you don't refactor immediately upon realizing it, it becomes less elegant. But if you properly refactor, elegant code should always exist.

      I'm on a Java project that is 7 years old that was elegant to start and is still elegant.

    7. Re:It's always elegant at first by asylumx · · Score: 1

      But skimping on doing it properly may make future versions harder to ship.

      Yes, that's true, but that's a risk that the person who owns the software needs to consider. That owner is almost certainly not the developer and likely not their manager, either.

    8. Re: It's always elegant at first by Oligonicella · · Score: 1

      "If you want quality, remove time from the equations." If you want to spend all your money prior to having a functioning product - remove time from the equations. I've been in this profession my whole career. The vast bulk of programmers are far more interested in putzing around with their code and dicking around with little logical playthings than in making a finished product for sale. *Yet*, those same programmers want a paycheck.

      I'd rather see a bidding war situation.

    9. Re:It's always elegant at first by BasilBrush · · Score: 1

      There are two potentially conflicting routes to take here.

      a) Do whatever the person that pays the wages says.
      b) Do what your professionalism demands.

      I don't know about you, but I'm not a puppet, nor a prostitute. I don't simply do whatever I'm even if it's the person paying the wages. I'm employed to be a professional. If they don't like it I'll take my talents elsewhere.

    10. Re:It's always elegant at first by Anonymous Coward · · Score: 0

      > I don't simply do whatever I'm even if it's the person paying the wages. I'm employed to be a professional. If they don't like it I'll take my talents elsewhere.

      Accidentally words must be one of those talents. Maybe you have trolling slashdot listed too? Quite the resume, I'm sure. Probably shouldn't be referencing professionalism, as a standard. You tend to use meaningless vagaries when you think someone is going to take you seriously. It's never helpful.

    11. Re:It's always elegant at first by Darinbob · · Score: 1

      Sometimes the problem is that the code gets used, people ask for changes, it gets tweaked, it gets coopted to be used in very unexpected ways, and so forth.

  24. 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.
    1. Re:Elegant code is like a great teacher. by filannino.m · · Score: 1

      Well said!

  25. Teams can't do elegant code. by Anonymous Coward · · Score: 0

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

  26. Isn't it obvious? by Anonymous Coward · · Score: 0

    Malbolge.

  27. Modula-2 first compiler source code by Anonymous Coward · · Score: 0

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

  28. Most python code is elegant by greg.allen.uk · · Score: 1

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

  29. As little as possible by Anonymous Coward · · Score: 0

    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.

    1. Re:As little as possible by Anonymous Coward · · Score: 0

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

    2. Re:As little as possible by DavidHumus · · Score: 1

      In fact, APL is the epitome of elegance in computer programming languages: http://sharonhines.com/interne... (one random, recent example of many).

      One simple example: some languages have a way to do matrix multiplication but it's often a clunky function call or an odd, non-standard piece of notation (I'm looking at you, Matlab). APL doesn't just do matrix multiply but generalizes the very concept of it so that you can do a generalized inner product that reduces to matrix multiply when the functions supplied to it are multiplication and addition.

      Ignorance of the language, common and widespread though it is, is not the same as an actual reason for dismissing it.

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

  31. Code that explains itself by Karmashock · · Score: 1

    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.

    --
    I've decided to stop wasting my time responding to AC trolls/sockpuppets... so if you want a response from me... login.
  32. Elegant != performant by Anonymous Coward · · Score: 0

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

  33. Sieve of Eratosthenes (in Clojure) by Anonymous Coward · · Score: 0

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

    1. Re:Sieve of Eratosthenes (in Clojure) by Anonymous Coward · · Score: 0

      While I was an intendentur at swiss FIS I saw the most beautiful code of clojure I've ever seen, its implications to an expansion of general intelligence on a global scale, if released, is simply put unbelievable. It does so much. As I saw the beauty of this, I illegaly wrote it down by hand and smuggled it out, page by page. Unfortunally I've only been able to preserve the last page, but I'm sure it will give enough light to inspire future computer scientists.
      Here, this is the last page:

      )))...repeated 992 times.

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

    1. Re:Read "Clean Code" by Anonymous Coward · · Score: 0

      Actually, it includes an example of refactoring a piece of good code into clean code. The elegance is found in that margin between good and clean.

  36. Doom3 by tiago.bonetti · · Score: 1

    Linux Kernel is good, but huge... Doom3 seems more of a manageable. https://github.com/id-Software...

  37. Paint .NET by aojensen · · Score: 1

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

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

  39. language of the heart most useful digits by Anonymous Coward · · Score: 0

    thanks again moms...

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

  41. 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
    1. Re:My personal "law" by Anonymous Coward · · Score: 0

      Google for "complecting". You will find references to Rich Hickey (Clojure author).

      This is one of his main points for simplicity is that often things that should do one thing try to do more than one thing (complecting).
      He also argues heavily for statelessness to reduce complexity as well... Two themes mentioned in this thread. He also defines very precisely what "simple" should mean not what it's often conflated to mean (check him out).

      J

    2. Re:My personal "law" by Anonymous Coward · · Score: 1

      This. A thousand times this.

      I write requirements for a living. I also have a seat at the table reviewing the functional spec that is about to be handed to the coders based off my requirements. My personal "laws" in that space are really quite simple.

      1: Do not make any assumptions about future state. A design that needlessly closes doors that you might want to go through in the future is wrong.
      2: If a developer has to make any assumptions, I got the requirement wrong.

      I try to make life easy for the folks that have to implement the requirements I write, even when the requirements (often dictated by finance industry regulations) are complex. It means they turn out code with fewer defects and can concentrate on the good stuff, not chasing their tails fixing bugs.

  42. It exists, but you can't see it. by 140Mandak262Jamuna · · Score: 1
    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.

    --
    sed -e 's/Chuck Norris/Rajnikant/g' joke > fact
  43. Real-world code isn't elegant by Anonymous Coward · · Score: 1

    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.

  44. Of course by Anonymous Coward · · Score: 0

    10 PRINT "HELLO WORLD"
    GOTO 10

    1. Re:Of course by Anonymous Coward · · Score: 0

      10 PRINT "HELLO WORLD"
      GOTO 10

      I would write:

      10 PRINT "HELLO WORLD"
      20 GOTO 10

      And I remember I impressed quite a few people on the c-64 when I added a semicolon to suppress newlines as I was just 7 years old at the time.

  45. Re:GCC? Are you kidding? by u38cg · · Score: 1

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

    --
    [FUCK BETA]
  46. elegant = self-explanitory by globaljustin · · Score: 1

    if code is 'elegant', it can be read well after at most after brief explanation of how the algorithm is supposed to work

    exactly my thoughts as well.

    all "code" is symbols arranged to communicated **instructions** to a machine

    it's all instructions...the variation is the way the instructions are delivered

    knowing this, and having some experience coding, elegant code will be understandable to even novices once the basic "language differences" are learned

    --
    Thank you Dave Raggett
  47. John Lion's commentary on Unix 6th edition by Anonymous Coward · · Score: 0

    I originally had a 7th generation photocopy of this. Simple sweet code, even with the infamous comment on line 2238 of slp.c "You are not expected to understand this", to do with swapped out process resuming.

  48. Re:GPS? Are you kidding? by Anonymous Coward · · Score: 0

    Seconded, gcc is a throwback. Now LLVM, on the other hand ...

  49. Re:GPS? Are you kidding? by BasilBrush · · Score: 1

    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.

    Interesting. I can see that FORTRAN was once the computer language for mathematics, but it never occurred to me that GPS was old enough to be coded in it. But I see that GPS development started in 1973, and even then was based on some earlier work, so definitely during the time when FORTRAN was in common use.

    Can't say I'm surprised that it tends to get ported rather than re-implemented. With something that's as complicated as that, with an implementation that has stood the test of time, better to stick with something that's not easily understandable than to have a new readable version with a whole new set of bugs.

  50. 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
  51. Re:GPS? Are you kidding? by exploder · · Score: 1

    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.

    Yeah. If you want elegance, you should probably just go straight to the math. As soon as you put it into a computer with its pesky limitations of finite time and space, elegance goes right out the window.

    --
    Yo dawg, I heard you like the Ackermann function, so OH GOD OH GOD OH GOD
  52. Elegant code is not practical by Anonymous Coward · · Score: 1

    I'm sure this will seem controversial, but elegant code is not practical in a project sufficiently large enough to be useful. The problem is that for elegant code to stay elegant, you need really very high quality and disciplined programmers who are ALL following some established coding guidelines ALL the time. Even with the best intentions, this doesn't happen particularly during crunch and/or stressful times. In practice you need some level of flexibility and bending the rules in order to do what you want in a reasonable timeframe. Focusing on elegant code requires a non-trivial amount of extra effort for questionable benefit.

    If you're only coding for yourself or are the sole programmer and don't have a pressing timeframe to fit into, then sure, be as elegant as you want. But it's not all it's cracked up to be. In the end you need to produce something that works, even if it involves various ugly hacks to deal with the imperfections of reality.

    1. Re:Elegant code is not practical by Anonymous Coward · · Score: 0

      Hogwash.

  53. Beauty is in the eye of the beholder by cjeze · · Score: 1

    I can not stress enough how important it is to write readable code.

    Keep it simple and be consistent.

    Others will read your code and when they do they will most certainly scratch their heads in either amazement or frustration.

    If you wrote readable code you will make their heads spin less, or your own head spin less when you revisit your own code.

    And if you have been consistent it will be easier to review and update what already exists because it is going to be the same everywhere.

  54. can you say bloatware by Anonymous Coward · · Score: 0

    when the project is elegantly defined... the code has full opportunity to be elegant

  55. CakePHP by Anonymous Coward · · Score: 0

    elegant at least for being written in PHP

  56. Look at a MIT sample code... by Parker+Lewis · · Score: 1

    ... to learn with the PRO: http://www.cs.cmu.edu/~dst/DeC...

  57. Qt by Anonymous Coward · · Score: 0

    Two letters: Qt

  58. Simplicity by Zarjazz · · Score: 1

    I've always considered elegant code to have a few criteria.

    There is no unnecessary complexity in the code.

    The code base is "clean" and consistent. That can be the file system layout, filenames, variable names and function naming. Also a non-consistent comment and white space convention is a personal irk of mine.

    Where most programmers would write several hundred lines of dense code to solve a particular problem, the elegant coder will write a few simple lines instead as they really understood the problem.

  59. My first experience of elegance by Anonymous Coward · · Score: 0

    10 Print "Hello World"
    20 Goto 10

  60. K & R by Anonymous Coward · · Score: 0

    The C Programming Language is full of elegant, clean examples.
    http://net.pku.edu.cn/~course/cs101/2008/resource/The_C_Programming_Language.pdf :)

  61. I think it's been said... by multimediavt · · Score: 1

    I think the crux of it has been said above, but my $0.02:

    Optimized

    Well formatted

    Commented in areas where reading the code isn't obvious to even the newest entrant into programming

    Well supported by the author(s) or corporation that produced it

    I will also admit that I don't write a lot of elegant code, because I usually don't have the time to fully optimize it. But most of my code is well formatted, commented and supported.

  62. 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
    1. Re:FORTH by Anonymous Coward · · Score: 0, Flamebait

      OK, so I went to the wikipedia article, and skimmed through it. You're a fucking troll. That language is one step above INTERCALL for readability. Nice try.

  63. Not elegant at all by Buchenskjoll · · Score: 1

    I've often com across this: if (b) return true; else return false;

    --
    -- Make America hate again!
    1. Re:Not elegant at all by Dareth · · Score: 1

      Could be worse. Often you see:

      if (b = ) return true; else return false;

      Where = is assignment.

      --

      I only look human.
      My mother is a halfling and my dad is an ogre, so that makes me an Ogreling
  64. The Architecture of Open Source Applications by plover · · Score: 1

    I recommend you read The Architecture of Open Source Applications at http://aosabook.org/en/index.h... This book looks at many different open source projects, and can be a source of inspiration (and debate). You'll find some of what you're looking for in it.

    --
    John
  65. Re:GPS? Are you kidding? by mangobrain · · Score: 0

    Hear, hear! Well played. If only I had some mod points.

  66. Elegance is by joseph90 · · Score: 1

    lisp

  67. Definition of Elegant Code by Anonymous Coward · · Score: 0

    NetBSD.

    from https://www.netbsd.org/about/system.html
    >Probably the primary goal of the NetBSD project is emphasizing correct design and well written code.

  68. QuickSort. Donald Knut versiÃn by maitas · · Score: 1

    QuickSort is elegant

  69. 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
  70. Elegance in a nutshell: by ThatsDrDangerToYou · · Score: 1
    Ready? Here it is:

    ;

    That was difficult. Must be time for coffee..

  71. Example by Anonymous Coward · · Score: 0

    int main()
    {
    }

  72. The common mistake by Anonymous Coward · · Score: 0

    The mistake is "read the code". If you want to evaluate the stability of an house you check the project documents, you don't check the walls!

  73. Spaghetti code ... the root of all evil by Anonymous Coward · · Score: 0

    #1 problem) Spaghetti code is the root of all evil. It is the biggest problem that I constantly run into.

    1) New devs have a hard time getting up to speed.
    2) Even the original dev starts having trouble mainting the app if they have to work with it after a two year hiatus.
    3) Unit testing never happened and if it did, it is a poor excuse for unit testing that gets to 50% of the code if lucky.
    4) Ya, go ahead, maintain those unit tests!
    5) Those that are not the original developer have ahard time maintaining the code. Much like (2) above but it is much worse.

    #2 problem)
    No mentoring program for new devs.
    I don't care how good you are out of college. You don't have real world experience. And all the little crap you do wrong doesn't get better on it's own. Mentoring (through peer reviews hopefully) will turn a good recent grad into an excellent software engineer. I've seen too many people not get mentored or properly mentored just to be half of what they should be 5 years later.

  74. Lisp by Jmc23 · · Score: 1

    (loop (print (eval (read))))

    --
    Don't complain about syntax, grammar, or spelling. There is no.hell like input on android.
  75. simple and elegant code thats publicly available by Anonymous Coward · · Score: 0

    http://groups.engin.umd.umich.edu/CIS/course.des/cis400/c/hworld.html
    /* Hello World program */

    #include

    main()
    {
            printf("Hello World");

    }

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

    1. Re:Elegant code != Good code by Anonymous Coward · · Score: 0

      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.

      I think that's a textbook description of INelegant code, but whatever.

    2. Re:Elegant code != Good code by geekoid · · Score: 1

      Yes, elegant code does equal good code.
      Your example is not elegant.

      --
      The Kruger Dunning explains most post on /. http://en.wikipedia.org/wiki/Dunning%E2%80%93Kruger_effect
  77. code with a bow tie and suit ? by ElRabbit · · Score: 1

    or just a nice shirt, if it's casual code day

  78. Re:GPS? Are you kidding? by Anonymous Coward · · Score: 0

    Fortran is the best language to write mathematical formulas. It's a FORmula TRANslator, after all. Auto-converting elegant FORTRAN to C is the most stupid thing you could do, and probably that's why the vendors did it.

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

    1. Re:I am one of those guys by Reapy · · Score: 1

      Wow thank you.

      I am just like yourself, although only 11 years in now. I intentionally write things to be as clear as possible. I avoid trying to use any 'tricks' that are particular to a language like the plague since I will often times have to swap between languages for different periods of time and it reduces the time it takes me to understand what I've been writing. Not to mention that passing the code out to someone who does not primarily use that language or is just learning, there is less of a chance they will misunderstand that part of the code if they have to use it or modify it.

      I like to write things straight and simplistic on purpose, but I also get that same feeling of contempt for not getting 'fancy' with what you I write.

      But I guess this is like anything, when some of the great minds explain something amazingly complex in just a few short sentences, is totally clear, and makes the concept seem like that with which a five year old could understand, it is easy to dismiss it. Yet getting to that simple explanation was anything but simple.

    2. Re:I am one of those guys by gweihir · · Score: 1

      I really do not get it, but there seems to be something wrong with a lot of programmers. I see this attitude you describe a lot (fortunately, mostly in teaching, and when I code I do it as "chief engineer" and can tell people off). It is about the most serious misunderstanding of what coding is about that you can have. Yet still you find it everywhere.

      --
      Most ACs are not even worth the keystrokes to insult them. Be generically insulted by this and ignored otherwise.
    3. Re:I am one of those guys by gweihir · · Score: 1

      Indeed. And the fun thing is that in my experience, clean and clear code is not even slower, but often faster and less resource-hungry. And you can optimize it! I do not mean optimize everything, but as it is clear you can find the few points where optimization pays off and do carefully isolated and documented optimizations just there.

      --
      Most ACs are not even worth the keystrokes to insult them. Be generically insulted by this and ignored otherwise.
    4. Re:I am one of those guys by oamasood · · Score: 1

      However, now with the rise of Ruby, Python, and other languages which emphasize simplicity and readability, I think that attitude is changing.

  80. Any code that's not my code by alta · · Score: 1

    My stuff gets the job done.

    I generally put enough notes in that someone could come behind me and see what's going on. And where I don't I try to use pretty obvious variable/function names. But it's usually not to pretty. And it's in PHP so most of yall would say it's not even actually CODE.

    --
    Do not meddle in the affairs of sysadmins, for they are subtle, and quick to anger.
  81. Punch cards! by cripkd · · Score: 1

    Jut use punch cards and make the holes butterfly-shaped. The just add some curls and leaves with a pink marker on the margins.

    --
    Curiously yours, crip.
  82. Quine-Relay by rwa2 · · Score: 1

    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.

    For some reason, your comment reminds me of this:
    https://github.com/mame/quine-...

    Code doesn't get much more beautiful than:
    https://github.com/mame/quine-...

  83. Anything expressed in... by Arroc · · Score: 1

    this notation

  84. Ruby by Anonymous Coward · · Score: 0

    Pretty much anything written in Ruby usually seems elegant to me. Ruby is one of the few languages that really encourages doing things in the most simple, direct way possible. And because Ruby has such a well thought out and consistent way of doing things, you rarely see obtuse, ugly solutions to problems, designed to work around the way the language is supposed to work. Ruby is the one language I have run across where I do not dread reading other peoples' code out of fear of having to decipher incomprehensible gibberish. With Ruby, I can usually understand another person's code as easily as my own. Unless of course, they are the type of coder that likes to be "clever" with the code they write, but situations like that are hopeless either way.

  85. 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
  86. I always try to keep in mind by pmoleri · · Score: 1

    Programs must be written for people to read, and only incidentally for machines to execute. - H. Abelson

    Also Zen of Python has a bunch of interesting points.

  87. Anything but a C++ template. Forth is better by Anonymous Coward · · Score: 0

    Forth is better. I've seen more mangled code from templates to get around all of the data casts. It's *GREAT FUN* to debug.
    Oh yeah, that and systemd!

  88. SSL/TLS Certificate validation by Anonymous Coward · · Score: 0

    What I really want to see is good code that does certificate validation. The apple goto fail being an example of bad code.

  89. Read The Story of Mel by Anonymous Coward · · Score: 0

    http://www.catb.org/jargon/html/story-of-mel.html tells the best story I know regarding someone who best optimized code based on an intimate knowledge of the hardware (a machine with Drum memory) on which he was working.

    Here's an excerpt:

    Mel never wrote time-delay loops, either,
    even when the balky Flexowriter
    required a delay between output characters to work right.
    He just located instructions on the drum
    so each successive one was just past the read head
    when it was needed;
    the drum had to execute another complete revolution
    to find the next instruction.
    He coined an unforgettable term for this procedure.
    Although “optimum” is an absolute term,
    like “unique”, it became common verbal practice
    to make it relative:
    “not quite optimum” or “less optimum”
    or “not very optimum”.
    Mel called the maximum time-delay locations
    the “most pessimum”.

  90. For me by Anonymous Coward · · Score: 0

    Elegance should mimic somewhat elegance and simplicity as sought by the great physicists, Dirac in particular - that the rules of nature should be defined simply or elegantly.

    For me

    Elegant code = mimics at some level what it is actually representing. The algorithm's earlier brach, not the fork itself should be implicit. So you can clearly see that it's a sorting algorithm by just looking at it, and when you drill further you see the nuts and bolts. That's elegance for me.

    So, for me:

    Elegant code = grabs your attention as understandable + works efficiently, reliably and quickly.

    At least that's what I'd strive for if I was still a programmer. Time to get back into the game.

  91. 209 comments by Anonymous Coward · · Score: 0

    means 209 different opinions.

  92. Re:Elegant Code? by Buchenskjoll · · Score: 2

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

    --
    -- Make America hate again!
  93. conditional operator by ZombieBraintrust · · Score: 1

    Does anyone else hate the conditional operator. It replaces
    if (a > b) {
    max = a;
    }
    else {
    max = b;
    }
    with
    max = (a > b) ? a : b;

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

    2. Re:conditional operator by Anonymous Coward · · Score: 0

      Nice!

  94. Nimble code by Anonymous Coward · · Score: 0

    Code that is easily adaptable and modifiable to accommodate ever changing requirements and new functionality by a plurality of the coders expected to work on it.

    Long term malleability and adaptability is what makes code and APIs great.

    If it is hard to change or use, it is not elegant.

  95. No weirdness by Anonymous Coward · · Score: 0

    Code which is easy to reason about. Where each peace of code has a clear task, with as few special cases as possible.

  96. Typically: terseness by Erich · · Score: 1

    Low-complication implementations of functionality are typically more elegant.

    --

    -- Erich

    Slashdot reader since 1997

  97. All of the code Ritchie wrote for his book... by Anonymous Coward · · Score: 0

    I allways enjoy scanning the pages of "THE C PROGRAMMING LANGUAGE" the original (or 2nd) by Dennis Ritchie. The world never gave him proper respect! RIP.

    To me elegant code is code that's enjoyable to read!

  98. In the olden days by Anonymous Coward · · Score: 0

    Back in the dark ages (early in the first Reagan term) when I was studying CS at Washington University, one of my favorite professors offered the following definition.

    "The elegant solution is the simplest one that completely satisfies the requirements."

    These have been the words I have tried to code by for the past three decades. Most of what I would consider inelegant code comes from either not taking or having the time to simplify things or ignoring the "completely satisfies" part and figuring that a Pareto solution is good enough.

    Generally, well written code with useful variable names does not need much documentation (how often have you found comments that don't quite match what the code actually does?). Where performance an optimization is critical (and developers often optimize the wrong things), good documentation is crucial (and good teaching opportunity) for explaining clever techniques that improve speed.

    While it is bad to be dogmatic about this, the general rule that any module/routine should fit on a single printed page is a useful construct. Complex or repeated operations can usually be factored into their own routine so that each is kept small enough to be understandable and maintainable.

  99. Buzzword-compliance is not elegance by Anonymous Coward · · Score: 0

    Unfortunately, to the great many programmers who specialize in terminology and syntax but can't solve actual problems, elegance is in complying with "best practices", "new technologies", buzzwords, terminology and pet methodologies. And most of it is impractical. The code they create is fractured, overly complex, and doesn't solve real-world problems on a schedule or on a budget.

    An elegant solution is one that anyone can pick up and understand, and doesn't lock anyone into any particular technology unnecessarily. An elegant solution gets the job done with the least amount of technology, not the most. An elegant solution delivers what the client asked for, not what the resume benefits by.

  100. Essays on J by DavidHumus · · Score: 1

    Most of the essays like this one here: http://www.jsoftware.com/jwiki... .

  101. Re:GPS? Are you kidding? by Anonymous Coward · · Score: 0

    Hey! I wrote some very early GPS computational code in 1971-1972 and it wasn't crap. FORTRAN was the default for engineers and mathematicians as it was the language we learned in college in the early 1960s and there weren't any real alternatives to it anyway. If some idiot in later years decided to let some bit of software automatically convert FORTRAN source to C source (given the syntactic, structural, and philosophical differences in the languages), blame him for the code being crap.

  102. Functional Code by allo · · Score: 1

    just saying

  103. HAKMEM by Anonymous Coward · · Score: 0
  104. But time is a finite resource by Anonymous Coward · · Score: 0

    The original architects, usually, don't work for themselves. They don't get to decide how much time is allocated to the project. While there is a negotiation, there is also a reality.

    And time to market matters, a lot. Compare a maintainable-but-late product to a good-enough-right-now product in the open market and which one do you think will win? (hint, if you pick "A," you probably aren't the CEO of a successful business).

    Perfect software is achievable, and prohibitively expensive. Good enough software has long-term maintainability costs, but it also has a long-term in which to pay those costs.

  105. Re:GPS? Are you kidding? by Grishnakh · · Score: 1

    I'm not an expert on any compiler code, but I thought that gcc was actually comparatively new, as it used to be called "egcs", and was different from what used to be "gcc", and was a newer project. At some point, the gcc team decided to simply adopt egcs as the new gcc and dump the original as it was too old and crufty.

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

  107. Code that is easy to read. by Ziggitz · · Score: 1
    • Self explanatory method names.
    • Low cyclomatic complexity
    • Good test coverage

    Good code should be easy to follow with no function taking more than a minute to read and understand with meaningful names that can be trusted to do what they imply they do. Each function should ideally have 4 or less paths through the code with greater complexity being shoved into another method. Test Coverage is sexy. There is nothing that will make me hate a codebase more than when I have to dig deep down into a code base and find that one little variable that's getting set to null in some peripheral object instead of what it's supposed to be after hours of debugging.

    --
    There is no memory shortage. yes I have heard of XFCE. Go away.
  108. 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).

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

  110. ((lambda (x) (x x)) (lambda (x) (x x))) by Anonymous Coward · · Score: 0

    Now /this/ is what I call elegant code.

    Haven't found out what it does though....

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

  112. ftfy r.e. idioms... by Fubari · · Score: 1
    "...and at the end of the day, is somewhat more readable."
    There, fixed that for you :-)
    (Unless I missed a use whoosh; here... don't think so because your post seems sincere.)
    At the point where you're using Perl idioms to slurp an entire file into memory... is the array reference really the hard bit to understand here? :-)

    I'll grant you the point about not needing to be a reference at all because of function locality.
    But my $x = [ ]; and my @x; both establish an array.
    push is actually suggestive of what it does, unlike the input operator's ability here @x = <$fileHandle>; to return all lines in a file as a list context... That is as obscure as references; if your target audience is expected to know how that aspect of the input operator works I wouldn't be too hard on your coworker for expecting them to understand array references.

    Oh so this!

    I have had to tell cow-orkers to knock that crap off. They've got the job, and from this point on the only thing that will impress us is code that can be maintained by anyone else on the team, even if they have not set eyes on it in years.

    Programmer did:

    my $something = []; open my $filehandle, '<', $filename or croak "Can't read file"; push @$something, <$filehandle>; close $filehandle;

    How about:

    open(my $filehandle, '<', $filename) or croak "Can't read file"; my @something = <$filehandle>; close($filehandle);

    Much more succinct, gets rid of a pointless use of an array reference (seriously, it was used as an array in that function only, never passed around or returned), and at the end of the day, is far more readable.

    1. Re:ftfy r.e. idioms... by PatMouser · · Score: 1

      All valid points, but I still say that one scans better than the other, and at 3 AM that becomes an issue. Especially when I get woken up by one of our lower tier folks who is trying to figure out why it doesn't work, asking me to decipher it for him. Turns out the issue was that he failed to check whether the open had succeeded. It didn't. So I added the croak and did some more repairs, with a rewrite for legibility's sake coming up.

      This guy never met an array or hash that he didn't turn into a reference just for gits and shiggles. Seriously. Every single damned one. I don't think I ever saw a native @ or % in his code (except for @_).

    2. Re:ftfy r.e. idioms... by Fubari · · Score: 1

      3am? ouch :-)
      I will grant you all points, increased clarity (especially in production code) is a win.
      I spend most of my time with Java these days, and rather miss the brevity of perl.
      Bonus points for croak (and error handling in general vs. "But... but... it always works on my dev image!").
      I will also concede the reality of a challenging coworker.
      So... have they gotten any better over time?

    3. Re:ftfy r.e. idioms... by PatMouser · · Score: 1

      He's no longer with us thanks to his horrible attitude. It was all about coding in job security and being perceived as some sort of guru, complete with the dribbling out just enough information to keep you guessing.

      Upon being presented with the coding style guidelines and team best practices, his response was "we do things differently, I'm not going to change how I code."

      That should have been a red flag.

      As for Java, I could be so lucky... :)

  113. gnu coreutils? by Boawk · · Score: 1

    wc, cat, sort, head, tail, split et al. Source here.

  114. Re:GPS? Are you kidding? by jeremyp · · Score: 1

    I'm not an expert on any compiler code, but I thought that gcc was actually comparatively new, as it used to be called "egcs", and was different from what used to be "gcc", and was a newer project. At some point, the gcc team decided to simply adopt egcs as the new gcc and dump the original as it was too old and crufty.

    If you call 1997 new, then yes it was new. Except that egcs was based on a gcc snapshot.

    --
    All I want is a secure system where it's easy to do anything I want. Is that too much to ask ~~ Randall Munroe
  115. Handheld GPS code as benchmark of elegance? by smcdow · · Score: 1

    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.

    No you don't. Trust me, you'll be very disappointed.

    --
    In the course of every project, it will become necessary to shoot the scientists and begin production.
  116. Many small pieces by geekoid · · Score: 1

    that is easy to read.

    No magic numbers, no overly clever recursion, consistent implementation and easy to read names.

    --
    The Kruger Dunning explains most post on /. http://en.wikipedia.org/wiki/Dunning%E2%80%93Kruger_effect
  117. Less is more by Redlemons · · Score: 1

    Elegant code is no code.

    1. Re:Less is more by Anonymous Coward · · Score: 0

      Elegant code never needs more than 1 line.
      It it takes 2 or more then it need's a rewrite!
       

  118. J is compact and elegant and so is the source. by jnkr · · Score: 1

    http://www.jsoftware.com/source.htm

    See the parser in p.c.

  119. Lisp's eval by istartedi · · Score: 1

    Lisp's eval

    It'll take you a while to get it. You'll have to be asking yourself the question, "What's all the fuss about Lisp?". You'll set it aside for a while. You could easily dismiss it for glossing over some details such as the actual (read) function; but when you "get it", you'll get it.

    Stumbling blocks: prefix notation. A lot of people say it's the ()s that make Lisp hard to read; but it's really the prefix notation. Another stumbling block is the lame explanations for what (quote) does. People say it says "don't evaluate me" and while technically true, it doesn't answer the question. A better answer is, "returns a syntax tree ". A more detailed answer is "returns a list which serves the same purpose as a syntax tree. This is handy because every function in Lisp takes that same kind of tree as an argument, so it's handy for writing macros".

    Like many people, I've never written a line of Lisp that runs anything, let alone an actual piece of professional code in Lisp. Also like many other people, I've found value in studying it and applying the concepts elsewhere.

    Another person said "Forth" and they've also got a point. In some ways, Lisp is the dual of Forth. The postfix notation of Forth can cause just as much confusion as the prefix in Lisp; but that doesn't mean they aren't elegant in their own ways.

    --
    For all intensive purposes, "whom" is no longer a word. That begs the question, "who cares"?
  120. Re:GPS? Are you kidding? by Anonymous Coward · · Score: 0

    As someone who got lost somewhere deep in a single sentence (which consumed three whole screen-width lines)

    Stop reading on your cell phone, or turn off beta. For me it fits into less than two lines.

  121. The most elegant code by Anonymous Coward · · Score: 0

    Is no code at all.

  122. The most elegant code I ever saw... by Anonymous Coward · · Score: 0

    ...was a program that kept a session alive in a modem pool. With the goal of essentially "reserving" a spot in that modem pool (sessions were routinely over-subscribed).

    It had to use absolutely minimal resources, never draw attention to itself, have a basic user interface, and never crash or fill the command buffer. It did all that in 3 lines of code.

    And no, I cannot post the code. The fundamental purpose of the program was, ah, "not officially sanctioned". We destroyed the program and never talked publicly about the program after. We had our reasons and agenda and the system gatekeepers had another. Sometimes that's just the way things are. But it was beautiful piece of code and truly elegant. Best I ever saw.

  123. My thoughts are... by djtremel · · Score: 1

    I'm all for writing awesome properly indented and commented code... speed, and the need to get most things done yesterday, leaves me satisfied with code that works and doesn't require some crazy "hack" to get around a problem I don't have time to solve the right way.

  124. Job security by dont_jack_the_mac · · Score: 1

    spaghetti code = job security

  125. Lions' Commentary by crepe-boy · · Score: 1

    Maybe a bit longer that you want, but the UNIX 6th Edition source code, as presented in John Lions' commentary book is excellent reading. Clean, functional code with some well-documented "wow" moments.

  126. Re:Elegant Code? by Anonymous Coward · · Score: 0

    What race is that? Please make sure to mention the caste system in your response.

  127. Easy to read by manu0601 · · Score: 1

    In my opinion, elegant code is easy to read. Functions are short, you can look seem all function body on a 25x80 terminal. Function and variable names are coherent and self-explaining, style is uniform, and comment exist where they are needed.

  128. nice code by Anonymous Coward · · Score: 0

    I've been reading over the MooTools core recently and there are many interesting concepts and techniques going on there.
    Most elegant though, it's got to be FORTH. That one is just inspiring by defining such a simple machine and the framework for calculations that can master any processing environment..

  129. Re:GPS? Are you kidding? by Anonymous Coward · · Score: 0

    I wonder how many slashdotters browse all websites maximized. I'm sure a not-insignificant number use their monitor in portrait mode.

    I don't do portrait mode, but I also rarely do maximized windows, since I multitask.

  130. Simple, concise, clean, no DRY violations and self by wei2912 · · Score: 1

    This pretty much sums up what I consider as elegant code.

  131. Was this post written by Mark Twain? by i621148 · · Score: 1

    Tom contemplated the boy a bit, and said: âoeWhat do you call work?â âoeWhy, ainâ(TM)t that work?â Tom resumed his whitewashing, and answered carelessly: âoeWell, maybe it is, and maybe it ainâ(TM)t. All I know, is, it suits Tom Sawyer.â âoeOh come, now, you donâ(TM)t mean to let on that you like it?â The brush continued to move. âoeLike it? Well, I donâ(TM)t see why I oughtnâ(TM)t to like it. Does a boy get a chance to whitewash a fence every day?â That put the thing in a new light. Ben stopped nibbling his apple. Tom swept his brush daintily back and forth â" stepped back to note the effect â" added a touch here and there â" criticised the effect again â" Ben watching every move and getting more and more interested, more and more absorbed. Presently he said: âoeSay, Tom, let me whitewash a little.â

  132. Perfect code? by Anonymous Coward · · Score: 0

    Doom 3 Source
    https://github.com/id-Software/DOOM-3-BFG

  133. Code that I can hand off.... by Anonymous Coward · · Score: 0

    Code that I can come back to years later and understand how it works and how to interfaqce with it, or that I can hand off to someone else and they can understand how it works, or how to interface with it, with little effort.

    Code that I can easily pull out and re-use along side other code, and in other projects.

    Code that I find myself re-using and building upon over and over again.

  134. Computer Science by Murdoch5 · · Score: 1

    Things that make code hard to work on or horrible to read and understand.

    1. Over structured.
    2. Over Abstracted.
    3. Use of Object Oriented concepts.
    4. Bad comments (99.999% of developers can't write comments to save there lives).
    5. Complex loops to prevent using goto.
    6. Using pointers over arrays because you can.
    7. Using case statements in place of if's.
    8. Single line if statements with out the brackets.

    I could keep going but to sum it up quickly, all the standard "good coding" practices basically destroy code, so don't listen to your professor.

  135. Project Euler by PJ6 · · Score: 1

    Many solutions posted there are masterful examples of elegance in programming. Some are so good they may change the way you think about code.

    But to see them, you actually have to care enough to solve the problems yourself first.

  136. Elegant and efficient do not have to be opposed by Anonymous Coward · · Score: 0

    I think elegance in coding deals a lot with how smartly do you accomplish the solution of the technical challenge. Remember, code is technology, and you can put all your art to the service of solving a problem - but the solution is not only in the code. Sometimes, digging out (or flushing out) the hidden business constraints makes up for an elegant solution as well. Leave alone readability, maintanability and error handling.

  137. Re:GPS? Are you kidding? by Anonymous Coward · · Score: 0

    A GPS (and Galileo) software receiver in C++: http://gnss-sdr.org

  138. Elegant Code by Anonymous Coward · · Score: 0

    You could do far worse and not much better than to look at Kernighan & Ritchie's book about C. Here is the URL to the PDF file:

    http://zanasi.chem.unisa.it/download/C.pdf

    Arthur