News for hackers. Stuff that matters.
Re:How important is it to reduce the number of lines in code? by Paul_D_Santana on Sunday April 07, 2013 @12:40AM (#5506130)
The #1 most important factor in coding is:

Will I be able to read my code tomorrow or next week and know what in the heck I did?

Re:How important is it to reduce the number of lines in code? by timr on Sunday April 07, 2013 @02:27AM (#5506299)
Which really means: did I spend the time to write good comments?

People will go to endless lengths to make their code more terse and/or "self-documenting", but almost nobody takes the five extra minutes it takes to write an intelligent comment. The comments are far more important.

Re:How important is it to reduce the number of lines in code? by jamesaguilar on Sunday April 07, 2013 @03:07AM (#5506376)
I don't really agree. Which is to say, good comments are helpful, but they are a flashlight in a dark room. If there's lots of furniture and clutter in the room, you still might trip over something.

How many times in your codebase have you seen a comment like:

    // This exists because that dumb thing happened, 
    // and during the migration from Y to Z we had to 
    // support these two systems simultaneously. This
    // component mediates between the two . . .
And someone had added some common logic into the mediator, then someone else had hooked into that, and now there's a snarl.

The most important thing is that the system be as simple as it can while still performing its intended functions. We have all made a first cut at something that ended up being three times as verbose or complicated as our second. You want a system made out of pieces of the second kind. That's even more important than comments.

I can definitely understand the desire to reduce lines of code, because it's often a good proxy for understanding how complicated a system is. Not always, but most of the time, something a quarter as long that does the same job is doing it a simpler way.

Re:How important is it to reduce the number of lines in code? by timr on Sunday April 07, 2013 @05:41PM (#5508893)
That's an easy question: it almost never happens. The most frequent occurrence (by far) is that there are no comments at all, just a wall of indecipherable code. Even an old comment describing intent and usage is better than no comments at all.

In your example, even if that comment is outdated, it's still incredibly useful. It tells you, in under 5 seconds, the original intent of a piece of code, and how it was supposed to fit into the entire system. That's something you'll never get without a comprehensive understanding of the project, which takes far more than 5 seconds of reading. The real problem here is not that there is a comment -- the problem is that a bad coder fucked up by not updating the comment. There's no excuse.

That all of the commenters below will spend paragraphs explaining how they shouldn't have to document their code with the occasional descriptive comment is an amazing testament to the overwhelming power of human laziness and self-delusion.

Re:How important is it to reduce the number of lines in code? by jamesaguilar on Sunday April 07, 2013 @09:54PM (#5509591)
My point is not that this comment is unhelpful. My point is that it would be better if the reason for this comment's existence were eliminated. I.e. that the removal of unnecessary complication in the system is an even more laudable goal than commenting well.

Obviously, both will have a part in any well written an maintained system. But the person I'm responding to held good comments up as the most important aspect of system maintainability, and that is simply not the case.

Re:How important is it to reduce the number of lines in code? by timr on Friday April 12, 2013 @09:39PM (#5542178)
You were responding to me, and no, that's not what I meant. ;-)

I'm not saying that comments are the "most important" aspect of system maintainability, but that they're one of a few things that are all of top importance.

Obviously, if you write spaghetti code, your system won't be maintainable, no matter how many comments you write. But that's a false dichotomy: you need to write good code and you need to write good comments. Neglecting either one leads to unmaintainable systems.

Re:How important is it to reduce the number of lines in code? by JamesLeonis on Sunday April 07, 2013 @03:09AM (#5506382)
I try to avoid having to write implementation comments. If I find I need comments, then it's a warning that I may be too clever by half. I prefer a description of what the function is supposed to do rather than how it accomplishes it's goal.

Even so, there are some times when I need to write some mentally dense code to accomplish several competing goals. It is then where I explain what's going on and why the code was built that way.

Re:How important is it to reduce the number of lines in code? by randomdata on Sunday April 07, 2013 @02:55AM (#5506354)
I have to wonder what a good comment gives that a good set of tests wouldn't also provide, plus all of the extra benefits that come from having automated tests? It seems like they both exist to solve the same problem (to explain intent, show usage, etc.), with just one being more formal about it.
Re:How important is it to reduce the number of lines in code? by jfim on Sunday April 07, 2013 @03:56AM (#5506463)
Sometimes, code is hard to read due to being optimized. In that case, it's often easier to read a short comment than having to parse the code.

  // p.xyz += f.xyz * timeStep
  __m128 ts = _mm_load1_ps(&timeStep);
  __m128 x, y, z;
  __m128 fx, fy, fz;
  for(int i = 0; i < NUM_PARTICLES; i+=4) {
      x = _mm_load_ps(px + i);
      y = _mm_load_ps(py + i);
      z = _mm_load_ps(pz + i);
      fx = _mm_load_ps(pfx + i);
      fy = _mm_load_ps(pfy + i);
      fz = _mm_load_ps(pfz + i);
      x = _mm_add_ps(_mm_mul_ps(fx, ts), x);
      y = _mm_add_ps(_mm_mul_ps(fy, ts), y);
      z = _mm_add_ps(_mm_mul_ps(fz, ts), z);
      _mm_store_ps(px + i, x);
      _mm_store_ps(py + i, y);
      _mm_store_ps(pz + i, z);
  }
Sometimes, it's because you're doing something that looks surprising, but is there for some reason, so that the next time someone looks at that code, they know why something is done in that fashion.

  val loginForm = Form(
    tuple(
      "email" -> text,
      "password" -> text,
      "rememberMe" -> optional(text)  // jfim: HACK For some reason, having this as boolean causes a None.get in Play 2.1.0
    )
  )
Comments should be there to explain why the code does something or what it does in a more readable fashion(because it's faster to read plain English than code), neither of which can be covered by tests.
Re:How important is it to reduce the number of lines in code? by randomdata on Sunday April 07, 2013 @10:52AM (#5507382)
I actually agree with you completely, but such cases should be rare, and doesn't seem to be what the parent was talking about.
Re:How important is it to reduce the number of lines in code? by tonyedgecombe on Sunday April 07, 2013 @02:57AM (#5506362)
That's fine if you have a team disciplined enough to write useful comments and keep them up to date. Personally I haven't seen that very often.
Re:How important is it to reduce the number of lines in code? by saraid216 on Sunday April 07, 2013 @04:37AM (#5506538)
Just to add to siblings, I'd propose a rule of thumb of at most 2 sentences per "page" of code, where a page is about as much code is on your screen at a readable size.

It's a rule of thumb, and snark will put you over that easily, but IME, it can suggest you're getting overzealous about commenting when you've got more than that.

Re:How important is it to reduce the number of lines in code? by dchichkov on Sunday April 07, 2013 @12:11AM (#5506083)
Every line of code is a constraint working against you.
Re:How important is it to reduce the number of lines in code? by baddox on Sunday April 07, 2013 @12:36AM (#5506125)
.split("/n").join(";")
Re:How important is it to reduce the number of lines in code? by dchichkov on Sunday April 07, 2013 @01:16AM (#5506191)
There is a little bit of ASCII art in any well written code. And yours would ruin it ;)
Re:How important is it to reduce the number of lines in code? by gruseom on Sunday April 07, 2013 @01:56AM (#5506246)
That's a subtle comment and a much deeper one than it might appear to be.
Re:How important is it to reduce the number of lines in code? by Someone on Sunday April 07, 2013 @04:17AM (#5506498)
There are few, if any, languages where that would be guaranteed to work. For example:

in C

  #include <studio.h>#include <stdlib.h>
won't work. In perl, strings with literal new lines or here docs will break (terminator must be on a line by itself)

Any language with 'comment till end of line' would break.

Any language that does not use semicolons as statement terminator or separator such as Forth, Postscript, and XML-based languages wouldn't like the inserted semicolons.

Even pascal would break, as it has a few places where repeated semicolons are illegal, as in the third line of

    type
      T = record
        a : integer;
      end;
Algol has a problem changing

    if x=4 then y:=5
    else y:=6;
into

    if x=4 then y:=5;else y:=6;
Because a semicolon is a statement separator in Algol (I think pascal has this problem, too)

So, can anybody suggest a language where this would work?

Re:How important is it to reduce the number of lines in code? by baddox on Sunday April 07, 2013 @03:29PM (#5508328)
I don't really know. I had Ruby in mind, and it seems to mostly work there, but still obviously breaks for things like heredoc multiline strings. Of course, the point is that making generalizations about the line count of a program is silly, because the line count can vary wildly between two semantically identical programs.
Re:How important is it to reduce the number of lines in code? by hayksaakian on Sunday April 07, 2013 @01:01AM (#5506157)
sorry for being pedantic, but should'nt it be "\n" ?
Re:How important is it to reduce the number of lines in code? by 1337Coder on Sunday April 07, 2013 @03:47AM (#5506443)
sorry for being pedantic, but should'nt it be shouldn't?
Re:How important is it to reduce the number of lines in code? by baddox on Sunday April 07, 2013 @01:08AM (#5506169)
I just used the first slash I could find on the iPhone keyboard. You're right.
Re:How important is it to reduce the number of lines in code? by k3n on Sunday April 07, 2013 @02:02PM (#5507998)
I'm in agreement in that I believe, with all else being equal, every LoC increases your chances of initial bugs (and/or security vulnerabilities) and refactoring errors. It will also make the code take longer to mentally parse and interpret, not to mention that it means you will see less code on the screen at one time. None of these points are universal truths or anything, rather, given 2 solutions that identical in everything except line-count, choose the shorter.

* BIG NOTE * This excludes code which is artificially short due to 'clever' coding.

Re:How important is it to reduce the number of lines in code? by dvt on Saturday April 06, 2013 @11:14PM (#5505950)
Things are complicated, but it's a well-known fact that lines-of-code is literally the worst metric of source-code health. Lines-of-code have been previously used as a productivity metric and as an efficiency metric, but in the past several decades, LOC has been debunked as virtually worthless in both cases.

In other words, if you're thinking "that guy must be productive, he wrote twice as many lines as this other guy" or "this code must be slower since it's 3 times longer than that code" you're most likely wrong in both cases. Or, in the best case, very naive.

And what's up with Ars Technica just copy-pasting SO (or prog.SE) answers into an article?

Re:How important is it to reduce the number of lines in code? by k3n on Sunday April 07, 2013 @02:24PM (#5508070)
It has everything to do with context, and the ultimate goal should be clarity for the reader. But, I also don't think you should ever compromise any non-trivial design for the worse to 'make it more readable'. Sometimes clever code can't be easily avoided, whether it's due to language limitations or the general design pattern itself, so proceed with caution and use lots of comments in those cases. A quick example here would be a factory method: since you're often referring to abstracted resources, you can't really make a non-clever factory without entirely defeating the purpose of the factory.

Another example would be from PHP, where you can many times do tasks in several different ways, and so you may have this code (straight from the manual) for reading the contents of a file:

    $filename = "/usr/local/something.txt";
    $handle = fopen($filename, "r");
    $contents = fread($handle, filesize($filename));
    fclose($handle);
And this isn't even very descriptive, unless you have a background in other languages such as C to grok that filesize($filename) might mean "read to the end of the file".

OTOH, this code does the exact same thing and is extremely explicit about what it's doing:

    $contents = file_get_contents("/usr/local/something.txt");
Re:How important is it to reduce the number of lines in code? by just2n on Sunday April 07, 2013 @04:02AM (#5506471)
Reducing the number of lines isn't important. Unless you're code golfing or otherwise competing to fit within a certain code/binary size, you should never care about line count at all.

The only thing it will do is cause you to crush your lines wherever possible and code horizontally instead of vertically, which generally conflicts with readability. In fact, I'd actually impose a limit on line length to prevent just that.

Instead, write code that makes sense when you read it. Avoid cleverness, and DRY. Repeating yourself in the way that violates DRY principles can often make reading code more difficult because you're essentially forced to re-read repetitive code because you can't assume it's all identical.

The only exception to this is code standards for consistency in the code base that make sense, such as use a '{' on the same line as the definition or omit the '{}' block if the body is just 1 statement in cases where you won't violate a width constraint, etc. Anything that isn't completely reasonable as a code standard is optimizing for line count and is probably the wrong thing to do.

Re:How important is it to reduce the number of lines in code? by just2n on Sunday April 07, 2013 @04:05PM (#5508512)
Downvotes on this?

Be thankful downvotes are anonymous. You are very likely incredibly incompetent, and I fear for anyone who has to read your code or worse, use it.

Re:How important is it to reduce the number of lines in code? by jfaucett on Saturday April 06, 2013 @11:04PM (#5505931)
personally, i think that when you're programming, not just pondering how to make your code simpler and shorter but also concentrating on patterns that repeat and packing them into a catchall solution can do a lot towards making code more readable and maintainable. I suppose this is what is usually meant by DRY, but I unfortunately still see an aweful lot of code that doesnt follow this principle. And i think it has to do with the fact that many (myself included) programmers think about solving the problem at hand and we sometimes allow our thoughts about abstracting what we're doing into overarching reusuable procedures to slip into the background.

for instance, say you notice you've got multiple for loops iterating over matrixes of pixel data and running transformation functions on member elements. The first level would be to abstract this into an each function taking the array and the function to call, the next step would be to pack the each into an even more general function, and now all those lines have been compacted into a single call pixel_data.update_array_matrix.

Re:How important is it to reduce the number of lines in code? by Manishearth on Sunday April 07, 2013 @12:15AM (#5506090)
Depends. Does it make it cleaner, faster, and more readable? Go for it. Does it just use syntactic sugar to cram stuff into one line? Don't do it.
Re:How important is it to reduce the number of lines in code? by deliminator on Sunday April 07, 2013 @01:52AM (#5506238)
Following quote comes to mind (Dijkstra) "...we have to keep it crisp, disentangled, and simple if we refuse to be crushed by the complexities of our own making..."

I found his use of the word "crisp" very interesting. I believe it means to keep your code short and to the point, without any extra embellishment.

Re:How important is it to reduce the number of lines in code? by mark_l_watson on Sunday April 07, 2013 @11:22AM (#5507476)
I have actually been programming since I was a kid (I got access to computers around 1962). I used to write huge blocks of comments, and even simpler programs had a high LOC count.

I work differently now. I mostly work in Clojure and I write very few comments but I like long and descriptive function and variable names. I think that a concise language like Clojure or Ruby, combined with very good semantic naming works much better for me. I can look at year old code, and fall right into it.

Re:How important is it to reduce the number of lines in code? by RougeFemme on Saturday April 06, 2013 @11:25PM (#5505978)
LOC is also used as a "maintainability" metric. Don't know how useful it is. I assume it would need to be massaged with some other metrics - or at least placed in proper context, whatever that means in your environment. Also, if your code verges on throw-away, maintainability would not be a consideration.
Re:How important is it to reduce the number of lines in code? by codygman on Sunday April 07, 2013 @06:22AM (#5506713)
The only metric you should work on reducing in your program is complexity.

Of course, some complexity/warts will be needed.

Re:How important is it to reduce the number of lines in code? by niggler on Sunday April 07, 2013 @01:03AM (#5506160)
What exactly did Ars Technica contribute to this discussion? It looks like a copy-paste job.