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?

16 of 239 comments (clear)

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

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

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

      if (auto x = SomeTest ())
      {
      }

      How about

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

  2. 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: Happy Saturday from The Golden Girls! by Anonymous Coward · · Score: 0, Insightful

    Why the fuck was my post modded down? It's better than most of the other posts on this story. I really hate moderators.

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

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

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

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

  8. Re: Happy Saturday from The Golden Girls! by Anonymous Coward · · Score: 3, Insightful

    Maybe because you are a douche?