Slashdot Mirror


Dirty Coding Tricks To Make a Deadline

Gamasutra is running an article with a collection of anecdotes from game developers who had to employ some quick and dirty fixes to get their products to ship on time. Here's a brief excerpt: "Back at [company X] — I think it was near the end of [the project] — we had an object in one of the levels that needed to be hidden. We didn't want to re-export the level and we did not use checksum names. So right smack in the middle of the engine code we had something like the following. The game shipped with this in: if( level == 10 && object == 56 ) {HideObject();} Maybe a year later, an artist using our engine came to us very frustrated about why an object in their level was not showing up after exporting to what resolved to level 10. I wonder why?" Have you ever needed to insert terrible code to make something work at the last minute?

133 of 683 comments (clear)

  1. Here's one... by Quartz25 · · Score: 5, Funny

    Right before I left from Microsoft: int security = *NULL; // eat it!

    --
    Most people don't get why the integral of "e to the x" is so funny. Most math majors don't have a sense of humor.
    1. Re:Here's one... by Niris · · Score: 2, Interesting

      Oh how I wish I had modpoints. That gave me a good laugh before bed :D +1 point for you, good sir.

    2. Re:Here's one... by pinkushun · · Score: 5, Funny

      Were you also responsible for #DEFINE RND_BSOD = 1 ?

    3. Re:Here's one... by ObsessiveMathsFreak · · Score: 2, Funny

      Don't be absurd. Even the lowliest coder would know enough to write #DEFINE PSEUDO_RND_BSOD = 1

      --
      May the Maths Be with you!
  2. One word.. by consonant · · Score: 5, Funny

    GOTO :-) (or is that two..?)

    1. Re:One word.. by wilx · · Score: 5, Informative

      The goto statement is very useful. Your dislike of it is irrational. Do you even know why you do not like it? Often, goto is the best solution to given problem.

    2. Re:One word.. by EvanED · · Score: 2, Insightful

      Error handling in C code is my typical example of that. It mostly avoids the need for lots of if statements to make sure that you clean up all that you need to and nothing more.

      There are other ways to go about it, but in general I'm not convinced they are better.

    3. Re:One word.. by Anonymous Coward · · Score: 3, Informative

      So, where's your example?

      Finite State Machines. They really are quite difficult to implement without goto logic and is exactly what you do when discussing theory.

    4. Re:One word.. by fractoid · · Score: 2, Insightful

      Every control structure in C++ is equivalent to either a goto or jnz plus some syntactic sugar.

      --
      Rampant carbon sequestration destroyed the Dinosaurs' tropical paradise. I'm here to help repair the damage.
    5. Re:One word.. by Derleth · · Score: 5, Insightful

      Breaking out of a deeply-nested loop, as can happen when you’re looking for a specific element in a multidimensional array. The alternative involves adding state variables and complicating the logic terribly.

      --
      How can you use my intestines as a gift? -Actual Hong Kong subtitle.
    6. Re:One word.. by Derleth · · Score: 5, Insightful

      I’m a goto-user, but this is a bad reason to use them: If you regard language features as ‘just’ syntactic sugar, why aren’t you programming in raw machine code? That is what everything eventually gets turned into anyway.

      You use gotos when the normal control structures are inadequate somehow. It doesn’t matter what the compiler does; source code is for humans.

      --
      How can you use my intestines as a gift? -Actual Hong Kong subtitle.
    7. Re:One word.. by Darinbob · · Score: 2, Insightful

      I think a lot of programmers are superstitious. They do what they teachers taught, without ever stopping and thinking about why they were taught that. So you see people instinctively avoid goto's, or forbid them outright when they get edit permission on style guidelines. I've seen some horrible stuff that avoids gotos, complicating code and making it difficult to read. They heard "goto considered harmful" and "you should prefer structured programming" and translated that internally into "thou shalt not use a goto". Some people even avoid "break" or "continue" in C because of similarity to a goto.

      Similarly, the "there shall be only one exit from a function" is often used as a tautology by some. Combine that with a prohibition on gotos (that lets you jump to the cleanup) and things get ugly.

      Granted, you can get rid of a lot of gotos with some simple language additions (such as a "finally" clause or automatic destructors), but if these don't exist the goto works just fine.

    8. Re:One word.. by zwei2stein · · Score: 3, Insightful

      Ewww.

      1) decent languages support labeled for/while cycles and apropriate "break label" constructs. It is not so different from using goto but has much better semantic meaning and thus allows neat optimalizations (with, say, paralelization in mind)

      2) if you do this kind of thing, you are MUCH better off separating lookup code to method or function and simply using return statement once you find it without having to break from cycles per se. Cleaner, more structured.

      --
      -- Technology for the sake of technology is as pathetic as eschewing technology because it's technology.
    9. Re:One word.. by Derleth · · Score: 4, Interesting

      decent languages support labeled for/while cycles and apropriate "break label" constructs.

      You often cannot develop software with the language you want, but must develop it with the language you have. C has no such features and, therefore, goto is used more often than in languages that have them. Fit the strategy to the tool.

      if you do this kind of thing, you are MUCH better off separating lookup code to method or function

      This is reasonable, but it assumes some other function can do the needed cleanup code or other data massaging just as cleanly. If the goto is being used because finding the value is an error condition, you often have to do certain things as soon as possible in the code so you do not lose important debugging information.

      And, no, exceptions are not part of C, and setjmp/longjmp is, if anything, even less likely to pass code review. An advantage of goto is that you can keep the cleanup code in the same function, visually close to the rest of the logic and sharing the same locals.

      --
      How can you use my intestines as a gift? -Actual Hong Kong subtitle.
    10. Re:One word.. by beelsebob · · Score: 2, Informative

      Yes it is, goto requires a label, and thus requires someone reading your code to go hunting for it. Return is known to push control flow to the exit of the function. One obfuscates code, the other doesn't.

    11. Re:One word.. by Anonymous Coward · · Score: 3, Informative

      Error handling in C code is my typical example of that. It mostly avoids the need for lots of if statements to make sure that you clean up all that you need to and nothing more.

      There are other ways to go about it, but in general I'm not convinced they are better.

      The most common use of "goto" in that circumstance is to enforce "only one return".

      Which is every bit the pedantic lunacy that goto-hate is.

    12. Re:One word.. by digitig · · Score: 2, Insightful

      as well as some oddly structured loops for which try/catch logic doesn't get you all the way

      Such loops are almost certainly buggy, almost certainly maintenance nightmares and I'll stick my neck out and say certainly unnecessary. The logic needs redesigning. So they are examples of dirty tricks to get code out of the door, as the GOTO poster suggested.

      --
      Quidnam Latine loqui modo coepi?
    13. Re:One word.. by Jurily · · Score: 4, Interesting

      But as below says, they make error handling an easier task as well as some oddly structured loops for which try/catch logic doesn't get you all the way

      Ugh. Magic invisible gotos FTW!

    14. Re:One word.. by hairyfeet · · Score: 5, Interesting

      I like the way my former VB teacher put it (and yes I use the occasional GOTO, but then again I learned in the real BASIC-Commodore BASIC) he said "The GOTO is like a chainsaw. yes, some folks can actually make good things, and even make really nice carvings with a chainsaw. most just make a big fucking mess."

      Of course me and him both laughed our asses off when some 19 year old tried to rip off my code and pass it off as his own. After laughing and giving the kid a big F the kid said "How do you know that he didn't steal it from me?". So he asked the kid where he learned VB and which OS and the kid said "Windows 98 and the VB I got from this class!" and the teacher projected the code onto the board and said "Now class, does anybody notice something a little...weird about this code?" and a girl popped up and said "Why are their numbers before the lines, and what is a GOTO?".

      The teach just laughed and said "once upon a time their weren't any GUIs on personal computers. All you got when you turned it on was a blinking CLI and you had to write your own programs, using VERY old syntax. The person who wrote this is used to working in teeny tiny amounts of memory and using the old style, which works just fine if you know what you are doing, but if not it'll blow in your face like Mr. Greene found out when he tried to snatch this code and incorporate it into his own without knowing how it works" he then turned to me after staring at the code for a minute and said "Atari or Commodore?" and I looked shocked and said "Commodore VIC20, but how did you know that?" and he said "because I have been around long enough to have coded on just about everything, and that looked liked Atari or Commodore code. Very efficient, but about as subtle as a chainsaw." which is when he gave me the chainsaw quote.

      So I have never forgotten the chainsaw quote, and while I can wield the chainsaw without making a mess, I saw first hand when others in the class tried to use GOTO what a mess you can make if you don't know EXACTLY what your code is doing. He caught me outside a month later and said "thanks a lot, I hadn't seen a GOTO in ages and then you come along and it spreads like the damned clap. Giving these youngsters GOTO is like handing a monkey a sledgehammer and letting them loose in a bomb factory. There is no doubt they are going to go boom, the only question is when." but what can I say, I'm just an old greybeard that was used to numbered lines and GOTO.

      --
      ACs don't waste your time replying, your posts are never seen by me.
    15. Re:One word.. by FourthAge · · Score: 4, Insightful

      Hardly pedantic or lunacy. For example, pick one of the drivers from the Linux kernel, e.g. this one. Look in particular at the "geode_aes_probe" function.

      The structure looks like a pyramid. On one side is the setup phase, on the other side is the cleardown phase. If one of the setup operations fails, then the "goto" jumps to the appropriate cleardown operation and continues from there. If the top of the pyramid is reached, then return #1 (success) is used. Otherwise, return #2 (failure) is used.

      This function could be written in C without using goto. But would it be as easy to read and as easy to maintain? Doubt it. As it is, it's perfectly obvious what you would need to do in order to add a new capability to the driver. Tricks to work around "goto" would only obfuscate the functionality.

      --
      The tao of democracy: the government you can vote for is not the real government.
    16. Re:One word.. by 91degrees · · Score: 3, Insightful

      Surely you could do that as a nested if.

      Whether that is better or not is subjective. "Goto considered harmful" has become dogma, but while your example is a very good example of goto used well, most programmers would use it to write spaghetti code. Barring the use of the keyword means that it does only get used by people who know exactly what they're doing.

    17. Re:One word.. by Hattmannen · · Score: 2, Funny

      Such loops are almost certainly buggy

      [citation needed]

      That seems a bit redundant. You just cited him, didn't you? I get the strangest feeling of recursion when someone quotes somebody else and asks for a citation...

      --
      People are not wearing enough hats.
    18. Re:One word.. by FourthAge · · Score: 5, Insightful

      I'd agree with all of that. Like C itself, goto is a powerful tool that is easily misused by beginners, but is still very useful in the right circumstances.

      --
      The tao of democracy: the government you can vote for is not the real government.
    19. Re:One word.. by Aladrin · · Score: 2, Informative

      I have not used a 'goto' statement in about 15 years now. But it's not some irrational fear. It was all due to someone saying 'there's no situation that requires a goto' and 'goto statements make code hard to read'.

      And after I used goto a little more, I realized they were correct. In any good, modern language, 'goto' is completely unnecessary and makes your code harder to read.

      If you're breaking out of a loop, you should use 'break'. If you're continuing a loop, 'continue'. If you're handling an error, throw an exception. If you're calling another piece of code, make that code a function and call it properly.

      --
      "If you make people think they're thinking, they'll love you; But if you really make them think, they'll hate you." - DM
    20. Re:One word.. by beelsebob · · Score: 2, Funny

      I agree, if you need cleanup code... But I don't write code with side effects, so there's no problem whatsoever. No side effects means no clean up.

    21. Re:One word.. by TheRaven64 · · Score: 3, Insightful

      Actually most exception handling constructs are even worse than goto, because they can unwind the stack an arbitrary amount. This is because they are taken from languages like Lisp and Smalltalk, which had accurate garbage collection and stack introspection and so could be used safely, and plonked into languages which have neither. In Java they're not too bad because you have to explicitly declare every exception that you can throw and so they become part of the interface, but they are horrendous in something in the C family. There's a nice Raymond Chen article where he writes the same bit of code with and without exceptions, and it's clear where the bug is in the exception-free implementation (error value ignored) but with exceptions it's very difficult to spot and the number of possible code paths grows alarmingly.

      Goto in C is not like goto in BASIC or many languages from the '70s and earlier, which was basically a higher-level wrapper around a jump instruction. In C, a goto statement is only allowed to jump within the current function, so it doesn't break structured programming too badly. Exceptions and longjmp(), do. Longjmp(), as it's traditionally implemented, is the worst because there is no way for any code in intervening stack frames to handle cleanup and so it's almost impossible to use without causing resource leaks of some kind. Non-local exceptions are almost as bad, because they hide multiple return paths. Sometimes it's cleaner to have two or three different return statements in a function, but with exceptions every single function call is a potential return path unless you wrap every single call in a try / catch block.

      --
      I am TheRaven on Soylent News
    22. Re:One word.. by robfoo · · Score: 5, Insightful

      I can't figure out if I'm the only sane one or the only crazy one. Especially given the 'pyramid' referred to - I don't see a pyramid unless it's rewritten to use nested ifs.

      To me, nested ifs are much easier to read - they convey the meaning/intent of the code a lot better. As in 'if this function call works, then do this. Otherwise, just clean up and exit'

      How is this so hard to understand?

      geode_aes_probe(struct pci_dev *dev, const struct pci_device_id *id) {
              int ret;

              if ((ret = pci_enable_device(dev)))
                      return ret;

              if (!(ret = pci_request_regions(dev, "geode-aes"))) {
                      _iobase = pci_iomap(dev, 0, 0);
                      if (_iobase == NULL) {
                              ret = -ENOMEM;
                      }
                      else {
                              spin_lock_init(&lock); /* Clear any pending activity */
                              iowrite32(AES_INTR_PENDING | AES_INTR_MASK, _iobase + AES_INTR_REG);
                              if (!(ret = crypto_register_alg(&geode_alg))) {
                                      if (!(ret = crypto_register_alg(&geode_ecb_alg))) {
                                              if (!(ret = crypto_register_alg(&geode_cbc_alg))) {
                                                      printk(KERN_NOTICE "geode-aes: GEODE AES engine enabled.\n");
                                                      return 0;
                                              }
                                              crypto_unregister_alg(&geode_ecb_alg);
                                      }
                                      crypto_unregister_alg(&geode_alg);
                              }
                              pci_iounmap(dev, _iobase);
                      }
                      pci_release_regions(dev);
              }
              pci_disable_device(dev);

              printk(KERN_ERR "geode-aes: GEODE AES initialization failed.\n");
              return ret;
      }

    23. Re:One word.. by microTodd · · Score: 2, Insightful

      You were very, very lucky, in an awesome way. None of my programming teachers were EVER that savvy.

      --
      "You cannot find out which view is the right one by science in the ordinary sense." - C.S. Lewis on Intelligent Design
    24. Re:One word.. by Derleth · · Score: 2, Insightful

      So formatting is worthless, then? And why do we have so many languages, many of them domain-specific? Compilers don’t care about how understandable the metaphors are or how many lines are needed to do a specific thing.

      --
      How can you use my intestines as a gift? -Actual Hong Kong subtitle.
    25. Re:One word.. by geminidomino · · Score: 5, Funny

      Pyramid? It looks more like the players' ship sprite from Galaga, rotated 90 degrees...

      Damn, now I want to play Galaga...

    26. Re:One word.. by geminidomino · · Score: 4, Funny

      So formatting is worthless, then?

      No, formatting is for successors and maintainers. As fellow coders, they're not human, strictly speaking.

    27. Re:One word.. by ArsenneLupin · · Score: 2, Informative

      That's why God invented the finally clause. Any cleanup that absolutely cannot be skipped goes into finally.

    28. Re:One word.. by basiles · · Score: 2, Insightful

      Every control structure in C++ is equivalent to either a goto or jnz plus some syntactic sugar.

      This is almost true, but I see one important exception: the exception machinery in C++ (that is the compilation of throw and catch C++ statements) is not exactly a goto (and neither is longjmp in C). And of course, any (method or function) call and return is not exactly a goto neither. Exceptions,calls and returns also change the stack pointer.

      I would also notice that computed goto (i.e. the goto *p; GNU extension of C) is compiled as an indirect jump.

      A more interesting concept is continuation Regards

    29. Re:One word.. by EvanED · · Score: 4, Informative

      How is this so hard to understand?

      It's not. But nor is code that uses goto in the idiom that FourthAge posted above.

      My objection to that code is that if you do even just three or four allocations, you start getting very large indentations pretty fast, especially if you like 8-character indentations. (They get pretty long even with 4, which is what I like!) This causes a problem if you restrict yourself to 80-columns.

      Arguably this is a problem with restricting yourself to 80 columns, but that's not entirely unreasonable even if I'd rather the limit be ~100. But guess how many your code uses? Your longest line is 109, longer even than my longer preference. Even if you use 4-character indentations, your longest line is still 80 characters.

      If you reformat your code to use 8-character indentations and 80-character column limits, your code would become a bit uglier as you'd have to wrap four lines (a couple of which don't really have a good breaking point), and hence a little harder to understand on its face.

      By contrast, the original code fits entirely within 80 characters (admittedly only just) without anything remotely like an awkward line break.

      Further, in some sense it doesn't entirely follow the flow of the code. Perhaps this is a vice and not a virtue, but I tend to think of places where there's an unusual condition (like a failed allocation) as not on the same "level" as normal control flow. In this sense, I would think of that procedure as basically linear "with some provisions for exceptional conditions". In that sense, your proposal of the cascaded ifs doesn't really match my mental model of how the code behaves -- the indentation of the normal code changes depending on how many exceptional conditions might arise, and there's not really any reason why it should by that model. By contrast, the original code matches it.

      (Incidentally, "linear with some provisions for exceptional conditions" is basically how I'd write it either in a language that supports exceptions or a language that has RAII. In the former case, there's a decent chance do just one try block for the body of the function, and in the associated catch test to see if each item is allocated in turn. (This doesn't match the structure of the real code exactly, but it's closer to it than it is to your nested-if code.) In the latter case, you'd have basically the real kernel code except that the deallocation would be in the RAII objects' destructors. Again, no nested ifs.)

    30. Re:One word.. by gid · · Score: 2, Insightful

      Heh, I rewrote it the exact same way--before I scrolled down to this comment. Of course the 8 space indents make it a bit wide, but really, who uses an 80 column display anymore?

    31. Re:One word.. by Bakkster · · Score: 3, Insightful

      You use gotos when the normal control structures are inadequate somehow.

      This is the heart of the issue: control structures are a well defined, easy to follow, hard to fuck-up subset of the things you can do with goto. If you can do it reasonably with a control structure, you shouldn't use goto, because it makes your code more readable. If you can't, then you should consider if your program should be restructured (which is why goto is dangerous to novice programmers). If not, then you can use a goto.

      Of course, all bets are off when you're scraping for clock cycles with machine code, but that's not necessary most of the time.

      --
      Write your representatives! Repeal the 2nd Law of Thermodynamics!
    32. Re:One word.. by inviolet · · Score: 2, Informative

      From the linked article:

      People have asked why I don't like programming with exceptions. In both Java and C++, my policy is:

      • Never throw an exception of my own
      • Always catch any possible exception that might be thrown by a library I'm using on the same line as it is thrown and deal with it immediately.

      I have done code that way, before exceptions came into vogue. To do it right, you've got to have many many many error-checking if() statements after every call to any function that could fail. That could maybe be done as neatly as with exception-handling, if one was ever careful to maintain one's error-codes in a single numeric heirarchy, so as to allow 'families' of errors. The error-checking statements can then select for specific errors or for families of errors, like this: if (errorCode & ERROR_FAMILY_FILEIO).

      But that is a lot of work, and the code won't be any cleaner than with exception-handling. In fact it will be uglier because you can no longer just call a bunch of functions in a row without checking returns, allowing a single exception-handler at the bottom to catch any errors it thinks it can handle.

      Nor is the author correct in contending that 'throw' is somehow less visible or less handy or less maintainable than 'return'.

      And he won't get the very very nice exception-handling support that some languages like C# offer.

      --
      FATMOUSE + YOU = FATMOUSE
    33. Re:One word.. by MikeBabcock · · Score: 3, Funny

      If you were going to do that without goto, use a while with a break instead of ugly nested ifs.


      while(1)
      {
              if (!start_condition) break;
              action1();
              cleanup1();
              if (!test_condition1) break;
              action2();
              cleanup2();
              if (!test_condition2) break;
      }

      And so on ... it basically gets you exception handling formatted code. Of course, goto is probably still cleaner :)

      --
      - Michael T. Babcock (Yes, I blog)
    34. Re:One word.. by dcollins · · Score: 3, Informative

      "How is this so hard to understand?"

      For me, it's hard to understand because your most highly indented lines wrap off the edge of the window, back to the left margin, wrecking the indentation cues. In an IDE, it sets a limit on how many conbditions you can check before having to scroll around to see the whole function.

      I used to work at a company where this was the standard and I was never fond of it.

      --
      We know where leadership by an anti-intellectual "strongman" who scapegoats minorities and likes boisterous rallies goes
    35. Re:One word.. by suomynonAyletamitlU · · Score: 2, Insightful

      I can understand what you mean (and your code) and that's probably how I would have written it that way too, but I have to say that the goto code is more elegant.

      Indented code is very useful when you are trying to look at logical levels, but at the same time, it makes it difficult to track the forward flow of code, especially when each step of indentation is very small. For example, in that code, you never have lines that stick out--you have the previous if(...) and then the next if(...) right below it, competing for attention, when in fact it may not even be called next if the statement equates to false. In the original code, the conditional and the code to be run are fairly distinct. You can see "This is what happens normally" and then, having that in hand, go back and track where each error goes, and then you say "Aha, they all come back to the same place, it's just that the closer you got to finishing, the more you have to undo."

      It may be personal preference but I have to say, when things line up, they're easier to understand; too many indentations per line of code is distracting.

    36. Re:One word.. by shutdown+-p+now · · Score: 2, Insightful

      But why use a loop + break, when your loop isn't really a loop (i.e. it only executes once)? Every time I see this trick, it makes me cringe: it is just a goto in disguise, and its sole reason for existence is that disguise! If the given situation is best handled by goto (and there are many such cases), then don't be shy and just use it.

    37. Re:One word.. by Alpha830RulZ · · Score: 2, Insightful

      I did years of work in Business Basic, and we managed to generally avoid go-to's even back then. Plenty of gosubs, but we tried to avoid the goto's.

      I have managed to avoid using a single goto since then. It's been 21 years, and at least half a dozen languages. I don't even recall being tempted or wishing I could.

      --
      I was taught to respect my elders. The trouble is, it's getting harder and harder to find some.
    38. Re:One word.. by hairyfeet · · Score: 2, Interesting

      Don't I know it. Mike was a blast to have as a teacher. He was a former Navy man who coded for DoD in the 80s and got burnt. One of the funniest part was at the beginning of a class he would whip off some chunk of code that would explain what he was doing that day and it would NEVER work. He would then project it on the board, and then after finding out what class he was teaching ATM, like say VB, he would go

      "okay...this is C++, that isn't gonna work there /replaces with VB code/ and that is Java, which I taught last class /replaces with VB code/" and after a couple minutes of this talking to himself and replacing code it would work beautifully. He just knew so many languages and taught so many classes he would get a little "off" at the very first of the class and need a minute to get his groove back. He was a great teacher and really stressed understanding exactly what the code was doing step by step. He said if you understood what the code was actually doing, instead of just learning to regurgitate the language, then your code should be easy to maintain. He also stressed good commenting so that those that come after you could see how your logic flowed on a particular implementation, and could easily pick up where you left off.

      He was a real blast, and could give you a lengthy conversation on just about any language ever written. It was great having a teacher that knew so much about coding and could really push you to learn and do more. I may be a PC repairman and thus rarely get to code anything, but his method of working the process to hunt down bugs by always working at the simplest level (which he demonstrated by having one of the kids who thought he was a "network wizard" try to diagnose a problem with a desktop. Turned out Mike had unplugged the network cable and the kid never thought to check because he was too busy doing ping, checking services, etc) I still use to this day to work my way through an irritating bug. Just a great teacher.

      --
      ACs don't waste your time replying, your posts are never seen by me.
    39. Re:One word.. by julesh · · Score: 2, Insightful

      Finite State Machines. They really are quite difficult to implement without goto logic


      int state = BEGIN_STATE;
      while (state != EXIT_STATE)
      {
          switch (state)
          { ...
              case SOME_STATE_OR_OTHER: ... do something ...
                  state = NEXT_STATE;
                  break; ...
          }
      }

      I fail to see the problem. Or there are table driven solutions that are much more amenable to automatic code generation.

    40. Re:One word.. by EvanED · · Score: 2, Insightful

      It forces one to keep nested ifs to a minimum, the bane of testing and reading comprehension.

      My biggest problem with 80-character limits is that if you have reasonably descriptive identifiers, they tend to be a little long, and so it's not all that hard to go beyond 80-characters even if you are only a couple levels deep in code. If you're in a language with function definitions inside of a class like Java or Python, you've already got two levels of indent to your function body before you've even started writing actual code! With 8 character indents, that's 20% of your line width already gone. If you have an if statement in two nested for loops (not at all unreasonable), that's 5 indent levels and half of your line width! If you then make a function call with two parameters, save the return value, and your average variable length is 8 characters, you're at 80 characters; and that's not even that long of a line, even for someone like me who likes to use a lot of explicit temporaries.

      The other thing is I tend to view line breaks as having a pretty high cost, especially if there are a couple related lines in a row. If you are doing similar operations two or three times in a row, it's nice to see the parallel structure, and adding line breaks obscures that quite a bit. (I used to try to line up operators in such cases, but I rarely do that any more. :-))

  3. pretty much everytime I write in by buswolley · · Score: 2, Insightful

    VBA

    --

    A Good Troll is better than a Bad Human.

  4. Balancing act by Tubal-Cain · · Score: 4, Interesting

    If you have short deadlines, you end up with issues similar to the bugs Ubuntu needs to smooth out every release. If you go with "It'll be finished when it is finished", Your stable releases can become ridiculously out of date between versions. Debian did a good thing by abandoning the open-ended release cycle in favor of the extremely long but predictable two-year deadlines.

  5. University Assignments. by Anonymous Coward · · Score: 5, Funny

    Once I had an assignment due and at the last minute before being evaluated, realized I had made a huge mistake, even though the code looked OK...

    Too much time playing games in class and I was about to fail the course unit if I didn't pass that one test (right at the end of a semester)

    So I ran the program, adjusted the output in a word processor, saved it as a file and threw some code hidden in the comments that read the file, outputted it and exited.

    Three minutes later my code was evaluated... I was the only one who passed.

    Fortunately, no one investigated too carefully at the time why I was the only one who passed, because after trying to fix the code later in my own time, I realized the source data we were all supplied was corrupted.

    Inevitably, Later the same lecturer came to the same conclusion when his program didn't work either and cornered me to ask why mine worked (of course he was suspicious). Thinking quickly, I told him my source data was corrupted and that I fixed that first so my program would work. I don't know if he believed me, but he accepted the story.

    Fortunately, I got away with it and I got to keep the pass.

    1. Re:University Assignments. by LaskoVortex · · Score: 2, Interesting

      We discovered that trick in O-chem lab too. You start with the percent yield to get an A on the lab and then back calculate your intermediate yields and amount of product you expected from the reagents you weighed. Fond memories.

      --
      Just callin' it like I see it.
    2. Re:University Assignments. by mrsurb · · Score: 2, Interesting

      What I learnt in Physics: First draw your lines-of-best-fit, THEN plot your points.

    3. Re:University Assignments. by Kentari · · Score: 2, Interesting

      This works well, until the teacher supplies clocks that have been tampered with to induce a 10% systematic error. You get to guess how many correct values of g turned up in that experiment... And who passed it.

    4. Re:University Assignments. by consonant · · Score: 3, Funny

      Similar story.

      In one of my "Intro to C" mid-term exam, one of the (sit down in the 'puter lab and spew code type) assignments was a simple string manipulation exercise. After I was done with the program, while sitting around waiting for the output-verifying lab drone to come over to my place, I noticed all she was doing for the other folks with the same assignment question was key in the same series of words as test inputs. I saw this, and quickly whipped up another little program that basically displayed a prompt, and did a printf("{hard-coded desired output for same set of words}"); and ran this piddly little pile of 'code' when she stopped by my machine.

      Sadly, I passed..

    5. Re:University Assignments. by Aladrin · · Score: 3, Interesting

      You laugh, but that's the basis of 'Test Driven Design'. :D You were only supplied with 1 test, and you passed it. Had their been more tests, your code would have had to be what was really wanted.

      I've started to think about how a class could be run like that... Create a series of unit test sets that progressively test more of the program. For each assignment, give the students the next set of tests and have them code to make the tests pass. In the next class session, work to show everyone how to make it happen, then give the next set.

      --
      "If you make people think they're thinking, they'll love you; But if you really make them think, they'll hate you." - DM
    6. Re:University Assignments. by TheRaven64 · · Score: 4, Interesting

      My Physics teacher caught me doing that once. He pointed out that the intended learning outcome of the experiment was to understand the relation between the properties being graphed, and if I already understood this well enough to work out what the results should be then I had achieved the objective. One of the few teachers I've had who really understood what education was meant to be about.

      --
      I am TheRaven on Soylent News
    7. Re:University Assignments. by GTarrant · · Score: 2, Interesting

      In one of my ASIC design classes, it was practically impossible for the professor to really go through everyone's design and ensure that they all worked properly - they were far too complicated. Likewise, it was difficult for students to ensure, while designing things, that the chip itself also worked as intended, because it was an error correction algorithm being implemented, so you had to sort of KNOW what a desired output would be. So the professor gave a sample input, and the intended output for this input, so that people could make sure their chips worked when they would run them in the design software.

      On the turn-in day, everyone turned in their huge heaps of paper that covered their design - again, practically impossible for the professor to 100% go through. Included also was a printout of everyone's signals within the chip - intermediate ones, and the final output. And of course, >95% of the things turned in gave the correct output and had everything correct inside.

      So the professor starts his lecture, and then stops and says "OK, everyone up!" And we headed to the computer lab, where he made everyone sit down in front of a computer, one by one, load up their chip, and gave a new input string (maybe 300-400 bits), and made each person run it.

      Approximately half the class had the output of their chip be the same output for the original "sample" input he had given so people could test - that is, their entire big ASIC (because it had to LOOK complex or it would be too obvious it didn't do anything) was essentially a giant set of fake elements which actually did nothing except give the appropriate output - for the ONE sample input.

      I have to admit, mine worked for the original input, but when he gave the new input, my output was correct for the first 399 bits - but the 400th was incorrect. It should have been a 1, I had a 0. It seems that no matter what the input was, my last bit (regardless of the number of input bits) had a stuck-at-0 fault. But since his sole sample input had a 0 as the final output bit, I never detected the fault. However, in this "second sample", the last 30 or so output bits were all 1's, and the difference between 29 '1" bits in a row and 30 "1" bits in a row in terms of looking at a long line quickly (as the professor was) is not noticeable. I saw it, but the professor didn't, and I got credit for the chip.

    8. Re:University Assignments. by geminidomino · · Score: 4, Funny

      To this day I continue to find typos in my code but less and less bugs-in-libraries.

      That's because the ratio of code-bugs to library-bugs increases with the programmer's age, even if both the code and the library remain unchanged. </zen>

  6. Really? Not Slashdot's fault, if so... by Anonymous Coward · · Score: 2, Insightful

    The Gamasutra article is dated August 20, 2009. I doubt any Slashdot contributor submitted a link to a 2009 story back in 2000.

    1. Re:Really? Not Slashdot's fault, if so... by fractoid · · Score: 4, Funny

      John Titor sent it just before disappearing.

      Where'd he get to anyway?

      --
      Rampant carbon sequestration destroyed the Dinosaurs' tropical paradise. I'm here to help repair the damage.
    2. Re:Really? Not Slashdot's fault, if so... by Trahloc · · Score: 4, Informative

      He's fighting in the civil war we're apparently not having, guess he fixed our timeline.

      --
      The Goal: A long simple life filled with many complex toys.
    3. Re:Really? Not Slashdot's fault, if so... by fractoid · · Score: 2, Funny

      I knew it! It really WAS true!

      --
      Rampant carbon sequestration destroyed the Dinosaurs' tropical paradise. I'm here to help repair the damage.
    4. Re:Really? Not Slashdot's fault, if so... by smash · · Score: 2, Interesting

      Not having - yet.

      --
      I run: Windows, OS X, Linux, FreeBSD. Just because you have a hammer, doesn't mean everything is a nail.
  7. Re:Wow. Talk about old news. by melikamp · · Score: 5, Funny

    The editor might have approved this submission just to meet some kind of deadline or a minimum requirement.

  8. Wolf 360 hack by anss123 · · Score: 3, Interesting

    The deadline is looming, I can't spend much more time on this. So, I did the unthinkable -- I packed the controller id into the pointer parameter. I marked it as a horrible hack in a 4-line all-caps comment, and checked it in.

    Does not sound so horrible, just make sure the 1,2,3,4 pointers never point at anything "free()"able and it'll work fine.

    BTW, is that Wolf 360 game out?

    1. Re:Wolf 360 hack by andy_t_roo · · Score: 2, Funny

      my favorite hack is doing object click detection by rendering objects in a function pointer (4 byte pointers, rgba colour buffer .... ) -- when you click, a render pass is done with no lighting, effects, ... , and with each object coloured according <rgbaColour>object->onClick. To act on a click, read of the colour of the pixel under the mouse, and call it :)

      (oh, and solaris lies about giving you rgba -- it only gives you rgb -- my code would work on one of the uni servers, but not on another)

  9. Wrong question by julesh · · Score: 5, Insightful

    Have you ever needed to insert terrible code to make something work at the last minute?

    Wouldn't "have you ever shipped a product without needing to insert terrible code to make something work at the last minute?" be a more sensible question?

    1. Re:Wrong question by Opportunist · · Score: 4, Funny

      Probably. But reading a stream of "nope", "sorry", "you're kidding", "good one" ... answers leads to a lot of redundant mods but no good entertainment.

      --
      We used to have a Bill of Rights. Now, with the rights gone, all we have left is the bill.
  10. Never by ChienAndalu · · Score: 3, Funny

    My boss however *only* does coding tricks. And he puts them in one big 1k line function.

    And is proud of it.

  11. Re:Wow. Talk about old news. by shish · · Score: 5, Insightful

    This is one of those stories where the story isn't the point, it's the comments that are worth reading, so it's only a problem if we have the same comments :-P

    --
    I mod down anyone who says "I will be modded down for this", regardless of the rest of their comment
  12. Deadline is not the problem by nomad-9 · · Score: 2, Funny

    In the real world there are deadlines, and it's entirely the developer's responsibility to be able to meet those deadlines without using such "dirty coding tricks". Good developers should have tested their code so as to not have serious problems to fix at the last minute, and designed it so as to be able to extend it easily.

    And putting such "if" statements is not solving the problem - not even temporarily - but hiding the bug.

    Right, nobody said it was easy. That's probably why software development is not for everybody.

    1. Re:Deadline is not the problem by 93+Escort+Wagon · · Score: 5, Insightful

      In the real world there are deadlines, and it's entirely the developer's responsibility to be able to meet those deadlines without using such "dirty coding tricks". Good developers should have tested their code so as to not have serious problems to fix at the last minute, and designed it so as to be able to extend it easily.

      Yes, because deadlines are always reasonable and never pushed up. And change orders are a myth.

      --
      #DeleteChrome
    2. Re:Deadline is not the problem by oldhack · · Score: 5, Funny

      Slashdot sorely needs "douchebag" moderation.

      --
      Fuck systemd. Fuck Redhat. Fuck Soylent, too. Wait, scratch the last one.
    3. Re:Deadline is not the problem by russotto · · Score: 4, Insightful

      Nope. Deadlines are often unreasonable. Welcome to the real world. But as a good software developer, you should be able to cope with that too, and without last-minute hide-the-problem hacks.

      Wait, you were serious? Does your hair come to points on the side of your head, by any chance?

      If I could cope with unreasonable deadlines without some sort of nasty compromise, I wouldn't be developing software. I'd be turning water into wine, holding back the tide, etc. "Good software developer" doesn't mean "miracle worker". If the time isn't there before the deadline to solve the problem correctly, either the deadline will be missed or the problem will be unsolved or poorly solved. That's close to a tautology; it's implicit in the term "unreasonable".

    4. Re:Deadline is not the problem by tholomyes · · Score: 2, Insightful

      Nope. Deadlines are often unreasonable. Welcome to the real world. But as a good software developer, you should be able to cope with that too, and without last-minute hide-the-problem hacks.

      This "real world" of yours sounds a lot like programming in a bubble. Aside from the constraints of working on top of other's libraries, operating systems, or web browsers, software will always have bugs, and they may not always be under your control. You'll have to defer the lower priority bugs to meet your release date, but without sufficient time to address them-- say, a last-minute bug that would require a significant rewrite of a subsystem that you didn't even author-- you can at least try to make the problem less painful in the meantime.

      --
      When did the future switch from being a promise to a threat? -C. Palahniuk
  13. Sucker punch by Anonymous Coward · · Score: 4, Funny

    When my deadline comes up and I haven't produced I wait for my boss to ask me for the code then I sucker punch him and run away. The trick is to hold down short term contracts and give false references and hire someone to back them up (another dirty trick). That also makes it easier to dodge the cops when your boss presses charges. It's getting harder though with all this talk of test driven development and short incremental releases. Then the trick becomes to write the most meaningless trivial unimportant tests first - but crucially tests that you can make pass quickly so you don't have to do any real work.

    (For anyone insane enough not to realise it, this is a joke. Don't try this at home...or at work).

  14. Game Art by j-stroy · · Score: 4, Interesting

    A 3d model export would break regularly screwing up the texture map orientation on certain polygons. The godawful export couldn't be fixed on the deadline, and risk management said best not to touch it cuz EVERYTHING might bust, let alone all the coders being nailed to the wall by the ship date. So I fixed the model files in an ascii editor. All the art builds that had tweaks needed this "touch" Since it was a hockey game, you can imagine how many goalie pads that was. Oh yeah, you couldn't see if the fixes were correct except in the game engine after more pipeline.

    Technically not a code fix, but still a valid solution.

  15. seen some bad shit. by Ziest · · Score: 5, Interesting

    I once worked at a Fortune 25 company in Chicago. They had this ENORMOUS mainframe program written in COBOL that ran their order inventory system which accounted for 20% of the companies revenue. All the guys who wrote this grunting pig of a system had either retired or had passed away. In the middle of the code was the following;

        *
        * We don't know what this does.
        * Please leave it alone !
        *
            SET INSIDE-INDEX TO 1.
        *
        * We don't know what this does.
        * Please leave it alone !
        *

    If this statement was commented out or removed the system stopped working. No one could find the problem. People had spent years looking for it but the code was such a mess and the documentation was so useless that they just left it alone and made a note that when the order inventory was re-done to make sure they left this "feature" out. I have been told that many old system have similar problems.
     

    --
    Another day closer to redwood heaven
  16. return, break, continue? by krischik · · Score: 3, Informative

    Have you ever wrote a function / procedure with more then one return statement? Or used break or continue in a loop? Then you can use goto as well. From a structure point of view goto, break, continue and return are all unconditional jumps. They are one of a kind. And looking back in retrospect: Since goto need to be paired with a label it's the least evil of the group.

    Note that Pascal the archetype of structured programming had goto but it did not have break, continue or return.

  17. Train simulation by LucidBeast · · Score: 5, Interesting

    Way back we had a project where we had to simulate entire train traffic entering Helsinki train terminal. Someone else had made the simulator and it ran pretty neatly, but unfortunately crashed mysteriously after about four - six hours of simulation time. Our customers were coming the on monday and I spent my sunday trying to figure out how this simulation worked and what crashed it. Finally I caught the problem, which was as simple as some null pointer to a train schedule or something similar which needed to be referenced. I couldn't figure out why it was null in time, so I just added test for null pointer, which skipped said code. Program ran fine and we got our money. Never figured out what was wrong with it. Luckily it was only a simulation.

  18. Study Assignment by LKM · · Score: 5, Funny

    This was a pretty important assignment back when I was studying computer science. It added to the final mark mark for that particular class. The task was to write a reasonably complex application in Prolog or some functional programming language, I can't remember which it was. I think the goal was to pair males and females based on their preferences, and find the optimal solution. Of course, I screwed up royally, and nothing worked five minutes before I had to demonstrate my solution.

    So in the final five minutes, I changed my code so it would avoid the parts which put it into an infinite loop, and instead simply output a random result. My goal was to tell the prof that it had worked a few minutes earlier, and that I didn't know what had gone wrong, and could I please have another week?

    So I demonstrated my app, it gave its random output, and I was about to start with my "damn, it used to work properly" spiel when he said (and this is actually true, even though it sounds unbelievable):

    "That's great! The result is correct, and your app is also quite a bit quicker than my own implementation of the problem. Congratulations, I think you're the only one so far who managed to get the correct result so far."

    I was so taken aback that I probably just stared at him for a few seconds. Then, I stupidly said "So... You want to see my code?" but he was like "No, the result is correct, and your implementation is very fast, so I don't need to see the code. Good job. Send in the next guy."

    And so I did.

    1. Re:Study Assignment by u.hertlein · · Score: 4, Insightful

      "That's great! The result is correct, and your app is also quite a bit quicker than my own implementation of the problem. Congratulations, I think you're the only one so far who managed to get the correct result so far."

      I was so taken aback that I probably just stared at him for a few seconds. Then, I stupidly said "So... You want to see my code?" but he was like "No, the result is correct, and your implementation is very fast, so I don't need to see the code. Good job. Send in the next guy."

      This is so sad. He notices your code is faster and he's not the least bit curious? (I presume he's some kind of CS prof.) Anyway, good for you, but still... :-(

      --
      Geek by Nature - Linux by Choice.
    2. Re:Study Assignment by mehrotra.akash · · Score: 2, Funny

      the opposite happened to me today, made a C++ program to demonstrate the use of classes and made full use of constructors, destructors,data hiding and DMA show it to the prof., he stares at it for 5 mins and then tells me to make everything in the class public and do the thing using arrays only....

    3. Re:Study Assignment by LKM · · Score: 2, Interesting

      He had to grade about 100 people in one day, so I guess he didn't want to spend too much time on each individual student. I'm also not sure whether he actually personally implemented his version, or whether it was one of his assistants.
      He was a pretty good prof, otherwise.

    4. Re:Study Assignment by houghi · · Score: 3, Interesting

      In Real Life dating agencies, there are often a lack of males. So one person who owned it often dated the women, just to keep them on longer and to get more money from them. They were not in the dating game, they were in the 'get money from desperate souls' game.

      The reason (his words) was that women were less afraid to admitting to each other that they were unable to find a partner, where male ego's would never admit such a thing.

      Obviously with the anonymity that is The Internet, this difference is gone and any man now gets ripped of as well.

      --
      Don't fight for your country, if your country does not fight for you.
  19. Re:Wow. Talk about old news. by pjt33 · · Score: 2, Interesting

    Quick, find the dupe and copy-paste all the +5 Insightfuls!

  20. Example by Anonymous Coward · · Score: 5, Interesting

    Example?  Right here:
    #include <stdio.h>

    void    *f(void)
    {
    a:
        printf("Here!\n");
        return &&a;
    }

    int     main(int ac, char **av)
    {
        goto *f();
        printf("There\n");
        return 0;
    }

    1. Re:Example by 7+digits · · Score: 5, Informative

      OMG. I didn't even knew you could write that in C (and I have my name in the comp.lang.c FAQ...)

      Of course, I checked C99, and, no, you can't write that:

      3.6.6 Jump statements

      Syntax

                          jump-statement:
                                          goto identifier ;
                                          continue ;
                                          break ;
                                          return expression<opt> ;

      identifier being defined as:

      identifier:
                                          nondigit
                                          identifier nondigit
                                          identifier digit

      So, goto *f() is a no-no (as is probably &&a)

      But, anyway, wow. Gcc actually compiles that to something that somewhat runs...

    2. Re:Example by Anonymous Coward · · Score: 3, Informative

      Yes, it is non-standard. But quite useful for some things (although not in the way written above). Consider a function that needs to return and then resume where it left off the next time it is called. Could be done by wrapping it in a large switch, but this is more direct and efficient.

      #include

      void *f(void *p)
      {
              if(p != 0)
                      goto *p;
              return &

      a: printf("A\n");
              return &

      b: printf("B\n");
              return &

      c: printf("C\n");
              return &
      }

      int main(int ac, char **av)
      {
              void *p = f(0);

              p = f(p);
              p = f(p);
              p = f(p);
              p = f(f(f(f(p))));
              return 0;
      }

      [and perhaps it's time to get myself an account on here... captcha: "untested"]

    3. Re:Example by 7+digits · · Score: 2, Interesting

      I don't think the efficiency is worth having a non-standard construct, considering a simple switch would do the trick.

      You could also split the function in multiple function (because having all the code in the same function is not very useful as local variables are trashed between executions), and directly returning pointer to the next function to call (hence you could spare of the cost of actually calling f() before jumping).

      Anyway, a nice trick. Didn't thought I would learn another one in C. The worst I ever did with function pointer (not in production code, of course, just to provoke disgust) was in the line of:

      #include

      int f0()
      {
              return 10;
      }

      int f1()
      {
              return 20;
      }

      int f2()
      {
              return 40;
      }

      main()
      {
              printf( "%d\n", (*((int (*)())(((int)f0+(int)f2)/2)))() );
      }

      (yes, this will print 20 on most compilers).

    4. Re:Example by sxltrex · · Score: 2, Insightful

      I pity the developer who has to maintain your code after you've moved on.

  21. complex finance math by Anonymous Coward · · Score: 3, Funny

    I worked with some finance guy who was convinced that the square root of a negative number -x was -sqrt(x), and wouldn't hear otherwise. I hacked sqrt(x) to return sgn(x)*sqrt(fabs(x)), but he complained that when he squared the answer, he didn't get back a negative number. Luckily our code was C99 so I changed his dollar type to be "double complex", made him use the complex sqrt, and changed his print function to display creal(x) - cimag(x). The guy said things worked great. I was glad to hear that, but it still feels wrong that part of our finance system is handling complex number of dollars, whatever that means.

    1. Re:complex finance math by Xenographic · · Score: 2, Funny

      > I was glad to hear that, but it still feels wrong that part of our finance system is handling complex number of dollars, whatever that means.

      What? I'm sure most finance guys are adept enough at counting both real and imaginary dollars, so having complex dollars isn't really that complex...

    2. Re:complex finance math by EdgeyEdgey · · Score: 2, Insightful

      but it still feels wrong that part of our finance system is handling complex number of dollars, whatever that means.

      They're called Imaginary dollars, and there's a lot of them about at the moment.

      --
      [Intentionally left blank]
    3. Re:complex finance math by Bakkster · · Score: 2, Insightful

      I learned long ago that regular math and financial math follow very different rules.

      --
      Write your representatives! Repeal the 2nd Law of Thermodynamics!
  22. Who hasn't? by Opportunist · · Score: 4, Funny

    After years of programming, I guess everyone had to cut some corners sometimes. It's also not (always) a problem of goofing off, a module you depend on not shipping in time but you being required to keep your deadline can already force you into doing just that: Delivering a hack that 'kinda-sorta' works, or at least the customer won't notice 'til we can ship the patch.

    Yes, that happens often. It's dubbed "Bananaware". Delivered green and ripens with the customer.

    --
    We used to have a Bill of Rights. Now, with the rights gone, all we have left is the bill.
  23. Re:Wow. Talk about old news. by 7+digits · · Score: 5, Funny

    > it's the comments that are worth reading

    More specifically the comments in the article. I loved this one:

    "Back on Wing Commander 1 we were getting an exception from our EMM386 memory manager when we exited the game. We'd clear the screen and a single line would print out, something like "EMM386 Memory manager error. Blah blah blah." We had to ship ASAP. So I hex edited the error in the memory manager itself to read "Thank you for playing Wing Commander.""

    That's awesome.

  24. Re:yuck by quintesse · · Score: 5, Insightful

    Basically ALL the software you use works like this.
    Welcome to the real world, no need to feel bad.

  25. Even worse stuff! by syousef · · Score: 4, Interesting

    Some of the worst I have seen:

    In critical C code:

    if (some condition)
            i *= 0;
    else
            i *= 1;

    And I was the actual variable name.

    Even worse, on a different project, an Easter egg that told the user their hard drive was about to be erased, and another that popped up about 30 dialog boxes full of banter between Spock and Kirk. Worst of all this code written in VB and was licensed for megabux then we got hold of it for orders of magnitude more megabux (Most of the original coders were hired fresh out of highschool). It ended up being rewritten (thankfully NOT by me) but we had to get the source to work out how it worked in the first place.

    I wish I was making this up.

    --
    These posts express my own personal views, not those of my employer
    1. Re:Even worse stuff! by Anonymous Coward · · Score: 2, Interesting

      I've come across horrible if-statements, too. One developer I worked with liked using the following for code he wasn't using right away: if (1 == 2). There're many other hilarious variations, of course. The thing that got me was nobody else on my team questioned that if-statement for over 4 months! They saw it and assumed it was important. I came across it while fixing a bug and, at first, couldn't see why several hundred lines of code seemed to do nothing at all. In the end, all code surrounded by that if-statement was unneeded, as admitted by the developer in question. Why didn't he remove all of it to make things clearer for the rest of us in the first place? Instead he let it sit there and clutter up pertinent code until another person took the time out of their busy schedule to do some housekeeping. Don't get me wrong; that developer had done the same sort of thing on many files - not only the specific instance mentioned here. Hunting through ~1100 files for rogue if-statements wasn't fun, even with aide of search functionality in SVN, since I 1) had no clue what other conditions the guy decided to use while being lazy and 2) couldn't figure out where to begin since the issue was EVERYWHERE. I made the developer sit down with me in order to make progress. When all was said and done, the code base was noticeably lighter and much more manageable. Oh, the joys of going through everybody else's code while fixing bugs. The biggest change came in the form of new and incredibly strict coding standards for the team. This was my first programming job and I'd only been there for 3 months, so I guess it was a good experience in one way or another.

  26. Prolog Assignment by becker · · Score: 4, Interesting

    That's completely understandable in this case of programming in Prolog.

    Prolog is a declarative language.

    You declare the rules, and the system figures out a result that matches those rules.

    The problem is that this basically doesn't work. So a Prolog programmer has to write the "declarative" rules in a procedural order so that the run-time system doesn't have to try every possible combination to find (or fail to find) a matching result.

    The proper ordering of declarations can be quite subtle. With a modestly complex program you can make a seemingly unimportant change in the order of the declarations and have the runtime go from a second to a week.

    In this case the professor didn't (couldn't) know how long a Prolog program to solve this problem should take. He just assumed that you had found a more efficient ordering for the declarations. He might even have thought it was luck rather than deep insight that your program was faster than his. But you have to a decent understanding of the limits of Prolog to get a complex program to complete in a reasonable time, so you had to be good before you could get that lucky.

    If you couldn't already tell, I have a low opinion of Prolog and declarative languages. They are "parlor tricks". Much like computer 'Life' and neural networks, simple programs can produce unexpected seemingly-sophisticated results. But they don't get better from those initial results. To compute the answers or results you want in a reasonable time, you end up with at least the complexity of writing things in the traditional explicitly procedural method.

    The promoters of declarative language typically don't mention that you end up writing rules in an explicitly procedural order if you want the program to work. If you press them on the issue, they then say "well, OK, it's not actually any easier to write, but it's easier to verify that you've correctly specified the desired result." But if you have to carefully shuffle declarations around, and even then some results unpredictably take centuries to compute, pretty much no one cares.

    1. Re:Prolog Assignment by QuoteMstr · · Score: 3, Informative

      General-purpose declarative languages are bunk, I agree.

      However, domain-specific declarative languages often work pretty well. Consider build systems (Make, ant, etc.), or SQL, both of which are declarative.

    2. Re:Prolog Assignment by greed · · Score: 2, Interesting

      Interestingly, a LOT of people, let's say almost everyone, get Make wrong because they don't understand how the declarative rule structure works.

      I'm not a fan of ANT, actually; I think it exists to solve a problem that Sun should have never created in the first place. (Produce arbitrarily named .class files from a given .java file.) I don't know how declarative it _really_ is under the covers, but everyone I see saying "it's better than make" are doing procedural things with it and using that to justify ANT over make.

      (My gripe with ANT--aside from the XML soup--is it affords sloppy build systems: it's a wildcard enabler.)

    3. Re:Prolog Assignment by Blakey+Rat · · Score: 2, Insightful

      Yeah, but everybody's experienced the SQL query which, when re-written to say the same thing a different way (i.e. replacing a sub-query with a join) runs 10 times faster than before. The trick to get good at SQL is just to remember these cases and avoid them... the fact that the SQL parser/engine can't do this optimization on its own doesn't speak well for SQL's design.

      It also doesn't help that when extensions are made to SQL (like T-SQL), the very first thing they add are procedural looping operators.

      That's not to say the *concept* of SQL is flawed, just that the language itself is, IMO.

    4. Re:Prolog Assignment by Abcd1234 · · Score: 2, Informative

      If you couldn't already tell, I have a low opinion of Prolog and declarative languages.

      Better not tell your database, it might get offended...

  27. I knew a guy who pulled a hack like this by FranTaylor · · Score: 2

    it made a total hash out of what I was trying to do. But he lost the source code, so I couldn't prove that he did it. Of course we couldn't fix it either. It was in code that calculated people's paychecks. He got fired. I quit.

  28. Wow am I the only one in here by Big+Hairy+Ian · · Score: 3, Insightful

    who just aims to get what is functionally absolutely needed finished & tested by the deadline? Bear in mind that most of my deadlines get set by clueless salesmen who even if they consult me generally tend to ignore what I say and tell the client what the client wants to hear.
    I haven't implemented a fully finished system by the deadline in years simply because I can't squeeze 3 months work into 1 month.

    --

    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:Wow am I the only one in here by wrook · · Score: 2, Interesting

      Here is my strategy for dealing with this situation:

      1) Tell the salesmen that you have absolutely no problem with them telling the customer whatever they want. Their function is to make sales to customers. Your function is to write software. You won't try to tell them how to do their job, because quite frankly you aren't qualified to know what's best for sales. Of course the implication is that they shouldn't tell you how to write software, but you probably don't have to tell them this explicitly (well, it happened once that I had to say it...)

      2) Show the salesman what you actually *are* going to deliver. Generally a list of use-oriented functionality is the best. You might be doing a lot of refactoring underneath, but they won't understand that. Only list what the user will see.

      3) Probably what they are saying to the customer and what you are promising to deliver will not match. No matter how clueless they are, the salesmen will probably notice and tell you, "You had better do something to fix the situation". This is where you reiterate, "I can't tell you what to say to the customers, that's up to you. But this is what I plan to release. However, if you would like to substitute something on this list with something more important, I'd be happy to oblige."

      4) Now they will still want it all. They will tell you that the whole company will go under unless you deliver everything. You can now say, "That's a shame. I like working here too. Well, if that's the way it is, I guess I'll go fix up my resume. It was great working with you." You only have to do this once (thank god). At this point the salespeople will say, "Well, maybe we can do something if you at least give us feature X".

      5) Negotiate with the salespeople. But use each piece of functionality as a lego block. Its size is immutable, but you can put it in, take it out, put it in a different place etc. At every point make sure to point out that you are quite happy to allow the salesmen to choose what they want you to do. It's just that it doesn't all fit.

      6) Sometimes you will run into the situation where the salesman will swear at you and tell you to go do something anatomically impossible. Then they will storm off. At this point it's important to let them go, but to go to your own management (or executive management if you have no manager) and explain, "The salesmen are upset and I understand their point of view. They can't have everything that they want. It's frustrating for me too. But I need them to choose what things are most important. If you could just have a chat with them so I can prioritize things properly I would really appreciate it." After this you will have no problems (unless the salesman in question *is* executive management, in which case you should jump ship as quickly as possible).

      7) Probably you will have to go through this charade about 4 or 5 times. But each time it will get easier. There will be one last time where they will pull every dirty trick in the book. Just hang tough, because after that you will have no problems.

      Hope this helps.

  29. Re:PHP signed 32 bit integers by jesset77 · · Score: 2, Interesting

    Axually, we wrote the code long before 4.4.0 or 5.anything, so... new manual entry is unhelpful. :) (I cited "MAXINT" given my C heritage .. PHP's nomenclature fails anyway, as they lack an analogue to "MININT" ;3)

    When you've got code failing at unpredictable places for unpredictable reasons, the first place you look is not the "integer" subsection of the manual, anyhow. Besides, by that time the damage were already done. We noodled out the cause and thereafter found your cited manual points to corroborate our theory.

    We were still stuck using PHP which apparently cannot understand anything but signed 32 bit reliably, interfacing with MySQL which isn't capable of interim calculations in that space.

    we refuse to write anything but simple two's compliment logic into all of our applicable SQL statements, so for things like sort we just aren't going there.

    Allow me to forstall suggestions of using GMP given that gmp_strval(gmp_add(gmp_init("2"), gmp_init("2"))) is fail compared to "2+2" in every conceivable way, and there do not appear to be any OO bindings for GMP in PHP 5.x to rectify.

    Put simply, we could obviate this problem easily if ANY of the following were possible:

    * Sane integer support in PHP

    * Sane OO support in PHP (for example, OO GMP bindings .. though there would still be crippling performance hits for major parts of our app!)

    * sane functional support in the database to handle the two's compliment logic imposed by PHP

    If we had the resources to remake the project in Ruby or Python against a postgres database, then all of those possible solutions would be at our fingertips, so much so that only the first solution would need to apply. The other solutions/capabilities would simply stand around looking cool. :P

    So... meantime, can't afford the Ferrari and have to duct tape the pinto's engine together. *sob*

    --
    People willing to trade their freedom of expression for temporary entertainment deserve neither and will lose both.
  30. Customers by CarpetShark · · Score: 2, Insightful

    Have you ever needed to insert terrible code to make something work at the last minute?

    Yes. But mostly it's not to "make it work"; it's because the customer wants something that is entirely against the original design they asked for.

  31. char Str[255] by dargaud · · Score: 2, Informative

    My worst shortcut is to use fixed-sized strings with non size limiting functions, as in:
    char Str[255];
    sprintf(Str, "%s, %s", Lastname, FirstName);
    I really wish snprintf was available on my C implementation.

    --
    Non-Linux Penguins ?
    1. Re:char Str[255] by dkleinsc · · Score: 4, Insightful

      I believe another name for that little snippet is "buffer overflow vulnerability".

      --
      I am officially gone from /. Long live http://www.soylentnews.com/
  32. New London Underground station??? by Anonymous Coward · · Score: 2, Funny

    First year at university, as part of the end of year project, we coded a shortest path algorithm to work out the distance between two stations in the London Underground system. However at 4am a couple of hours before the class presentation we discovered a bug! This was that if you chose the station 'Bank' it could for example take you to 'Embankment' (since it contains 'bank'). Our 'fix'?? We renamed Embankment to... Embonkment! Nobody realised in the presentation! :)

  33. Configurable sleep() by Get+Behind+the+Mule · · Score: 2, Interesting

    So we had a race condition on database transactions using two-phase commit, your usual mind-fucking WTF situation, drove us up the walls for days, you all know what I mean. We knew it was a race condition because if we put a sleep() statement at the end of one of the transactions, everything ran fine. sleep(10) was always long enough, and since all of this ran asynchronously in the back end, an end user would never notice the difference.

    So we went to the customer. We told them that we could continue to bust our brains trying to find a "real" fix, and didn't know how long that would take, or we could just leave the sleep() in. And we could even make the length of the sleep interval configurable, so they could try to make it shorter than 10 seconds, if they really felt like fiddling around with it.

    The customer went for the configurable sleep().

  34. DOS to the rescue... by Xenographic · · Score: 2, Interesting

    > Once I had an assignment due and at the last minute before being evaluated, realized I had made a huge mistake, even though the code looked OK...

    I once did almost the same thing, except that I wrote the entire assignment the first day we got it, during class. But I couldn't turn it in yet. And nearly forgot about it. So I turned it in at the last minute...

    Except that I had misread the specification! Oh, the program worked just fine, but it printed everything to the screen. It was *supposed* to go to output.txt. That would've been trivial to change, if I actually had any time. But now I was out of time and couldn't change the code I had submitted...

    With a bit of quick thinking, I actually managed to convince the TA that the problem was that you were supposed to execute the program as:
    java MyProg > output.txt

    So instead of getting a zero, I got 98%, because I had failed to document this.

  35. syntactic sugar by sigxcpu · · Score: 2, Funny

    syntactic sugar is just fine, but what I would really like is syntactic caffeine.

    --
    As of Postgres v6.2, time travel is no longer supported.
  36. VB6: Lost source code - Ultimate repack by netsavior · · Score: 5, Interesting

    So it was 1999 and I was working for a mom and pop software shop, we had been acquired by a dot com. All our money and toilet paper stock options were held until we delivered the re-branded product with source. Part of the "rules" said we had to have only C/C++ and VB6 source, NO OTHER LANGUAGE.

    . We finished converting a few rogue scripting modules and things like that, which creep in over time. But we COULD NOT find the source code to one of our VB6 DLLs (an old one that had not been changed since it was first compiled in VB6). We searched and searched and eventually the fastest coder(not me) started rewriting it. We were 1 day from delivery date and there was no way he could finish it, so I ran it through a disassembler.

    the C++ code we delivered looked like this:

    int functionName(int parm) {
    _asm {
    push esi
    mov esi, dword ptr ds:[esp+8]
    mov dword ptr ds:[edi], esi
    retn
    }
    ....(you get the idea)
    It was unreadable, but it compiled and worked and we got our money. I still wonder what they ever did with that... since the software is still in use...

    1. Re:VB6: Lost source code - Ultimate repack by mrwolf007 · · Score: 5, Funny

      Yeah, just think what those guys thought when they saw the code.
      "Wow, assembler code."
      "It must be highly optimized."
      "Told you it was a good idea to buy it."

  37. Not exactly programming, but... by TheFourthDoctor · · Score: 2, Interesting

    One of my uni courses our assignments required us to build circuits on breadboards in class - no opportunity to work on it otherwise. My lab partner and I were having problems with one assignment which, despite being wired properly, refused to produce the required output. After checking and rechecking wires, swapping out gates, etc., we were finally down to the last five minutes of class with no idea what to do next. Out of frustration, my partner reach out and scrunched the entire mess of wires in his fists and held them there.

    "Try it now"

    It worked. He just sat there while I dragged the prof over to evaluate it. As soon as he was done, my partner let go and it stopped working again.

  38. Easter egg dependency by plover · · Score: 4, Interesting

    We had an easter egg in our code that was in a routine scheduled to be executed only at 0-dark-30 when our users were long gone. But someone later called the routine as part of the loading process, and the users ended up seeing it anyway as they signed on at start of day. It made people smile, so we left it in.

    A few years later, we were telling a client that we couldn't add their new feature X because we don't have the memory. At that point the director said to get rid of the easter egg and then it'd fit. (A few hundred bytes was not going to make a difference, but our director didn't care, it was a perception thing.) What we got instead was a hundred bug reports that the easter egg wasn't displaying, and that they "needed" to see it so they'd know when start of day was complete.

    --
    John
  39. We in the Linux camp never do that sorta stuff... by Becausegodhasmademe · · Score: 2, Funny

    That's the good thing about open source! All of the dirty hacks the devs use eventually get weeded out of the code as time goes on! Honest!

  40. I program small games by selven · · Score: 3, Funny

    I always just hard-code all my levels - it's easier to just go back and recompile (which takes 15 seconds in C or 0 seconds in python) than code all the extra logic in for reading from files. As another plus, this makes it harder for other people to cheat. Speaking of cheating, once I called my player save file "makefile" to discourage people from looking at it or modifying it.

    And, I never split my code into multiple files - scroll and Ctrl+F were good enough for my grandfather, and they're good enough for me!

  41. Re:Here's another one... by Tuna_Shooter · · Score: 5, Interesting

    This is the code for the Apollo 11 lunar lander flight computer.

    http://code.google.com/p/virtualagc/source/browse/trunk/Luminary099/LUNAR_LANDING_GUIDANCE_EQUATIONS.s?r=258

    and yes some of my code is in there along with the equivalent of a few "goto's

    Lots of bright people worked on this and in some circumstances a "goto" is required.

    --
    *--- Sometimes a majority only means that all the fools are on the same side. ---*
  42. Re:yuck by TheRaven64 · · Score: 2, Insightful

    What, you think no hobby programmers have added quick hacks because they've spent two days chasing a bug and still can't find it? No open source projects have ever added quick hacks to make a feature they want to boast about work in time for their code freeze?

    --
    I am TheRaven on Soylent News
  43. The Fucksort Incident by ari_j · · Score: 5, Funny

    Back in college, we were at a programming competition and I was the on-the-keyboard coder for one of the problems. We had 10 minutes for the problem and I coded it quickly, having decided on the best algorithm before sitting down. Part of the solution was a sorting routine on a list. We were using Visual C++ although we were all not C++ experts at the time, and so rather than mess with the STL and the possibility of having to read documentation, I did it all from scratch. I knew that sort was already in use by the standard library, so I called my routine mysort.

    Apparently, however, Visual C++ includes a mysort in its standard library. So, with the clock ticking down and the solution's only impediment to our victory being an identifier conflict, I renamed the routine the way that any one of us would have: myfuckingsort. We won the competition.

    In this particular competition, the judges were not supposed to read our code - they just run the output of your code on the input and check for correct output - so I felt safe when I typed what I did. However, one of them came up to us afterwards and told us that they do in fact usually read the code of the winning team to see if we did anything unique in our solution. Yep. Sure did. And my classmates and professors never did let me live down what was affectionately nicknamed the fucksort algorithm.

  44. I see two unconditional jumps here by krischik · · Score: 2, Insightful

    But I might have missed some. There is not much difference between "return 0;" and "ret=0; goto exit_function;". Both are unconditional jumps there is no rational reason why one should be "considered harmful" and the other not.

  45. Re:Here's another one... by sburchill · · Score: 2, Interesting

    I really love this bit :

    DMP*    VXSC
            GAINBRAK,1    # NUMERO MYSTERIOSO
            ANGTERM

    --
    sbb
  46. Re:Here's another one... by Tuna_Shooter · · Score: 2, Interesting

    # Page 731
    # BURN, BABY, BURN -- MASTER IGNITION ROUTINE

                    BANK 36
                    SETLOC P40S
                    BANK
                    EBANK= WHICH
                    COUNT* $$/P40

    --
    *--- Sometimes a majority only means that all the fools are on the same side. ---*
  47. Re:Sorry... by gt6062b · · Score: 2, Funny

    10 Print "No"
    20 Goto 10

    Please hand over your geekbadge...

    10 Print "No"
    20 Goto 10

  48. Not the only lesson by Jonathan · · Score: 4, Insightful

    Well, in part, but another important lesson in science labs is learning to report the truth, even if is disappointing and not what you want. This is an important lesson and unfortunately even some well known scientists don't learn it,

  49. Re:Last one was great! by QuoteMstr · · Score: 2, Interesting

    We do this at my job. We have a decent production database system, but we develop against a K6-2/400 with 256MB of RAM and a couple flaky SCSI disks. If it performs adequately there, it'll perform adequately anywhere.

  50. note really code by sanguisdex · · Score: 2, Interesting

    Not that I have done this but I have seen plenty of web desigers use a css 'display:none' or before that was happening put comments tags around data that they did not want the site visitor to see.

  51. Re:Here's another one... by Chapter80 · · Score: 3, Funny

    This is the code for the Apollo 11 lunar lander flight computer.

    HELP!

    I'm trying to get this code to work. I'm at an altitude of 6,000 ft, hovering over the Sea of Tranquility, and the darn thing keeps crashing! (The code, not the lunar module.)

    PLEASE don't connect me to that Bangalor helpdesk again! I am in serious trouble here!

    Has this been tested for Y2K compliance?
    Did we not pay our last support bill?

    - Major Tom

  52. Word Conversion by Anonymous Coward · · Score: 2, Interesting

    I remember 15 years or so back; I was trying to get an application convert a text file into a Word document. I was using all these nice OLE calls from within Delphi but for some reason it didn't work.

    The deadline was looming, so I ended writing a function that copied the files and renamed the extension to DOC. When opening it in Word it didn't show any errors. Unfortunately my client found out and went ballistic. By that time I luckily had the word conversion code working and was able to provide a new executable that worked as requested.

  53. Bravo, robfoo by XenonOfArcticus · · Score: 2, Insightful

    Let others smack you down, but with nearly 30 years of programming experience in numerous languages, I'm with you. Indented branching flow seems clean, stable and maintainable. I got dissed for a job i applied for because my code was designed this way instead of the "enlightened" way of throwing exceptions. Exceptions are ok, I guess, if everything is a C++ objects that self-destructs when it goes out of scope, but reality doesn't always work that way. In retrospect, I'm glad I'm not at that job.

    --
    -- There is no truth. There is only Perception. To Percieve is to Exist.