Slashdot Mirror


Ask Slashdot: When Do You Include 'Unnecessary' Code? (sas.com)

"For more than 20 years I've been putting semicolons at the end of programming statements in SAS, C/C++, and Java/Javascript," writes Rick Wicklin, a researcher in computational statistics at SAS. "But lately I've been working in a computer language that does not require semicolons. Nevertheless... I catch myself typing unnecessary semicolons out of habit," he writes, while at other times "I include optional statements in my programs for clarity, readability, or to practice defensive programming." While Wicklin's post is geared towards SAS programming, Slashdot reader theodp writes that the question is a language-agnostic one: ...when to include technically-unnecessary code -- e.g., variable declarations, superfluous punctuation, block constructs for single statements, values for optional parameters that are the defaults, debugging/validation statements, non-critical error handling, explicitly destroying objects that would otherwise be deleted on exit, labeled NEXT statements, full qualification of objects/methods, unneeded code from templates...
He's wondering if other Slashdot readers have trouble tolerating their co-workers' unnecessary codes choices (which he demonstrates with a video clip from Silicon Valley). So leave your answers in the comments. When do you do include 'unnecessary' code in your programs -- and why?

147 of 239 comments (clear)

  1. "Unnecessary" code? by Anonymous Coward · · Score: 5, Funny

    All of my code is unnecessary, you insensitive clod!

    1. Re:"Unnecessary" code? by Darinbob · · Score: 1

      So much code is unnecessary too; it's only there because a customer thinks they need a certain feature, or added as a check-off box for features that no one actually uses but makes you different from the competition, and so forth. Necessary for sales, necessary to keep upper management happy, but ultimately doesn't really add any real value.

      Oh and don't forget all those asserts and error checks that will never kick off because the real errors you'll find in the field won't be tested for.

  2. Anything for work by Anonymous Coward · · Score: 5, Insightful

    I'll add extra intermediate variables, break up lines to make them as short as possible, and use extra verbose variable names along with explanatory comments of the logic of each object/function. The goal is to make it so that anyone reading the class for the first time with no prior experience can understand its purpose and basic function without having to spend 5 minutes deobfuscating the code. Yes you generally can golf most any class into a single line, but it's unmaintainable even to its original creator after a couple weeks.

    That said, for personal consumption code, I don't generally bother going to that much effort to make my code clean/clear.

    1. Re:Anything for work by Bite+The+Pillow · · Score: 1

      None of that is unnecessary code. You get larger debug symbol files, but it is way easier to debug and test. At a minimum, have a single return value, instead of returning whatever half a line of method calls do, so you can break point the end of the method, instead of all or its callers.

      Disposing auto-dispose objects is unnecessary code is really not good practice, because how thorough is the twice disposed code path going to be tested? I would call it a bug.

    2. Re:Anything for work by AchilleTalon · · Score: 1

      Comments, line break and meaningful variable names cannot be considered unecessary code. Comments, line break and variable names are not translated into executable instructions.

      --
      Achille Talon
      Hop!
    3. Re:Anything for work by lgw · · Score: 2

      None of the "unnecessary code" in TFS would be translated into executable instructions. Heck, the better the compiler's optimizer, the harder it is to add anything that's semantically equivalent but causes wasted object code.

      --
      Socialism: a lie told by totalitarians and believed by fools.
    4. Re:Anything for work by Anonymous Coward · · Score: 1

      Same here. To me, unnecessary code is code that does something without affecting any other variable and not returning anything. It's there to burn CPU cycles and adds nothing of value.

      Breaking up code to make it human readable/understandable is necessary code if it's going to be looked at again. The more "sense" the code makes, the easier it is to maintain and modify without introducing nasty bugs.

      Today's compilers are light years better than when I was in school where every little optimization made a huge difference. That's where unnecessary code really had to be unnecessary.

      Only "Rockstar" programmers that show off how small they can make their code complain, the rest of the programmers, in my experience appreciate the unnecessary code

    5. Re: Anything for work by hackwrench · · Score: 1

      Even though an auto-disposed object can auto-dispose I figure that manually disposing it should cause the auto-dispose not to happen and knowing when something is going to happen is usually a good thing. I know languages with automatic garbage collection have instructions to manually garbage collect and doing so can be a good thing.

    6. Re:Anything for work by Chrondeath · · Score: 1

      ...when compiling for release.

    7. Re:Anything for work by swilver · · Score: 2

      Ugh, single return rule sucks the worst. Nothing like having to read through dozens of lines of code just to see if the result wouldn't change somewhere halfway when an early return could have made it clear in an instant.

    8. Re:Anything for work by chipschap · · Score: 3, Interesting

      My approach also. Main goal for me is to make code readable enough that only minimal commenting is necessary. If personal stuff gets big enough that picking it up in a year would take effort then it gets the ultra explicit, readable and immediately understandable treatment.

      I agree with both this and the poster above, except that even if minimal commenting is truly necessary I'll still put in plenty of comments. A couple of months later I want the code to make sense to me as well as others, and it's so easy to forget what you were thinking at the time. My shorter programs tend to have at least as many lines of comments as of code. Perhaps that's overkill but there's no harm in it. Writing comments doesn't take a lot of time and it may save tons of time down the road.

      Side note: some years ago I went to a class by an "expert" who said that code should be so clear it never needs comments (sort of okay so far) so therefore code should never have comments in it (I walked out at that point).

    9. Re:Anything for work by Dutch+Gun · · Score: 4, Informative

      The single return rule makes sense in some circumstances. I like early outs, but then tend to the single return rule. If you're breaking apart your logic to that degree that you need a return in the middle of a long function, then you may want to consider breaking apart the function. Still, I think it's best to consider it a *guideline* rather than a rule. The moment you declare something a rule, someone will find a valid reason for breaking it.

      As for other "optional" code, I tend to put parentheses around any C/C++ code that depends on operator precedent. The only one *everyone* knows is * or / before + and -, otherwise, it gets parentheses, just to be clear.

      I see a lot of programmers try to cram as much as possible into one line, which I'm not a fan of. As one example, I'm not a fan of assigning a variable inside an if statement. It's harder to read than several short, clear lines, and it likely compiles to the same assembly in the end. So, I'll occasionally leave a formula as several steps and explicitly declare some of the intermediate variables, even if I could have stuffed it all into one line. It's easier to debug, since you can examine the intermediate values, and it helps others to understand what's going on, since the intermediate variables have an actual name as a hint. I'm sure it bugs some people who think it's too verbose or my variable names are too long and descriptive. I don't go crazy, but neither do I stick to single letters when a word or two works better.

      --
      Irony: Agile development has too much intertia to be abandoned now.
    10. Re:Anything for work by Anonymous Coward · · Score: 2, Insightful

      The code says WHAT you are doing
      The comments should say WHY you are doing it.

      I took over a project a few years back. The developer had no idea about :-
      - comments
      - Functions and Procedures
      - Everything was in if...then... else monolithic structures.

      As a result thousands of lines were replicated many many times and totally unmaintable.
      My background was in assembler code. We had one comment per line as a minimum.

    11. Re:Anything for work by fahrbot-bot · · Score: 4, Insightful

      Side note: some years ago I went to a class by an "expert" who said that code should be so clear it never needs comments (sort of okay so far) so therefore code should never have comments in it (I walked out at that point).

      Comments describing exactly what you're doing should be relatively unnecessary. However, comments as to *why* you're (not) doing something or how you're doing something, especially if it's non-obvious and/or "clever" are always appropriate. Code is changed for many reasons. Commentary can help understanding of various facets in various ways.

      Personally, I think clear logic and consistent style are most helpful for both coding and commenting. Most people should be able to skim your code and have a general understanding of what's going on and why. I always try to write my code so that more junior people (and, quite frankly, even more senior people) on our team will be able to learn from my examples and work with what I've written. (You know, in case I get hit by a bus tomorrow.)

      --
      It must have been something you assimilated. . . .
    12. Re:Anything for work by fahrbot-bot · · Score: 1

      I see a lot of programmers try to cram as much as possible into one line, which I'm not a fan of.

      Me neither. Especially if you ever have to run it through a line-oriented interactive debugger like adb or gdb. (I'm old.)

      --
      It must have been something you assimilated. . . .
    13. Re:Anything for work by BlackHawk-666 · · Score: 1

      +1 for the 'why' remark.... ...i'd also add, that it should explain semantics when needed, out of bounds logic, reasoning where it isn't obvious, and addendums to what the code is doing.

      I'm a firm believer that you should be able to page through code reading only the "green code" in order to understand what is happening.

      Where code perfectly expresses the algorithm / concept, few comments are needed...but the rest of the code should be commented to hell.

      --
      All those moments will be lost in time, like tears in rain.
    14. Re:Anything for work by BlackHawk-666 · · Score: 3, Insightful

      I try to write my code as if I'm explaining it to a new, but competent coder. This serves me well when I write articles and include snippets of the code, as well as when I try and remember what the hell I was doing.

      I also make heavy use of: // NOTE: // TODO: // HACK:

      and their ilk.

      --
      All those moments will be lost in time, like tears in rain.
    15. Re:Anything for work by BlackHawk-666 · · Score: 1

      I write game code in c++, so the expectation is anyone coming to work on the code has a pretty decent level of skill in c++. I early out whenever it makes sense, but obey the "one return" rule is there is nothing to gain from short-cutting the evaluation path. Game coders are used to multiple returns, so it's not a big deal for them.

      --
      All those moments will be lost in time, like tears in rain.
    16. Re:Anything for work by BlackHawk-666 · · Score: 1

      I'm not a fan of assigning a variable inside an if statement. It's harder to read than several short, clear lines, and it likely compiles to the same assembly in the end.

      I'm guessing you mean inside the if () part of the statement rather than in the body of the statement for the if.

      I'm not a big fan of it either, but I see it often enough because i work with a lot of outside code. I typically see it looking a bit like this:

      if (auto x = SomeTest ())
      {
      }

      which always make me second guess the '=' statement...should it be '=' or '=='. It's valid syntax and it's both shorter and helps to contain the variable X to within the statement enclosed in parentheses, but...it's jarring to someone who is on the lookout for misuses of the assignment and equivalence operators. That said, it's awesome, so I use it myself :D

      --
      All those moments will be lost in time, like tears in rain.
    17. Re:Anything for work by phantomfive · · Score: 1

      To add to your comment, in general it's better to follow the style of the codebase you're working in than try to rewrite it from scratch.

      --
      "First they came for the slanderers and i said nothing."
    18. Re: Anything for work by plopez · · Score: 1

      You do not code for yourself you code for your customers and the next coder that comes along

      --
      putting the 'B' in LGBTQ+
    19. Re:Anything for work by Anonymous Coward · · Score: 2, Insightful

      To me code should not be commented to hell, it should be commented to a level that a make the code understandable to a programmer or average skill. Most code is self explanatory, I actually read code better than English it is always accurately describes what the program is doing, and it is always up to date. Yes there is a place for comments, in code that is complex or relies mathmatical principles, or an API.

      Too many times have I seen coding standards that require you to comment every function, you end with copious amounts of code like this:

      /**
        * sets X
        * X IN int
        */
      void SomeClass::setX(int x)

      The comment above is worse that useless, it takes time for me to read it, write it, and maintain it.

      More is not always better than less, as in non-fiction writing you should say just enough to explain the concept to your target audience, and no more. I this is a concept they never taught me in school but should have. They should say give me an essay with X good points, not Y words. So through school I used to make my essays much much much longer by putting in superfluous words.

    20. Re:Anything for work by DudeTheMath · · Score: 1

      I'm happy to consider constructs like "if ((newThing = CreateAThing()) == NULL) { /* handle the error */ }" legit when you don't have try/catch exception handling.

      --
      You save only 59 seconds over 8 miles by going 75 instead of 65. Do you really have to pass that guy? Do the Math!
    21. Re:Anything for work by Anonymous Coward · · Score: 2, Insightful

      if (auto x = SomeTest ())
      {
      }

      How about

      if ( ( auto x = SomeTest() ) )
      {
      }

    22. Re:Anything for work by vivian · · Score: 1

      I'll add extra intermediate variables, break up lines to make them as short as possible, and use extra verbose variable names along with explanatory comments of the logic of each object/function.

      All great practice. These days I make sure I put enough doxygen style comments in the headers so that others (and myself in a few years time) can just browse through the doxygen generated documentation and be able to understand the purpose and function of the code.
      For very maths oriented functions (say calculating the minimum time needed to decelerate something within velocity and acceleration limits) I might also include a few lines of comments that show the derivation of the formulas from the more commonly seen physics equations.

      For something that is doing a lot of geometric manipulations using a lot of linear algebra operations, likewise there's usually a line or two of comments saying what it's trying to achieve - it gives me or others a chance to later look at what the code is supposed to be doing and evaluate if there's a better way to achieve the same goal.

      Correct comments are just as important as code - and frankly, I type pretty fast so they really take next to no time to put in. I never did understand the obsession some people have in trying to cram as much logic into as few statements as possible - makes for less code to type, but the time it takes to type it is not the main reason programs take time to develop and debug.

    23. Re:Anything for work by Anonymous Coward · · Score: 2, Funny

      I like to sprinkle //FIXME around my code. Sometimes I even put it where something needs to be fixed, though I never say what.

    24. Re:Anything for work by Darinbob · · Score: 1

      Agreed. I've run across so much code where I knew exactly what it was doing, only I had no idea why it was doing it. Sometimes it's an obscure feature for just one customer, so if you change it you get angry calls. Doesn't help that most of the code was originally written people who weren't trained in computer science or programming.

    25. Re:Anything for work by EETech1 · · Score: 1

      Shhh!
      Don't teach them assembly!
      You'll confuse them!

    26. Re: Anything for work by chipschap · · Score: 2

      Remember that comments always lie. Still put them but don't trust them.

      Actually this can work to your advantage when debugging. If the comment explains what is supposed to be going on, but that's not happening, it can help narrow things down.

    27. Re:Anything for work by mrchaotica · · Score: 1

      Better would be to explicitly test for failure or success:

      if(NULL == (char* x = malloc()))
      {
      //handle error
      }

      or

      if(0 != (int x = some_math()))
      {
      //do stuff
      }

      (I'm also not a big fan of auto... I like to know what my types are.)

      --

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

    28. Re:Anything for work by gzuckier · · Score: 1

      I try to write my code as if I'm explaining it to a new, but competent coder. This serves me well when I write articles and include snippets of the code, as well as when I try and remember what the hell I was doing.

      I also make heavy use of: // NOTE: // TODO: // HACK:

      and their ilk.

      since we started with SAS...
      for the kind of things i work with in SAS, you can't break it up into the usual IT/designer/user kind of thing; you need to know the data you're working on inside and out... which variables are reliable, which need to be recoded.... so i put a lot of that stuff in comments. /*4000 unique accounts*/ or /*tax_paid is always 0*/. stuff like that.

      --
      Star Trek transporters are just 3d printers.
  3. Simple reason... by QuietLagoon · · Score: 4, Funny
    I put the unnecessary code in so that the next programmer who likes to complain has something to complain about besides my real code.

    .
    There are some programmers who like to complain about other people's code (it seems to make them think they are a better coder), so why not give them something intended for them to complain about?

    1. Re:Simple reason... by Z00L00K · · Score: 1

      Not all code is completely unnecessary, it may be unnecessary for the language variant but if you work with many similar variants it may be an advantage to be a bit defensive.

      E.g. not all C compilers initiates variables to 0.

      --
      If builders built buildings the way programmers wrote programs, then the first woodpecker would destroy civilization.
    2. Re: Simple reason... by beelsebob · · Score: 2

      No, that's you. The point he's making is that it's not unnecessary to miss out these initialisations in *any* compiler, even (and I'm not sure these actually exist), ones that initialise every variable to 0. You're writing C, not "C for this specific compiler", and that means that no matter the compiler implementation, the value stored in an uninitialised variable is undefined, and as soon as you read an uninitialised value, your whole program has an undefined behaviour.

    3. Re: Simple reason... by Immerman · · Score: 2

      Quite. Reminds me of the definition of "undefined behavior":
      It compiles perfectly.
      It debugs perfectly.
      It works perfectly throughout all functionality and QA testing.
      It explodes in the worst possible manner when proper functioning is actually important.

      --
      --- Most topics have many sides worth arguing, allow me to take one opposite you.
  4. Bugs are optional too by bidule · · Score: 1

    ... so debugging/validation statements and error handling can be removed.

    Some others are a cheap way not to write comments.

    Others are... noise... that might cause bugs as soon as the function is modified.

    --
    ID: the nose did not occur naturally, how would we wear glasses otherwise? (apologies to Voltaire)
  5. Code doesn't need punctuation by guruevi · · Score: 3, Insightful

    In effect most punctuation, indented blocks etc is superfluous to a computer. Is your code more or less readable with whatever construct you include? What if you add more code between eg your declaration and your use, would it still be obvious?

    That's why languages without those construct are a pain to work with, you add a bunch of code and suddenly you've lost whether you're 4 or 5 tabs deep when the tabulation decreases. I like to add comments to the end brackets of regular code myself and add brackets to all if statements. It's superfluous but it's harder to rewrite a conditional one liner into a multiline code after the fact.

    --
    Custom electronics and digital signage for your business: www.evcircuits.com
    1. Re:Code doesn't need punctuation by danthemanvsqz · · Score: 3, Insightful

      The problem is that you write code that's 4 or 5 tabs deep. Keep your code simple and obvious, also how hard is to test code that have 4 or 5 nested code blocks vs code that has only 1 or 2 nested code blocks?

    2. Re:Code doesn't need punctuation by Immerman · · Score: 3, Insightful

      Depends on what exactly you're doing. As a general rule I prefer to avoid deeply nested code, but I've also written some code where a large block of code all interacted with a large amount of data, so that there were no natural "separation planes" to decompose it into smaller blocks without creating subfunctions that would themselves take dozens of parameters that might (or might not) be modified, making the whole even more error-prone and difficult to understand.

      Not a common occurrence I'll grant you, but sometimes the task at hand really is that ugly.

      I've also employed deep nesting in special purpose situations code where it could be naturally decomposed into subfunctions, but those subfunctions would themselves be extremely brief with near-zero chance of reuse. At that point the overhead of function decomposition can rival the time to actually get it working, so unless there's a dramatic improvement in clarity or I've got time to spare, I'm unlikely to bother.

      --
      --- Most topics have many sides worth arguing, allow me to take one opposite you.
    3. Re:Code doesn't need punctuation by guruevi · · Score: 2

      The problem is and remains readability, not testability. You can perfectly test minified JavaScript (all the superfluous is removed). Additionally, your code may test correctly but still not give the results expected, especially when you're doing things like write mathematical code or image processing (you can't test for correctness if you don't know the result yet). Manually scrolling and looping through a program in your head is not easy with everything is in superfluous functions. And that is precisely the code where you'll easily go 5 loops or more deep and left spinning, dazed and confused with a beginner language like Python.

      --
      Custom electronics and digital signage for your business: www.evcircuits.com
  6. When it reduces the cognitive burden by El+Cubano · · Score: 5, Insightful

    When Do You Include 'Unnecessary' Code?

    Here is how I make the determination: if it reduces my cognitive burden now, later when I return to the same code, or other programmers who will have to maintain it, then I include it

    These days, a programmers time is nearly always far and away the most expensive commodity employed in any project. Why should I spend time asking myself about minutiae rather than focusing on architecture and algorithms?

    1. Re:When it reduces the cognitive burden by Greyfox · · Score: 3, Insightful

      "These Days?" They invented OO because the maintenance phase of the project was always very expensive, and they were looking for ways to reduce those costs. Fortunately they solved that problem with Agile -- now you just work on the project for years until it's done, then throw all the code away and start over again. No maintenance costs, it's genius!

      --

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

    2. Re:When it reduces the cognitive burden by Anonymous Coward · · Score: 1

      These days, a programmers time is nearly always far and away the most expensive commodity employed in any project.

      This is perceived and industry best practice wisdom... but it's not actually true. The problem though is that the real cost is almost never accounted for: The cost to the end-user of using, or having to use, your software, complete with required hardware upgrades, time lost in frustration, to software failures, opportunities lost because some piece of software or perhaps cloud-supporting hardware threw a kink or coughed up smoke, and all that. Much of that remains invisible, but the costs are real nonetheless.

      Of course, the cost to an individual end-user is typically less than the cost of a single programmer even without his fancy shmancy hardware and toys and perks and things to keep him happy. But there are typically far more end-users than programmers.

    3. Re:When it reduces the cognitive burden by Anonymous Coward · · Score: 1

      Constantly throwing away existing code and replacing it with new code is neither the fault of agile methodologies nor did it start with them. It is far better explained by the overwhelming proportion of young, inexperienced coders, which is only reinforced by rampant ageism.

  7. Semantic whitespace is stupid by Anonymous Coward · · Score: 1

    Not terminating statements with a semicolon means you're using semantic whitespace. Semantic whitespace is stupid. And the proper whitespace style is "tabs to indent, spaces to align". It's a courtesy to people who favor other tab widths.

  8. Only if it improves readability by anarcobra · · Score: 1

    If I think it makes the code looks cluttered I will remove it.
    If I think it makes things more clear then I will put it in.
    For instance, braces for if else where one of the branches is more than 1 line and the other isn't.

    1. Re:Only if it improves readability by BlackHawk-666 · · Score: 1

      Agreed, if one branch is more than one line - and disagree if they are both only one line, or there is only one branch.

      --
      All those moments will be lost in time, like tears in rain.
  9. Code should be as concise as possible. by Hans+Lehmann · · Score: 5, Funny

    I never use variable names of more than one character unless all possible single character names have already been used, which rarely happens. I never indent blocks; extra white space is only superfluous. I never do in six lines of code what can be done in one long convoluted line. If the person that needs to maintain my code can't make sense of it, too bad. They're probably just a sloppy programmer.

    --
    09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0
    1. Re:Code should be as concise as possible. by elrous0 · · Score: 1

      I second this, and also add that I like to throw in a bunch of superfluous methods in all my classes that are very complicated and are never called.

      --
      SJW: Someone who has run out of real oppression, and has to fake it.
    2. Re:Code should be as concise as possible. by Anonymous Coward · · Score: 2, Insightful

      You use variable names? That's so last century! Modern code doesn't use named variables:

      postMessage(story("https://developers.slashdot.org/story/16/07/23/0357235"), createMessage(MsgType.ACPost).addSubject("Re:"+previousMsg().subject).addGenderNuteralBody(createText("You use variable names?"+Spacing.Sentence+"That's so last century!"), Lang.English).convertTo(OS.getDefaultLang()))

    3. Re:Code should be as concise as possible. by AchilleTalon · · Score: 1

      I never read code unless it is actually called. So, your superfluous methods just generate yourself superfluous work.

      --
      Achille Talon
      Hop!
    4. Re:Code should be as concise as possible. by Waffle+Iron · · Score: 1

      I never use variable names of more than one character unless all possible single character names have already been used, which rarely happens.

      If you're not routinely using up all possible single-character variable names, then you're not making your functions large enough, and/or you're not using enough global variables. You can do better.

    5. Re:Code should be as concise as possible. by lgw · · Score: 1

      One-letter variable names alone provide far too little job security, except for l and o. This is much better code:

      for (godzilla=pokemon, godzilla+=l; godzilla<jesus)
          lllillilil = llliliilil + llillilill;

      Did you think I was adding one to godzilla in the for clause? You're not worthy to maintain my code. Seriously, I got stuck maintaining a code base where some genius used l as a variable name everywhere - he now works for Microsoft Research (not making that up).

      --
      Socialism: a lie told by totalitarians and believed by fools.
    6. Re:Code should be as concise as possible. by elrous0 · · Score: 1

      Then I clearly need to step up my game and have them call one another for no reason that anyone reading my code will ever be able to understand.

      --
      SJW: Someone who has run out of real oppression, and has to fake it.
    7. Re:Code should be as concise as possible. by uncqual · · Score: 1

      It sounds like you should just switch to writing your code in APL - or maybe you already did...

      --
      Why is there an "insightful" mod and why isn't it "-1"? If I wanted insight, I wouldn't be reading /.
    8. Re:Code should be as concise as possible. by Immerman · · Score: 1

      Ideally such functions will contain several pages of incredibly complicated looking code that will be completely optimized away in release builds, but exhaustively execute for debugs and traces, and require months of careful human analysis before anyone else can be completely certain of that fact.

      --
      --- Most topics have many sides worth arguing, allow me to take one opposite you.
    9. Re:Code should be as concise as possible. by goose-incarnated · · Score: 2

      Then I clearly need to step up my game and have them call one another for no reason that anyone reading my code will ever be able to understand.

      You do. You really do. Until you do, we're revoking your evil overmind badge :-) Here is a function that is never called but cannot be easily proven to be called or not:


      struct usethisoften {
      ...
      };
      ...
      void usethisoften (void) {
      printf ("Doesn't get called!);
      }
      ...
      typedef void (*ftype) (void);
      ...
      ftype foo[] = {
      funcs, that, get, called, usethisoften, otherfuncs, go, here, will not get called,
      };
      ...
      foo[somevar % sizeof (int)] (); // Here it never gets called!!! Looks harmless

      Just ensure that the 'usethisoften' struct is used everywhere. The last line that can never call your "don't-call" functions will be glossed over by the maintainer who assumes that you're simply trying not to overrun the array because they've still got another 1500 occurrences of "usethisoften" to double-check.

      Bonus: if this is ever discovered you can claim it was an honest error! Plausible Deniability!

      --
      I'm a minority race. Save your vitriol for white people.
    10. Re:Code should be as concise as possible. by Zeroko · · Score: 1

      I have run out of Latin letters & started using Greek ones a few times. In my defense, I was just grabbing elements of small nested lists (via Haskell's pattern matching) & permuting them, & a comment saying what the permutation meant (or better yet, a good function name) would be a lot clearer than trying to give meaningful names to 32 (or however many it was) variables used only once.

    11. Re:Code should be as concise as possible. by mmdurrant · · Score: 1

      I call this the Charlie Sheen pattern: why do it in multiple lines when you can do it all in one?

      --
      I see my shadow changing, stretching up and over me...
    12. Re:Code should be as concise as possible. by Jeremi · · Score: 1

      I never read code unless it is actually called. So, your superfluous methods just generate yourself superfluous work.

      Time to add in some superfluous calls to those methods, then? :^)

      --


      I don't care if it's 90,000 hectares. That lake was not my doing.
    13. Re:Code should be as concise as possible. by Dog-Cow · · Score: 1

      Those other funcs might be called if `int` is 8 bytes. If you're going to obfuscate, you'd better make sure your obfuscation isn't buggy.

    14. Re:Code should be as concise as possible. by goose-incarnated · · Score: 1

      Those other funcs might be called if `int` is 8 bytes. If you're going to obfuscate, you'd better make sure your obfuscation isn't buggy.

      Yeah, but if you code in a check for sizeof(int)==4 then they're onto you - there's no plausible deniability :-)

      --
      I'm a minority race. Save your vitriol for white people.
  10. View from on high by Okian+Warrior · · Score: 5, Insightful

    I used to make firmware that goes into aircraft instruments. The FAA has some guidelines on this.

    Unnecessary code is generated machine code, and the rule is that you can have none of it. Source code doesn't matter, if it's ifdef'd out it's the same as commentary.

    The theory is that if execution takes an unexpected jump, it can't land in anything that isn't specific to the purpose of the device. Some people take this to extremes, writing new versions of printf() that omit the floating point and pointer output formats when they're not used in the system.

    However, if a buffer overflow causes the program to jump, it can't land in the middle of the pointer formatting section and send a pointer to the airspeed computer instead of the decimal altitude.

    What the OP is talking about is unnecessary source, which is a different matter.

    IBM did studies of bug frequency, and concluded that the number of bugs in a program depends on the number of source lines a programmer can see at any one moment. Big screens allow the programmer to view more lines of code at once, little screens require reading the code through a soda-straw.

    Their studies showed that simple code-tightening techniques reduced the number of bugs. Placing the brace on the if-statement, for example, allows one more line to be viewed in the window. Omitting braces altogether for single-statement "if" saves another line. Using 120-char width lines instead of 80 allows fewer wrapped lines, and so on.

    There is a competing goal of readability, so tightening can't be taken too far. The complex perl-style or APL-style "everything on a single line" construct goes the opposite direction - too much info and it becomes hard to understand at a glance.

    Typical C-like syntax with line-tightening techniques is easy to read, and presents probably an optimal view of code to the engineer.

    Braces on their own act like vertical whitespace. Requiring one-and-only-one exit from a subroutine leads to convoluted and chevron code (where the code looks like a big sideways "V" and the hints of indenting is lost). Requiring all definitions at the top of the module requires the reader to flip back-and-forth, and requiring Hungarian notation makes the code look like gobbledy-gook.

    Dump it all.

    Name your variables clearly, using nouns for objects and verbs for actions. Name your subroutines after their functions. Tighten your code to make it terse, but keep it readable.

    1. Re:View from on high by Z00L00K · · Score: 1

      However omitting braces is not necessarily a good thing because it's easy to get really nasty bugs if they are omitted.

      --
      If builders built buildings the way programmers wrote programs, then the first woodpecker would destroy civilization.
    2. Re:View from on high by Anonymous Coward · · Score: 1

      When was this study made? I'm going to guess it was some time ago. This stuff just isn't applicable to modern code. It reads like it predates the adoption of OOP, and when people were still using 80x25 character CRTs. If you can't see all of the code in a procedure, maybe it's just too long. If you can't see the definitions without flipping, just another window. Don't use a monitor that's too small. Maybe get another monitor. If there's a big sideways "V", your procedure is too long. Try using sub-procedures.

    3. Re:View from on high by TechyImmigrant · · Score: 2

      It's great now that we have huge screens, we don't have any more bugs.

      --
      I should use this sig to advertise my book ISBN-13 : 978-1501515132.
    4. Re:View from on high by Megane · · Score: 1

      If braces aren't put on single-line if or else conditions, that leaves the possibility of a bad code merge causing a goto fail situation. In the worst case, if you keep open braces on the same line (1TBS like "} else {"), you add one line over naked statements, which is still better than putting open braces alone on a line.

      So basically, it ensures that if a merge or patch slips in an extra line, it doesn't silently cause a change in code flow. It also keeps the unchanged if() expression out of the diffs when the sub-blocks are changed, which makes merges more reliable.

      --
      #naabhaprzrag, #sverubfr-000, #agi-fcbafberq, negvpyr[pynff*=' negvpyr-ary-'] { qvfcynl: abar !vzcbegnag; }
    5. Re:View from on high by byteherder · · Score: 1

      Most of these guideline above do not enhance reliability. The object is not to make your code look like it came from an obfuscated C contest.

      I put the open curly brace on its own line. Not that it needs to be, but because it enhances the readability of the block of code contained.
      Readability == Less bugs

      One exit from subroutines/functions/methods makes it easier to debug. Definition at the top, makes it easy to find variable type and initialization, instead if hunting through all the code trying to find the definition. Though a good IDE will handle most of that for you.
      All this saves programmer time and makes for easier maintenance.

      The OP says "unnecessary code -- e.g., variable declarations..." who doesn't declare their variables. I would hate to debug that code.
      Also, who considers error handling, unnecessary code. Critical or not, the programmer should catch and handle every type of error he can. It's called robustness.

      All this "unnecessary code" has a purpose, enhanced readability, less bugs, faster debugging, easier maintenance, stability. All these young bucks could stand to take a lessen or two from the grey beards.

    6. Re:View from on high by NormalVisual · · Score: 1

      Requiring all definitions at the top of the module requires the reader to flip back-and-forth

      This is true, but if you define the variable in the middle of something, and it's used somewhere other than just after the definition, you can end up playing hide and seek trying to find the definition, and can sometimes encounter unexpected scoping issues if you're not paying attention. I would probably say that it's better to define them at the beginning of the scope in which they're used.

      --
      Please stand clear of the doors, por favor mantenganse alejado de las puertas
    7. Re:View from on high by Anonymous Coward · · Score: 1

      There was this study saying the best readable text is about 65 characters to a line, which goes well with 80 cols and one or two levels of indentation. That is also why I stuck on 80x40 xterms: Nice and easy to read in a big font (eg the xterm default huge font), good screen use, more code on the screen than in 80x25. There's also that reasonably printable text is amendable to, well, printing, which comes in handy on occasion.

      It's also compatible with code sharing: Not all of us like (or can easily read) 200+ character lines, with or without wrapping. I don't think longer lines without wrapping is a good idea, in general, and not just because of poor line readability. There's also that if you use really long function names and other overly long constructs that make you run out of horizontal space, your abstractions aren't working very well. Or the abstractions of the systems you're working with. Looking at you, java, and windows. So if you have umpteen nearly-identical constructs in your code, with many parameter values, all mostly the same, it's time to add a (static inline) wrapper to bring back readability and to make the differences stand out more.

      Personally I do try and stick to the single return thing if reasonable. IOW if there's not a lot of visual difference we'll go with the fewer return statements. Like a function containing basically one switch where each case sets the return variable instead of doing the return. Or a linear search where you could return or break just as well. Some things work better with multiple returns, some don't. And anyway, functions oughtn't be too long. "Three to twelve lines" in the words of an acquintance, but I personally stick to somewhat less than a single screenful, and to functions that do only one thing. Functions where single character variable names can make sense. If they start to get confusing, the function is certainly getting too long. I just have to trust that static inline will do its thing. Many of my functions get called exactly once, yes. So what I look for is to write building blocks and then write the building with them. Or rather the blueprint to the thing, being the source code. In a sense it should tell a story, and it should do that, at least to the programmer reading, coherently.

      The sticking point discussed here, of course, is the requirement or the banning of specific superficial features. If this makes a noticeable difference on the craftsmanship of your programmers, their craftsmanship wasn't very great in the first place. Still, a common enough occurrence. tdwtf is filled with examples.

    8. Re: View from on high by BlackHawk-666 · · Score: 1

      I haven't printed out my code since 1988.

      I understand the sentiment, but it's just really not true anymore. Even just having a CRT makes following that rule unnecessary, let along a modern LCD which can easily handle 160 x 80 lines of code. Even still, I would never arbitrarily format my code to fit the screen resolution of the device I was currently using. To paraphrase the words of Fight Club "Code will go on as long as it needs to.".

      It's just not true that a programmer needs to read the whole damn function on a single page, at least...not since the invention of the Page Up and Page Down keys.

      I'm working with some code (written elsewhere) which includes functions over 1000 lines long. While this is very definitely the other end of the argument, those functions are that length for a reason - they are doing something really complex that is just one function.

      I'll probably refactor those all down to a few hundred lines each or fewer, when I get the chance. But I won't consider the length of my screen when I do it - rather, the natural break down points of each function. Even so, doing that will introduce something new and weird to the project. Instead of the functions being explicitly defined, and only the functions - now it will need to define all the sub-processes that are needed to make them happen. Something is lost in doing that, high level clarity.

      --
      All those moments will be lost in time, like tears in rain.
    9. Re:View from on high by BlackHawk-666 · · Score: 1

      Current wisdom is to define variables just before, or exactly as, you use them. This benefits the compiler as well as readability and cut and paste.

      e.g.

      vec3 v = OtherVec * SomeQuat;

      vec3 abc = v * OtherQuat;

      Your IDE will let you know pretty quick if you cut and paste it wrong. The CPU will thank you for your declarations and assignments, especially if it can shortcut some of it.

      --
      All those moments will be lost in time, like tears in rain.
    10. Re:View from on high by angel'o'sphere · · Score: 1

      Never experienced such a bug, not in my code nor in others.
      And no: if not forced by stupid code formatting rules, I only use { and }, when it is actually needed.

      --
      Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
    11. Re:View from on high by tepples · · Score: 1

      Using the value of a variable before it is declared produces undefined behavior. Giving a variable a value when you declare it reduces the possibility that undefined behavior will occur.

    12. Re:View from on high by ebvwfbw · · Score: 1

      Seems to me that back in the 1990s they found that a programmer writes about 13 lines of correct code a day on average.

  11. Readability wins every time by paavo512 · · Score: 1

    In professional software development, the general idea is clear: if any non-functional change in a source code file makes it more readable and more maintainable, then it's good, and vice versa. You write the thing once and it has to be maintained for years. This is actually called code refactoring, which is part of several methodologies.

    Code refactoring may mean either adding or deleting code. There ought to be a golden middle point somewhere where the code is neither too verbose nor too condensed.

    There is a slight complication in that not every person agrees what is the most readable form for a program, but in general it's best to imagine that you may have a total autobiographical amnesia in the next day and still need to understand what the program does.

    1. Re:Readability wins every time by R3d+M3rcury · · Score: 2

      Speaking of readability, here's an entertaining one I've been seeing more of in C:

      if (result == SUCCESS)
      versus
      if (SUCCESS == result)

      The rationale behind the second is that you don't end up accidentally assigning SUCCESS to result (eg, if (result = SUCCESS)). But I know that I find it weird to look at it the other way around. I want to know if the result was successful, not if successful was the result. Maybe it's an english thing.

      I know that Xcode has been putting up warnings/errors for code that does assignments in if-statements and saying that if you really want to do that, wrap it in an extra layer of parentheses (eg, if ((booleanResult = Do_Something()))). I'm not sure this is somehow more clear that you're doing the assignment...

    2. Re:Readability wins every time by NormalVisual · · Score: 1

      But I know that I find it weird to look at it the other way around. I want to know if the result was successful, not if successful was the result. Maybe it's an english thing.

      I find it kinda weird too, but IMO it's a small price to pay for avoiding bugs that are sometimes pretty difficult to track down. I also tend to add parentheses where they're strictly not needed because I don't count on everyone knowing the rules of precedence. I've seen people get bit by something like "if( i & 0xff == TRUE )" before because they don't remember that in C/C++, "==" is evaluated before bitwise operators.

      --
      Please stand clear of the doors, por favor mantenganse alejado de las puertas
    3. Re:Readability wins every time by paavo512 · · Score: 1

      Speaking of readability, here's an entertaining one I've been seeing more of in C:

      if (result == SUCCESS) versus if (SUCCESS == result)

      The rationale behind the second is that you don't end up accidentally assigning SUCCESS to result (eg, if (result = SUCCESS)). But I know that I find it weird to look at it the other way around. I want to know if the result was successful, not if successful was the result. Maybe it's an english thing.

      I know that Xcode has been putting up warnings/errors for code that does assignments in if-statements and saying that if you really want to do that, wrap it in an extra layer of parentheses (eg, if ((booleanResult = Do_Something()))). I'm not sure this is somehow more clear that you're doing the assignment...

      In proper C++ this would be

      if (bool booleanResult = Do_Something()) {

      or more usefully

      if (AClass foo = PrepareFoo()) { DoSomethingWith(foo); }

      This does not generate those assignment warnings, is in the right order for readability and does not need obscure extra parens.

    4. Re: Readability wins every time by Fwipp · · Score: 1

      I prefer to use static analysis tools that will catch this sort of thing for me, rather than bend the code style so the compiler will catch it.

    5. Re:Readability wins every time by BlackHawk-666 · · Score: 1

      Competent programmers, never. It's only for the other ones.

      --
      All those moments will be lost in time, like tears in rain.
    6. Re: Readability wins every time by sydneyfong · · Score: 1

      I agree with your statement generally, but the commonly accepted solution against unintended assignments in the if conditional is to add an extra set of parenthesis -- which is literally bending code style so that compiler (at least the static analysis tool) will catch violations.

      --
      Don't quote me on this.
    7. Re:Readability wins every time by Zeroko · · Score: 1

      Just because math or programming allows something does not mean it should be done. Conventions help with readability & thus avoidance of bugs.

  12. Code should read like a good story by Anonymous Coward · · Score: 2, Interesting

    A function should read like a good short story. Set the scene, develop the characters, advance to the climax, then there's the denumont/ epilog (sp?) where loose ends get resolved. Add comments if the story is hard to follow, don't if it's not. If the story is too long, create some helper functions.

    A dash of humor here and there helps keep things entertaining, but go easy on it.

    Remember, some software archaeologist may have to go back in 5 or 10 years and figure out what the heck the code does to fix a problem -- and that guy may very well be you.

    I'm completely serious. This is what I do, and I actually enjoy going back through my 10 year old code (I've got a nice stable job)

  13. Code Style for Effectiveness vs Purity by Fringe · · Score: 1

    I've seen a lot of style wars - tabs vs spaces, braces starting same line vs next line vs omitted when possible, commented enums required (especially by European companies using StyleCop), etc.

    All of that is unnecessary from a compiler perspective. But the style you are accustomed to aids your efficiency and effectiveness. Code doesn't care if it's consistently indented, but finding that unbalanced loop is much easier with it.

    For me personally, since I'm in C++, Java, JavaScript/Node (never by choice), Groovy, C# and Python every week, style consistency for me, rather than optimizing for what zealots for a particular language want, is highly beneficial. So the Groovy gets semicolons. The inability of JavaScript to handle certain brace formattings resulted in me modifying my default across all the languages, because they other (real) languages don't care.

    Use what makes you personally across all your development, and more importantly your entire team, faster and better.

  14. I avoid reliance on operator precedence by iceco2 · · Score: 3, Informative

    I add "unnecessary" parentheses to complex expressions in order to avoid the mental burden of thinking of operator precedence. I instruct my team to do the same.
    Obviously if I can name a sub expression reasonably I just extract it, this is often enough not a reasonable solution.
    Usually I prefer terse code, but the above is a fairly common exception.

  15. Nothing Listed is Unnecessary by Bender0x7D1 · · Score: 1

    The items listed in the summary aren't unnecessary - they are good practices. Readability, ease of maintenance, debugging and error-handling are all good things, and SHOULD be included - even if they aren't needed in a specific instance.

    Car analogy: Most cars never need to have airbags, but we put them in because they are a good idea. The same should go for the listed code constructs - they should be there for the times it does matter.

    --
    Reading code is like reading the dictionary - you have to read half of it before you can go back and understand it.
  16. Parenthesis by Alomex · · Score: 1

    I over parenthesize C/C++ expressions. There are so many precedence levels that it is easy to forget who goes first**. There's a limit of course, I wouldn't write 4+(5*6) but I would certainly fully parenthesize:

    x = 4*A|| B? C||D: E && F || G +3;

    ** Brian Kernighan admitted to having the table of precedence glued to his monitor, since he himself can't keep them straight.

    1. Re:Parenthesis by angel'o'sphere · · Score: 1

      The post would have made more sense if you had shown us where you would have placed the parenthesis ... I see no reason for one, but I might be blind.
      However I find the badly placed ? and : annoying :)

      --
      Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
    2. Re:Parenthesis by Alomex · · Score: 1

      x = ((4*A) || B)? C||D : E && F || (G +3);

      My rule it that if you have to even think more than a second about precedence then there is somewhere out there who will misinterpret it.

      By the way Kernighan claimed that he should have done pemdas+left to right associativity between operators of the same precedence, instead of the present 15 levels of precedence in C and sixteen in C++.

    3. Re:Parenthesis by angel'o'sphere · · Score: 1

      You still have the '?' misplaced :)
      And frankly: the '(' and ')' add nothing fo me, they are just PERLish line noice IMHO.
      On the other hand: I never counted levels of precedence either.
      Never had guessed it is 15 or 16.

      (You know, I had math in school, albeit it is over 30 years ago, if it is not a language like SmallTalk, which is strictly left to right, I have no problem to grasp the meaning of a complex expression at first glance ... but that might be just me).

      --
      Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
  17. Re:Rick Wicklin is an idiot. by cathector · · Score: 1

    true that. also semicolons are optional in javascript. for ordinary statements you can simply leave them out.

  18. You mean "documentation" ? by rbrander · · Score: 1

    I also write notes to people, like this one, with the usual amount of English that isn't really necessary - like a quarter of the words in this sentence.

    A certain amount of redundancy in communication is still around, though, yes, languages tend to drop and slur words over the centuries. Interestingly, military communications, where you'd think speed was very important, tend to be written quite formally, that is to say, with lots of that redundant English. Turns out that clarity is even more important than speed when lives are on the line!

    I bet that your really important code that runs SCADA and other real-word systems has the most ponderous, overstated, tedious and obvious code of all. The same way that surgeons say, "Hand me the #3 rib spreader" rather than "Gimme that" while gesturing in a general direction.

    Actually declaring and destroying your variables - stating what they are in clear, rather than by implication, and making clear when they are no longer needed - should be considered documentation for the programmers, even if the mechanism will perform identically without it.

  19. I'm in my sixties by Intron · · Score: 4, Funny

    Since I make a ton of money, and my boss is itching to fire me and replace me with a Syrian refugee who will work for cafeteria scraps, I make heavy use of 6-level deep macros and the C downto operator: while (i --> 0)

    --
    Intron: the portion of DNA which expresses nothing useful.
  20. Xtra code when there is no cost by mysticgoat · · Score: 3, Insightful

    Caveat: I am retired. Programming was a major part of my career between 1995 and 2005 but I mostly do HTML/CSS these days, with only enough PHP to glue others' existing scripts together.

    What I determined back in the day is that efficient coding is unnecessary for performance when the wetware BKAC would always be the primary limiter on speed. Since virtually all of my work was repurposing documents from old versions of Word, Excel, WordPerfect, Lotus1-2-3, and other outdated apps to newer standards (mostly early HTML), I did not have to worry about shaving off microseconds. The typing speed of the person selecting the raw data had more impact on performance than the programming. So I was much more concerned with whether I would be able to rewrite a handler for a Windows3.11 app to work on a Windows98 version, if that need arose.

    So I worked mostly in Perl using the Tk graphic interface and Javascript front ends, which made rapid development and easy revisions to meet new criteria possible. I used explicit declarations, human-readable naming conventions, extra punctuation, and the long way around the barn whenever the shorter routes looked like they might cause head-scratching later on.

    If I had been working in an environment where microseconds counted, I would have used a compiled language and a different approach.

    My old-timer's advice to you young'uns: Look at the environment you are coding in and match your coding style to fit its shape. Eschew becoming the cleverest code monkey in the cube farm and focus instead on becoming wiser than all the others.

  21. Whenever I want really... by RyanFenton · · Score: 2

    I code for thousands of mostly-unique commercial software products a year, using 8 languages (mostly C#), for many dozens of major customers, and lots of smaller ones.

    Because of this, I have a huge chain of demands I keep track of, and methods of automation in order to collectively manage a constant flow of data requirements, and of course tracking issues both shared and common between these scenarios.

    When I'm coding, I've got to code in a way that communicates these details to myself, consistent between all the languages I might have to touch for coding, scripting, database, reporting, and specialized languages a client may suddenly require.

    Because of that, my code has to be a loose framework, a late-binding train station of logic, where demands may switch at any moment, and limitations imposed from other teams may similarly pop up.

    My code is littered with multi-paragraph discussions of a technology I once had to interact with (customers often switch back), large sections of functions commented out rather than deleted, and other 'bad' practices just to give me landmarks and a 'flavor' of what a customer is occasionally interested in, amidst a never-ending avalanche of context switching between products and customers.

    I've redesigned these several systems from the ground floor once (they used to only handle a small fraction of the work, using an antiquated language), and am working with a team to do a better design... but it's been very difficult for a team of perfectionists to understand how to react to an unlimited flow of changing requirements. Fortunately, the code itself has been quite usable, and they're using the same languages, but no system can really handle these demands truly consistently - I'd call it NP ridiculous. It's basically the "mythical man month" writ live, where I've got to do my work, and train a team whose work process may never really be able to do what I can do - definitely healthier long term, but can't help but result in some amazing process failures.

    I actually would have made most of these design changes myself, but at the time, I was forbidden by management from making those choices, since I was doing my work directly at the production level - so it's actually a bit of a relief to see someone at least allowed to make some of the better choices.

    In short (and yes, for this scenario, this is short), because I'm doing alone, for years, what a team of almost any size would struggle to approximate, as many of us seem to be doing, I've got no choice but to code how I need to in order to have a system that I can sanely maintain in an insane set of requirements. There's not really a choice in the matter, if your put in a position where "oh, we suddenly need this" exists as a live production task in a growing industry.

    Ryan Fenton

    1. Re:Whenever I want really... by 110010001000 · · Score: 1

      I call bullshit. Thousands of products per year? There are only 365 days in a year. And you have the time to write this gibberish on Slashdot?

    2. Re:Whenever I want really... by RyanFenton · · Score: 1

      I know, it DOES sound absurd, and in practice, it is. Now, it's "only" around 800 individual products actually delivered fresh each year, but because I'm having to touch and test older games as a part of that process, I'm in effect coding for thousands of shipped products per year, just to make it as sane as possible to continue each product line.

      And yes, that means each day, I'm jumping between 15 minute mini-projects, reviewing and raising issues on design documents, throwing together project directories and rapidly configuring them, throwing those project into automated testing suites of tools (which I'm also cross-developing), testing the various inputs/outputs of other teams to make sure nothing will prevent delivery to spec.

      I'm making active progress on around a dozen separate projects each day, contacting clients as needed to hammer out shared documents, then reacting to rare but important issues as they are raised.

      Ryan Fenton

    3. Re:Whenever I want really... by angel'o'sphere · · Score: 1

      Well, if you need assistance, I call my self 'Software Generalist' on my business cards.
      I gladly assist,

      I'm especially good in shoulder massages, fetching coffee and siftdrinks and as I have a martial arts education, I can keep every one - unless armed with a Panzerfaust - out of your office room.

      Deal?

      P.S.
      I'm a retired gamer, too. I can easily tell you which games are mot worth supporting anymore. E.g. Pokemon.

      --
      Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
  22. Re:Almost never by TechyImmigrant · · Score: 1, Informative

    I usually write all my C++ if statements, even if they contain just one statement, with curly brackets. I read somewhere it was better to do this, but I can't remember why.
     

    It's a land mine. When you later add a second line to the conditionally executed section, you then need to notice the lack of braces and add them or you will not get the intended behaviour.

    --
    I should use this sig to advertise my book ISBN-13 : 978-1501515132.
  23. Re: Happy Saturday from The Golden Girls! by Anonymous Coward · · Score: 3, Insightful

    Maybe because you are a douche?

  24. Re: When by bondsbw · · Score: 1

    The sad thing is, some people probably do get paid by LOC.

    --
    All my liberal friends think I'm a conservative, all my conservative friends think I'm a liberal.
  25. The golden rule of code writing by ealbers · · Score: 1

    Write code in a way you'd like to read it, if you didn't write it and had to fix/extend it.

    If you've been programming since the early 80's, you've probably had to go back to code you wrote 10+ years before on occasion.
    If its written well, (haha) with good comments and variable/function names, you'll spend almost no time getting it to work again.
    Clarity is key, avoiding writing code which makes debugging difficult, I often create a local var and pass it to a function when I could just put it in the function call. Why? Well, I can easily look at it in the debugger, the little extra effort of a local var gets optimized out anyway, and it makes debugging a LOT faster.

    1. Re:The golden rule of code writing by BlackHawk-666 · · Score: 1

      +1 for writing code that you need to read 10+ years later

      --
      All those moments will be lost in time, like tears in rain.
  26. I use it when it makes things better by JohnFen · · Score: 1

    Some "unnecessary" code can be very necessary to improve human understanding of the code and maintainability. When I use it, that's why.

  27. Never - But Because Your Definition of Unnecessa.. by brian.stinar · · Score: 3, Interesting

    If you believe that code will help someone with understanding (yourself included) then it is necessary. It is needed to help with clarity. It may not be strictly required for the correctness of your program, but your goal should not be to express the correct solution as succinctly as possible. That approach leads to many other problems.

    Occasionally I include solutions for problems which have not yet been uncovered. Those methods may not be called (dead code) and any kind of static analysis would report them as "unnecessary." If I make the decision that such code will help me, or help someone else, later then I believe it is totally necessary, and good to include. Worse-case is that it will be a good starting point for someone later, and they will throw it away and replace it with something better.

    Never include unnecessary code. If there are incorrect implementations that you are replacing, remove the incorrect ones! Don't leave traps lying around for people to get caught in. Unexecuted code, or not succinct code, is not unnecessary. I constantly include semicolons, and brackets around one-line conditionals - those are defensive practices which are designed to prevent future problems, and aid in clarity.

    This is why people are hiring you - to apply human intelligence and judgement to a problem. There are situations where doing not strictly necessary things is appropriate, and situations when doing not strictly necessary things is a waste of time. It's up to you to decide. Different actions are necessary for different metrics. One thing may be necessary for a correct solution, and another thing may be necessary to help someone else understand your correct solution. Everything should be useful (necessary?) under some kind of metric.

  28. Depends on the audience by Morpeth · · Score: 1

    If it's just for myself or a personal project, little comments or extraneous stuff

    If a junior programmer or someone I haven't worked with before will be using it in some fashion, I'll probably use more descriptive variable names, more comments, even formal comment blocks describing a given method/function, etc.

    But regardless of who it's for, I always use proper indentation, consistent naming conventions, etc., just makes life easier all around.

    As far as error handling, again, depends on the audience, if there's an end user product where it really matters, then absolutely have thorough handling; if it's an internal app used by the dev team, probably stick to handling critical errors for the most part.

    --

    'The unexamined life is not worth living' - Socrates
  29. Unnecessary semicolons? by aglider · · Score: 1

    Since when are semicolons considered code?

    --
    Sent as ripples into the electromagnetic field. No single photon has been harmed in the process.
    1. Re:Unnecessary semicolons? by angel'o'sphere · · Score: 1

      Hae?
      In a langugae that requires semicolons?
      What else should they be ?

      Look! This is a for loop:

      for (int i = 0; i < max; i++ ) ....

      Nevermind the ';' they actually don't belong to the code ...

      --
      Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
    2. Re:Unnecessary semicolons? by aglider · · Score: 1

      In all languages I know that use semicolons, extra semicolons are never extra code. Just extra semicolons.

      --
      Sent as ripples into the electromagnetic field. No single photon has been harmed in the process.
    3. Re:Unnecessary semicolons? by Blaskowicz · · Score: 1

      It's some kind of "do nothing" operation?, like a function which immediately returns void.

      I think that if you write

      if (condition);
              do_something();

      you're actually doing

      if (condition) do_nothing();
      do_something();

      so your test is ruined.

    4. Re:Unnecessary semicolons? by aglider · · Score: 1

      It's some kind of "do nothing" operation?

      So everyone is a coder, then!
      Extra semicolons are not (and never will be) extra code, just like extra newlines are neither extra code (in programming) nor extra text in (type)writing.
      I could agree that semicolons can be seen as "code" because needed by syntax rules.
      But I won't ever agree that extra semicolons are extra code.

      --
      Sent as ripples into the electromagnetic field. No single photon has been harmed in the process.
  30. Money by krray · · Score: 1

    I get paid by the line you insensitive clod

    1. Re:Money by Ginguin · · Score: 1

      My code would rapidly devolve into a monster if that were the case. It would also be horribly inefficient since I would probably spend less time thinking things out beforehand. The output will definitely reflect what they reward... and rewarding by line seems like a bad idea.

      --
      "Anything you say can and will be used against you in a targeted advertisement" - Adam Harvey
    2. Re:Money by Immerman · · Score: 2

      /*
      That's
      fine
      ,
      good
      code
      should
      be
      well
      commented
      */

      --
      --- Most topics have many sides worth arguing, allow me to take one opposite you.
  31. In C/C++ by Areyoukiddingme · · Score: 1

    Redundant semicolons at the end of macro instantiations that have an embedded semicolon. Because code editors try to auto-indent the next line if it's not there. Both the extraneous semicolon and the auto-indent make me twitchy, but... other people's libraries. What can you do.

    1. Re:In C/C++ by cathector · · Score: 1

      don't do that.
      the editor is not the boss of you.

  32. What does SAS stand for? by ark1 · · Score: 1

    SAS = Semicolon After Semicolon
    Old SAS joke

    1. Re:What does SAS stand for? by mekkab · · Score: 1

      Haven't SAS'd in over 20 years but lol'd all the same.
      Honestly, habits die hard. I hit ESC three times in vi, but I don't "think" I'm OCD...? :)

      /Wonders how many /.'ers know of SAS
      //Probably the same amount that know of Ada

      --
      In the future, I would want to not be isolated from my friends in the Space Station.
  33. Re:Almost never by BlackHawk-666 · · Score: 2

    Any c++ programmer with more than 1 years experience will see this immediately and slap some braces around it. Thanks to modern IDEs and standard indentation (which the IDE will auto-correct) it's extremely unlikely anyone will make this mistake, or it will go unseen for very long.

    I'd group this sort of 'error prevention' in the same category as putting the constant first in every if statement e.g.

    if (1 == YouShouldHaveDoneThisTheOtherWay)
    {
            Whatever();
    }

    The people who make the mistakes that this shit prevents have no place working on code.

    --
    All those moments will be lost in time, like tears in rain.
  34. Re:Reduction of unintended consequences by BlackHawk-666 · · Score: 1

    And that is why almost every country in the world uses SI units instead of outdated imperial measurements, like the US.

    --
    All those moments will be lost in time, like tears in rain.
  35. Re:Never - But Because Your Definition of Unnecess by BlackHawk-666 · · Score: 1

    Occasionally I include solutions for problems which have not yet been uncovered. Those methods may not be called (dead code) and any kind of static analysis would report them as "unnecessary." If I make the decision that such code will help me, or help someone else, later then I believe it is totally necessary, and good to include. Worse-case is that it will be a good starting point for someone later, and they will throw it away and replace it with something better.

    This is called YAGNI - You Ain't Going to Need It, and all it does is clutter code and make it harder to see what is truly needed vs what some programmer thought might be needed at some point in the future, if some things changed. Don't do it. Alternatively, place it in as scaffolding, but remove whatever elements aren't needed before you ship the code.

    Never include unnecessary code

    See above.

    I constantly include semicolons, and brackets around one-line conditionals - those are defensive practices which are designed to prevent future problems, and aid in clarity.

    No decent programmer needs these, and often they just clutter the code. Only put in the semicolons and brackets that are actually needed by the language.

    I agree with the final statements, though not the ideas you expressed which would be actionable items by those statements.

    --
    All those moments will be lost in time, like tears in rain.
  36. When it makes the code more readeable by DirtyFly · · Score: 1
    I tend to use so called unnecessary code when the codeneed to be human readeable.

    This may vary,if writing something that is intended to be read by novices or some funcition that in my understanding should be explained by more verbose code.

    I try to write self commented code where I can , and I'm a believer in simple to to read functions instead of 'virtuoso'code that needs heavy comments

    JC

  37. urgh by JustNiz · · Score: 1

    > block constructs for single statements

    This one bugs the snot out of me, especially when the braces don't line up.

    1. Re:urgh by Ihlosi · · Score: 1
      This one bugs the snot out of me, especially when the braces don't line up.

      Your coding standard might require that even blocks with single statements are enclosed in braces.

      My personal choice: If it's a single statement, it's in one line including braces. If it's more than one statement, braces get their own lines.

  38. Re:Almost never by TechyImmigrant · · Score: 1

    Any c++ programmer with more than 1 years experience will see this immediately and slap some braces around it. Thanks to modern IDEs and standard indentation (which the IDE will auto-correct) it's extremely unlikely anyone will make this mistake, or it will go unseen for very long.

    I'd group this sort of 'error prevention' in the same category as putting the constant first in every if statement e.g.

    if (1 == YouShouldHaveDoneThisTheOtherWay)
    {

            Whatever();
    }

    The people who make the mistakes that this shit prevents have no place working on code.

    You assume braces. BEGIN/END is less visually distinguished.
    You assume only one person will touch the code.

    Code for what might happen, not what your ego tells you you will get away with.

    --
    I should use this sig to advertise my book ISBN-13 : 978-1501515132.
  39. Re:Almost never by BlackHawk-666 · · Score: 1

    Code for what might happen, not what your ego tells you you will get away with.

    Experience tells me what might happen is that code and projects are broken up based on the experience of the teams working those code bases. You don't ever let an advanced code base get taken over by an inexperienced team. You will always have an A team, a B team, and the other guys. What is right for the A team is not right for the B team or the other guys - and it goes down the line.

    There is always going to be advanced projects in languages that most team members will shy away from or will be too damn hard for them to work with - that's totally fine. Your 'B' team is most likely the vast number of team members. The 'A' team are those members able to work at the highest level, whatever that is within your organisation. They will take care of the really awful projects that need kid gloves to keep working, and they will prefer doing that work - because they know that's where they are challenged.

    'B' team is the bulk of most teams. Your arbitrary rules are probably quite OK for these guys. They might even be best for most of these guys. Following the rules won't really harm them, as they will create / maintain code bases that also follow those rules - that's most code. Only the 'A' team members need to worry about code that breaks these sort of rules, and...why.

    If syntax is causing you issues, you are the other guys.

    --
    All those moments will be lost in time, like tears in rain.
  40. Re:C/C++ coding style by mekkab · · Score: 1

    Your style is admirable. Keep it up!

    --
    In the future, I would want to not be isolated from my friends in the Space Station.
  41. Re: Happy Saturday from The Golden Girls! by angel'o'sphere · · Score: 1

    Well as you post as AC we don't know which of ... cough cough ... "your posts" got modded down.
    That teaches you a lession, doesn't it?

    --
    Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
  42. Re:Almost never by angel'o'sphere · · Score: 1

    In all your wisdome you still made a mistake:
    You formatted your braces wrong!
    Sorry to point that out!

    --
    Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
  43. Re:Almost never by TechyImmigrant · · Score: 1

    I often have to go in fix problems caused by people's overconfidence. Everyone is fallible.

    I design chips, where the tolerance of design errors is substantially lower than for software. You can't just roll out a patch.

    --
    I should use this sig to advertise my book ISBN-13 : 978-1501515132.
  44. decent compilers will X that out by Maxo-Texas · · Score: 1

    Code is for humans.

    Extra code/white space usually means extra clarity.

    And most compilers will either remove unreferenced unused code or the code will only execute once anyway so there's no real performance hit.

    --
    She was like chocolate when she drank... semi-sweet at first and then increasingly bitter.
  45. commentsubject by Falos · · Score: 1

    Overcoding > Undercoding

    Gain increased readability and clarity of actions involved, with little bloat cost. Bloat and inefficiency are from reckless calls and libraries and imports and poor design, often a result of lazy/inept design.

    lol who cares phones have 4GB RAM anyway who cares the web container can run 16GB anyway, if the user doesn't have that much how is that my problem get an i7 faggots stop living in 2014.

  46. Re:Almost never by PhilHibbs · · Score: 1

    I put in semicolons, curly braces, line breaks, and indentation if they make the code more maintainable and clearer to the human reader. For example Microsoft T/SQL doesn't need semicolons at the end of SQL statements, but I put them in anyway.

  47. Re: Jews did 9/11 by PhilHibbs · · Score: 1

    Obviously this is off topic for a story on comments in code.

  48. On control systems it's a must! by EETech1 · · Score: 1

    I write a lot of embedded systems code, and everyone wonders why I check a timer configuration register that was already set at boot, or do an internal sanity check to verify everything is as I intended it to be before loading the timer (turning the output on) and then double check that the timer expired when I thought it should.

    Sooner or later someone reuses the code, ignores the comments and takes those checks out. Then you get the "randomly quits working until I reboot" hell that drives warranty and service crazy!

  49. SAS? Really? by Dahamma · · Score: 1

    How about "unnecessary language?"

  50. Re:Never - But Because Your Definition of Unnecess by Antique+Geekmeister · · Score: 1

    > Never include unnecessary code. If there are incorrect implementations that you are replacing, remove the incorrect ones!

    When possible, I comment them out with "wrapper" comments to preserve the code in the source control change history. And explain _why_ you've replaced the code, so the evidence is there for at least one or two more releases. It can be very difficult indeed to compare new code to the deleted code it replaces if you've successfully removed the visible traces of the deleted code.

  51. Use only the simplest necessary code by yes-but-no · · Score: 1

    Code should be rid of any fluff. Any description of what/how/why about the code should be in comments - well written and this is for human consumption; so it can be elaborate to avoid any misunderstanding. Code is written once but read/debugged many many times; Maintenance is the real cost. So you don't want to have noise in the code which takes a higher cognitive-load on your brain; your visual system too processes extra lines. These are unnecessary. Only after reading the code and thinking about it, you realize that code is harmless/unnecessary (eg while debugging or extending the software). The point is a line of code should have the least labor (cognitive/visual) from the human. A code which doesn't exist does this job the most perfectly. Hence write compact code; use standard libraries. Think at higher level of abstraction (like say containers instead of managing an array of objects); this needs spending lot more time in the design phase -- seeing the big picture of the various moving parts.

  52. All code is necessary. by Ihlosi · · Score: 1
    All code should be necessary. Either for the compiler, or for my own understanding, or for the next person trying to make sense of it.

    Strictly speaking, things like talking variable names aren't "necessary", the code will compile just find if you rename "error_flag", "sample_index" and "accu64" to "joe", "bob" and "alice".

  53. 1 and 2 character comments by drnb · · Score: 1

    Yes, code for the next person to work on it. And pray your predecessor did the same.

    Personally I think of the described semicolons as 1 character comments.
    And unneeded parenthesis in an expression are 2 character comments.

  54. Using doc comments right by tepples · · Score: 1

    It look better if the comment describes the actual effect that calling the function would have, plus what each argument means.

    /**
      * Sets the horizontal position of an actor.
      * @param x the distance in pixels from the left side of the map
      */
    void SomeClass::setX(int x)

  55. Re:Anything for work - by lpq · · Score: 1

    AC:"The goal is to make it so that anyone reading the class for the first time
    with no prior experience can understand its purpose and basic function
    without having to spend 5 minutes deobfuscating the code.That said, for
    personal consumption code, I don't generally bother going to that much effort
    to make my code clean/clear.
    ----
    and ^^ That said, I do the same for my personal code -- since maybe 10-15 years back when I started seeing code that I'd written 2-5 years before that I knew I had written, but looked totally foreign to me. As time has gone on and I write code that builds on code that builds on more code (much going into libs), AND as I am forced by ever changing priorities to work on more projects in "parallel" (meaning I have more projects that have unfinished code waiting for more attention), I find that even spending a few months away from some code and I realize I didn't leave myself enough signposts to spend 'no-time' getting back up to speed.

    The 2nd big point of this discussion is who decides what is "unnecessary" and what removal of "extra code" doesn't violate the premise that premature optimization is, at least, in the top 5 time-wasters category? I had a Dilbertian-boss, who only wanted bugs fixed that were reported by paying customers, and didn't want pre-release stress testing on multi-threaded kernel code ("Today's untested code can become tomorrow's paycheck."), but using short-term solutions for short-term OS-limitations was bad -- especially if documented. I.e. estimated time before limitation was removed: 2-3 years (was actually 18 months). Condition necessary to hit the "design-flaw": 25-30 years of continuous system *uptime* (no reboots or crashes). Admittedly this wasn't windows, but ...

  56. Explicitly destroying objects by cpghost · · Score: 1
    I'm working in Unix and Network programming and also Systems programming, and I made an early habit of explicitly destroying / releasing / closing resources that are not needed anymore, even when they are reclaimed by the OS when the program exits. This includes in particular open files, and all kinds of network descriptors. Why? Because most of my code usually ends up repackaged into libraries and reused inside longer running programs (i.e. inside loops); and not being disciplined about releasing resources would result in all kinds of leaks. This is particularly bad when that code gets reused inside device drivers.

    Of course, things got a lot easier once I switched from C to C++ and the STL and RAII idiom, but trying to release resources is still ingrained in my muscle memory; it takes a conscious effort in C++ NOT to explicitly release a resource acquired through initialization.

    --
    cpghost at Cordula's Web.
  57. Interesting faux video.. by MercTech · · Score: 1

    I say faux video as it shows two actors supposedly coding on identical macbooks.
    Tabs vs spaces.... gad, I remember an editor that came with a "C" package that would always change any tab character into five spaces unless you designated the tab character to be an ANSI code insertion which took as many keystrokes as doing five space characters.

    "Unnecessary Code" that is punctuation and comment for clarity is only "unnecessary" for scripts instead of programs. Programs are "compiled" which ignores comments and extra punctuation. So, the extra comments and punctuation only exists in the source code and is often beneficial for clarity. Try going back to an assembler program you wrote a decade before and try to remember what you did and why you did it that way. Or, worse yet, get assigned to update someone's code that retired a decade ago.

    Do they still teach the difference in a compiler, an interpreter, and a scripter? So much pop literature doesn't seem to know the difference in a program and a script.

    --
    NRRPT/RCT
  58. Wherever it helps understandability by tingentleman · · Score: 1

    Code relating to a complex situation or unique idea can often be more understandable (and self-documenting) if laid out in a certain, sometimes more verbose, way

  59. Re:Almost never by Blaskowicz · · Score: 1

    About accidental semi-colons, I was wondering about this one

    if (1 == YouShouldHaveDoneThisTheOtherWay);
    {
                    Whatever();
    }