Slashdot Mirror


Code Reading: The Open Source Perspective

nazarijo writes "You can usually tell someone who's been writing a lot of code by how they write code. That may sound like a tautology, but it's got a deeper meaning than that. What editor they use, what idioms they use to avoid common pitfalls, and what organization patterns they employ all tell you what kind of programmer you're meeting. When you first start writing code, so many things are inconsistent and just plain wrong that it's almost embarrassing. I know that when I look over older code that I've written I feel sheepish about it. But how do you grow as a programmer, and what really makes a good programmer beyond language familiarity?" Read on for Nazario's review of Code Reading: The Open Source Perspective, a book which attempts to instill deeper knowledge about programming than just "knowing how." Code Reading: The Open Source Perspective author Diomidis Spinellis pages 499 publisher Addison-Weslet Longman rating 7 reviewer Jose Nazario ISBN 0201799405 summary A tour of large-scale development projects from code to organization

A few books are tackling this subject, including Coder to Developer and Programming Language Pragmatics. These books don't teach you much about a particular language in the way that an introductory text would. Instead, you grow as a skilled developer by studying them and learning from them. That's one of the key things that people are talking about lately, that to be a strong developer requires more than a working knowledge of a language. It requires a familiarity with the strengths, weaknesses, and core features of a language and the base libraries to be efficient.

Code Reading: The Open Source Perspective is one of these books in this small but growing library. In it, Diomidis Spinellis takes you through a large body of code and focuses on several languages, techniques, and facets of development that differentiate strong developers from weak ones. What I like about this book is how much it covers, how practical the information is, and how much Spinellis teaches you. You wont learn a language, which is the complaint of some people who read this book, but if you know one or two you'll be a better programmer.

Perhaps one of the most telling things about the book is that it draws heavily from NetBSD source code, and features over 600 examples to make the point. Examples are often annotated using NetBSD as a reference. This makes sense, because NetBSD is a large project that's relatively stable and mature. Everything from how to define a C structure consistently and sanely to UML diagrams and build systems are covered, making this truly a developer's book. However, even Windows and Mac OS X developers will benefit, despite the BSD focus.

Chapter 1 introduces some of the basic tenets of the book, namely that code is literature and should be read as such. All too often people only read code when they have a specific problem to solve or want to get an example of an API. Instead, if you read code frequently you'll always be learning things and improving your skills. Also, Spinellis discusses the lifecycle of code (including its genesis, maintenance, and reuse), which simply must be taken into account if code is to be good. Poorly skilled developers forget these things and just slap it together, never thinking ahead.

In Chapter 2, a number of concepts basic to any programming language are covered, including the basic flow-control units common to many languages. The book focuses on C, with additional coverage given using C++, Java, and a few other things thrown in for good measure. As such, these chapters -- in fact the whole book -- focuses on concepts common to these languages but absent in some other languages, like Scheme or LISP. One neat section is called "refactoring in the small." It illustrates the real value of the book nicely, in showing you various ways to organize your code and your thoughts for various effects. Oftentimes a book will only teach you one way (which doesn't always suit your needs), and Spinellis' examples do a nice job of escaping that trap, not just here but throughout the book.

Chapter 3, "Advanced C Data Types," focuses on some language-specific matters. These are pointers, structures, unions and dynamic memory allocation, things that most people who code in C may use but only some truly understand well. Again, a somewhat basic chapter, but useful nonetheless. Make sure you read it; chances are you'll learn a thing or two.

In Chapter 4, some basic data structures (vectors, matrices, stacks, queues, maps and hash tables, sets, lists, trees and graphs) are covered. This is an important chapter since it helps you see these structure in real-world use and also helps you understand when to chose one structure over another. While Knuth, CLRS, or other algorithms and data structures texts cover these, they often do so in isolation and at a theoretical level. While their coverage is short, it's to the point and usable by anyone with a modest understanding of C.

Chapter 5, "Advanced Control Flow," the last chapter that deals with actual programming information, is another useful one. Again, short but to the point, this chapter covers things like recursion, exceptions, parallelism, and signals, all topics that have warranted their own books (or major sections in other books) but which are covered in a single chapter here. Still, seeing them side-by-side and in the context of each other and in real-world use provides some justification for the compact presentation.

The remaining chapters of the book go well beyond a normal programming book and focus on projects. These chapters complement the first bunch nicely by focusing on the organization of your code and projects. Chapter 6 deals specifically with many of the commonly identified (but rarely taught) things like design techniques, project organization, build processes, revision control, and testing. A number of things that aren't covered include defining and managing requirements for a release and their specifications, basics on how to use autoconf and automake, and instead rips through a whole slew of topics quite quickly.

Chapter 7 is sure to be controversial for some people: it covers "Coding Standards and Conventions." Some people seem to be big fans of the "if it feels good, do it" style of programming, and instead of writing sane, usable code, what they produce is buggy and messy. This chapter teaches you tried and tested methods of naming files, indentation (and how to do so consistently using your editor to help), formatting, naming conventions (for variables, functions, and classes), as well as standards and processes. The style and standards are (as you would expect) based on NetBSD, which differ slightly from GNU and Linux standards, as well as commonly found Windows practices. However, I think you'll agree that the style is readable with minimal effort, and that goal, coupled to consistency, is paramount in any standard.

Chapter 8 introduces you to documentation, including the use of man pages, Doxygen, revision histories, and the like. Also included are hints at using diagrams for added value. One thing I don't like about this chapter is the opening quote, which sets a bad precedent. It blithely suggests that bad documentation is better than none, which is highly questionable. Misleading docs can be worse than no docs at all, since someone without docs will have to dig through the code in front of them to understand it. Someone with bad docs will rely on the docs and wonder what's broken when things go awry.

Chapter 9 focuses on code architecture, such as class hierarchies, module organization, and even core features like frameworks to chose. This chapter covers a lot of material, and is, despite its size, simply too terse on many of these subjects. It serves as a decent introduction, but doesn't go very far in some places, considering the importance of the material. However, like much of the book, it's a good introduction to the topics at hand.

Chapter 10 also features a lot of good things to know. Granted, you could pick them all up with a lot of hard work and scouring for information, but it's easier to have them presented to you in a cohesive format. The chapter discusses code reading tools, things that you use to help you dig around a large body of code. One you get over a few source files, even if you have well-organized code and interfaces, many changes can require that you inspect the data path. You can do this manually, or you can be assisted with tools. Tools like regular expressions, grep, your editor -- Spinellis shows you how to make use of all of them when you write code. A lot of tools I've never used (but have heard about) are featured, and their use is demonstrated, but of course many tools are simply ignored, focusing on popular ones that will work for most people.

Finally, all of the above is brought together in Chapter 11, "A Complete Example." A small tour of a large, complex piece of code is taken (34,000 lines of Java) as the author makes changes. It's unfortunately in Java, when so much of the book focused on C (why couldn't they have been consistent examples?), but it works. The example itself could have covered a few more things, such as a proper JUnit example, but overall I'm pleased with it.

Overall, Code Reading: The Open Source Perspective is ambitious and worthwhile, both as a complement to a bookshelf of study that includes The Practice of Programming and Design Patterns, and to someone who is growing tired of books on learning a language. At times it feels like the author promised more than he wound up delivering, but it serves as an introduction to a large number of topics. You wont learn a language, and you wont be able to get as much out of the book if you don't engage it with practice, but it's a useful book to get started on the road from being someone who knows a language or two to someone who is a developer, ready to contribute to a team and work on large projects. Never underestimate the skills required to be a good developer, because they go well beyond knowing how to use a language.

You can purchase Code Reading: The Open Source Perspective from bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

464 comments

  1. Consistency and good comments by Neil+Blender · · Score: 4, Insightful

    When I see that develop in someone, then I know they are going to the next level. When I don't see it after time, I know they will never evolve.

    1. Re:Consistency and good comments by Arimatheus · · Score: 5, Interesting

      Pseudocode.

      The other day I was looking at some code a peer of mine wrote and noticed a few places where there were comments with no code associated with them, he (like me and I'm sure a few others) builds the frame of his project and then fills in the code. I think it really helps to think the project through before hand, build your comments and then write.

      And oddly, you'll notice that a lot of the coders who do this know a large multitude of languages and probably developed this habit over the course of doing personal projects, it helps you quantifiably say how far along you are in the project, remember what direction you were taking with the project (because of course we NEVER let there go a ~3 week gap in personal projects :-P ) and allows you to look at the fundabmentals of a project without forcing yourself into a language before you can address where your language of choice might fail.

      At least that's the way I see it.

      --
      OEÉæÁÄZÝÈA OEÉæé_CX
    2. Re:Consistency and good comments by Lunix+Torvalds · · Score: 1

      I would like to see more comments in the new code coming in from the contributors. Watch out for an announcement concerning this on the mailing lists.

      --
      Farmix
    3. Re:Consistency and good comments by Anonymous Coward · · Score: 0

      dewd WTF?!?! Linus, is that realy you?!?

    4. Re:Consistency and good comments by Anonymous Coward · · Score: 0

      Yes, it really is me.

      -- Lunix

    5. Re:Consistency and good comments by shufler · · Score: 4, Insightful

      builds the frame of his project and then fills in the code. I think it really helps to think the project through before hand, build your comments and then write.

      And oddly, you'll notice that a lot of the coders who do this know a large multitude of languages

      This isn't odd at all. I do it myself. And I know why I do it too -- the language you use is inconsequential. If you "write" a script, you can probably use a host of languages to do the task. The key is knowing what you want to do.

      Over the years I've sat and listened to many "debates" (arguments, really) about which language was better than another. I've always sat back and thought, "Who cares?" Once you can reach a point where you can visualise the solution (this includes pseudocoding it out, or at least listing what the program has to do at this point), selecting a language is irrelevant, other than considering what languages are available to you.

      I'm not saying different languages don't have their strengths and weaknesses, and I'm espcially not saying they are all the same. What I am saying is that once you "write" what the program needs to do, use a programming language is as easy as literally looking up syntax and function names in a book.

      This is also how proper language translators operate. They don't know entire languages, but they instead form exactly what they need to say before translating. New languages become second nature after repeated use, it's always just a matter of knowing what you want before hand.

    6. Re:Consistency and good comments by fireman+sam · · Score: 2, Insightful

      Personally, I prefer to have my code self commented. Meaningful variable names, no "smart arse" tricks, good clear layout.

      If you have to explain what a function is to do, it has not been coded very well.

      --
      it is only after a long journey that you know the strength of the horse.
    7. Re:Consistency and good comments by msgregory@earthlink. · · Score: 3, Interesting

      I go the opposite route. I write the code and then a week later go in and write the comments. Doing it this way gives you time to get some perspective on the code, so when you go back to do the comments, you can get a sense of what's clear about the code and what isn't. So it not only helps you write more pertinent comments, it also forces you to think through the code again with a little emotional distance from it, which helps in finding flaws. Actually, it's best to read code and rewrite comments on a continual basis. You can find a lot of bugs by doing this.

    8. Re:Consistency and good comments by dtrent · · Score: 5, Insightful

      Personally, I prefer to have my code self commented. Meaningful variable names, no "smart arse" tricks, good clear layout. If you have to explain what a function is to do, it has not been coded very well.

      Yeah but your function doesn't live in a vacuum does it? How about you write some lines up there at the top to put it in context for when I have to fix it next year.

      Your Cubemate.

    9. Re:Consistency and good comments by pfrench42 · · Score: 0, Redundant

      Agreed. Also, you can learn a lot from java. I don't write in java anymore, but learning the language greatly improved my C code (which is 95% of what I write) I avoid typedefs, nothing is more aggravating than figuring out if somebody else's typedef is a struct, a struct *, or a native type. The benefit of java is, there is only one way to write everything. Thus, you can read anyone's code because they haven't wandered into their own "dialect" of the language. C++ is horribly abused in this way, where people tend to write their own language, simple aritmetic operations can expand into gazillions of execution cycles (image = file * matrix)

    10. Re:Consistency and good comments by Bill+Dog · · Score: 0, Redundant
      Pseudocode is fine, but it's not critical to your point. You can do all that you describe in an actual language, as at this level you'll not be using any language-specific features anyway (otherwise by definition you couldn't use pseudocode either!).

      For example, I work with many languages but am most fluent in C++, as are my coworkers, so for an object-oriented design, for example, I'll just go ahead and write up some mostly-empty class declarations, with comments inside for guts that aren't appropriate to spell out at this level, as it's as good a language as any in this case. No need to make up a pseudo one.

      --
      Attention zealots and haters: 00100 00100
    11. Re:Consistency and good comments by Anonymous Coward · · Score: 0

      Well put. I'm constantly cursing the name of people who came before me and assumed that whatever project they were doing would be a one-off. There's nothing really wrong with their code...it's quite readable, variable names make sense, and no fancy tricks. However, you could save me about 2 weeks of spinning-head-syndrome if you just added a few lines at the beginning of each function putting it in context.

      Sure, you know your code well...doesn't mean that I do too.

    12. Re:Consistency and good comments by Bill+Dog · · Score: 3, Insightful
      You sound as if you work in the sysadmin side of the house. This is probably totally appropriate for your tasks, where you may typically need modest-sized scripts to piece together some things to, say, process a log file.

      But note that there's a whole other world out there, and be careful not to fall into the PHBism of assuming that anything you don't know about must be simple. On the software engineering side, for large-scale projects, the choice of languages is not at all inconsequential, and can affect maintainability, quality, and performance. We're not handed a pseudocode design that spells everything out, and we only have to translate it into the actual language syntax. A requirement may say such-and-such shall appear alphabetically. You know what the program "needs to do", but there are choices of sorting algorithms, and data structures/containers, that have different qualities, that should be evaluated and chosen deliberately for the task at hand.

      --
      Attention zealots and haters: 00100 00100
    13. Re:Consistency and good comments by Anonymous Coward · · Score: 0

      Comments???

      Geez I hope my employer doesn't see this and have to start putting comments in.
      Since I am the only one maintaining it, I am 'indispensable' :D

    14. Re:Consistency and good comments by Anonymous Coward · · Score: 0

      I always gnu Lunis was a lune.

    15. Re:Consistency and good comments by Chemisor · · Score: 1

      > builds the frame of his project and then fills in the code.

      Yup, I do it all the time. But then I go through and delete all the comments, because when I'm finished, the final code explains what's going on much more eloquently than any comment I could write about it. If it doesn't, then I'm not finished, and the comments stay, all bearing Doxygen tags like \todo or \bug to allow me to find them later.

    16. Re:Consistency and good comments by Bill+Dog · · Score: 0

      Nice troll/automatic assuming of a borken function, but most people use IDE's these days, and they're perfectly capable of pointing out where a function is called, among other things. And in OOP, typically functions reside in classes or interfaces, that by their names provide additional context above and beyond what you can already readily discern from the name of the function and its parameters and which are in or out parms. What other context do you somehow require?

      --
      Attention zealots and haters: 00100 00100
    17. Re:Consistency and good comments by Anonymous Coward · · Score: 0

      A problem with Slashdot is that there are way too many reactionary children on here spouting simplistic and absurd things. Encountering a poorly-name typedef does not make typedefs evil. Functions can be poorly-named too, should they be banned as well? And if you find a feature of a language horribly abused, the language has to go? Some people abuse the privacy of their homes by running meth labs in them, so homes should be banned? You're either an ignorant college kid, or a middle-aged Liberal. If the former, come back when you've grown up (if the latter, you never will). And you should stick to Java, as you seem to need a more totalitarian environment.

    18. Re:Consistency and good comments by AhBeeDoi · · Score: 3, Funny

      I always seem to end up with your code before the week is up.

    19. Re:Consistency and good comments by Kwil · · Score: 0, Redundant

      The key to commenting isn't explaining what your code is doing.

      It's explaining why your code is doing it.

      --

      That Jesus Christ guy is getting some terrible lag... it took him 3 days to respawn! -NJ CoolBreeze

    20. Re:Consistency and good comments by drsmithy · · Score: 4, Insightful
      Yup, I do it all the time. But then I go through and delete all the comments, because when I'm finished, the final code explains what's going on much more eloquently than any comment I could write about it.

      But does it explain *why* ?

    21. Re:Consistency and good comments by msgregory@earthlink. · · Score: 1

      Don't go and start rushing me now. It'll be done when I get it done.

    22. Re:Consistency and good comments by supersnail · · Score: 1


      I go to the other extreme. If I find the code unclear or obscure I rewrite the code until it reads better.

      Comments are for wimps.

      --
      Old COBOL programmers never die. They just code in C.
    23. Re:Consistency and good comments by Anonymous Coward · · Score: 0

      Once you can reach a point where you can visualise the solution ... selecting a language is irrelevant, other than considering what languages are available to you.

      Spoken like a true monoglot.

      Languages vary wildly in the approaches they support towards implementing any given problem. Once you can reach a point where you can visualise the solution you need to then reach a point where you can decide which language is the best for implementation. Otherwise you're just coding hand-to-mouth. For instance, you can produce code an order of magnitude faster for certain tasks if you use a language like LISP. For other tasks, C++ is an obvious choice.

      Of course all languages are broadly equivalent, but it's the details that matter and that affect your productivity by a factor of 10. I agree that language arguments are often a waste of time for various reasons, but to say "who cares?" is missing the point completely.

    24. Re:Consistency and good comments by EkkiEkkiShiwaddle · · Score: 1
      Since I am the only one maintaining it, I am 'indispensable' :D

      Just to show you how 'indispensable' you really are, here is a nice little anecdote for you.

      A coworker of mine was once hired to do some work for a company which I will not name here. His job was to get to know an already existing project and comment on it.

      The guy originally working on the project had already spent 5 years working on it, and had never ever written even a single line of comments in his code. When his project leader asked him why he did not comment his code (after he had been absent and someone else had to take over his code for a few weeks), he answered 'to make me indispensable'.

      He explained to the project leader that he would still be needed for as long as the project was kept running, and he refused to comment his code, even after several chiefs several steps up the hierarchy had asked him to do so.

      And that's where my friend came in - he had to catch up the original programmer without him knowing. It cost him more than a year, but after that year the original programmer was fired.

      The only reason they fired him was to show him that NOBODY is indispensable.

    25. Re:Consistency and good comments by smittyoneeach · · Score: 1


      Dude: the deadline!
      Are you here to ship code, or are you living in some rose-colored academic glass house?
      </tongue in cheek>

      --
      Get thee glass eyes, and, like a scurvy politician, seem to see things thou dost not.--King Lear
    26. Re:Consistency and good comments by SillyNickName4me · · Score: 1

      Heh, recently I was talkign to a rather big tech company wanting to hire me to do JAVA work for them..

      The thing is, I have not written any serious JAVA code since the days of JDK 1.1, but I did write quite a few things in other languages since. I use a similar method of writing down what I want to do in comments, slowly ending up basicly describing the actual program's functinality there, and then fill in the code.

      Language does matter, one language is more suited to a task then another, but it should not matter at all for the process that gets you from a design (or even just an idea) to working code.

      (Oh, and I didn't accept the job, there is a reason why I didn't do JAVA since the 1.1 days, tho with the JDK5 this may change, at least you can avoid )

    27. Re:Consistency and good comments by Chemisor · · Score: 1

      > But does it explain *why* ?

      I don't explain "why" in the code itself unless it is really something unexpected, like a weird piece of code reloading a variable that might get suddenly changed by a signal handler. All the normal "why" explanations go to the class documentation, which gives details on how the class works. For nearly everything I've written, that has been sufficient and has kept me from creating hacky implementations of obvious code.

    28. Re:Consistency and good comments by p3d0 · · Score: 1

      For the millionth time... Code, no matter how clearly written, can only tell you what it does. Comments tell you why.

      --
      Patrick Doyle
      I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
    29. Re:Consistency and good comments by Anonymous Coward · · Score: 0

      HAHAHAHAHHA. The Seinfeld-ish sarcasm comes dripping through my monitor.

      You're other cubemate.

    30. Re:Consistency and good comments by Anonymous Coward · · Score: 0

      No I'm not.

    31. Re:Consistency and good comments by CoderBob · · Score: 2, Interesting

      Not everything is coded in OOP. And what about when I'm using your code as a library? Maybe it wasn't intended to be a library, and there is something concerning system state between function calls, or little things like is it a blocking function or not, etc. that I might need to know, now that The Pointy Haired Boss wants me to use it in my code.

      A few lines at the top of each function/procedure/class at least tell the other guy what the known effects of the function are would be nice. I don't want to have to look into your specific code unless something goes wrong. I want to be able to call foo() with baz and bar as parameters, and know that if baz happens to be of the format "xxx.xxx.xxx.xxx" instead of as a long int, it will be translated to a long int for the socket library (This is especially useful in such languages as Python, PHP, etc, that are not strongly typed). And I'd rather not have to take the time to dig through your code to make sure you're doing it.

      I'm not saying comment the process, I'm saying comment the functionality. Preconditions, postconditions, undefined behavior, etc. The best part is, there are tools out there that can rip those out to generate paper docs later, if you want to have a nifty reference. "Oh! You need a function that gives pigs wings? I have one of those- its in file whenPigsFly.py. Here's the doc for the function, its got all you need to know."

    32. Re:Consistency and good comments by b3h · · Score: 1

      I thought good code was never finished. ;)

    33. Re:Consistency and good comments by Anonymous Coward · · Score: 0

      No kidding. Only somebody who doesn't code for a living thinks that code can document itself. "Self-documenting" code can help keep your inline comments short and concise but it can't replace the good old What is it for, why is it there, what are the parameters, who wrote it and when and why was it changed comment at the top.

  2. I don't understand by AntiPasto · · Score: 1, Funny

    ... you're saying that there's more to it than just getting it done?

    1. Re:I don't understand by cperciva · · Score: 3, Insightful

      ... you're saying that there's more to it than just getting it done?

      Yes. Getting it done right.

    2. Re:I don't understand by nacturation · · Score: 2, Funny

      Ah, grasshopper... your code may get things done, but will someone in Soviet Russia who has to parse through your unreadable code get done by it?

      --
      Want to improve your Karma? Instead of "Post Anonymously", try the "Post Humously" option.
    3. Re:I don't understand by Anonymous Coward · · Score: 0
      I tend to jump in there with only a few commands that I know how to use, and see if I can cobble together a script that does what I want.

      No, it is not professional, by any means, but I work for myself, not anyone else, so I tend to want to accomplish something, and try and use a script or a series of them to get things done. If it works, I use it.

      The coding is not so much the issue, as the overall design of the project.

      I'm sure a professionally trained coder could redo a lot of my stuff, and have marvelous results.

      I maintain this Knoppix remaster, and one of the things I have in there is a way to switch mouse cursor themes, there are 4 of them in all, with one having three variants.

      I got a lot of negative feedback from beta testers in the beginning about the default Knoppix 3.4 mouse cursor, being too small, especially for laptops. I fixed that, and now can focus on other problems. (There are always other problems...)

    4. Re:I don't understand by Thud457 · · Score: 0, Troll

      Actually, it's usually the other case. Management outsources the development of new modules to vodka-addled Russkis, and honest, tax-paying Americans get the thankless job of hacking through 3,364,283 lines of multi-layered macros in 192 modules to learn that it prints "! ".

      --

      the preceding comment is my own and in no way reflects the opinion of the Joint Chiefs of Staff

    5. Re:I don't understand by Anonymous Coward · · Score: 0

      Stupid fucking slashdot ate my mad 'leet Russian. Bitches.

    6. Re:I don't understand by BattleCat · · Score: 0

      No. Your leet Russian was outsourced to Russia :-) And was buried somewhere in the countless layers of vodka labels and /insert your typical Russia stereotype here/

    7. Re:I don't understand by TheSpoom · · Score: 2, Interesting

      Damn right. My new job involves making modifications to a Russian-developed PHP shopping cart, and while it's decently programmed in some places, others are *hellish* to try to work through and/or edit. /me keeps telling himself that it's all for the experience... ;^)

      --
      It's better to vote for what you want and not get it than to vote for what you don't want and get it.
      - E. Debs
    8. Re:I don't understand by bewebste · · Score: 1

      In Soviet Russia, the code comments you!! (sorry, couldn't resist)

  3. Very true. by gimpynerd · · Score: 3, Insightful

    This is very true. While learning a certain language I always have many inconsistanies in my code. In fact I always want to go back and change it as I progress. It just shows that experince is much more than talent.

    1. Re:Very true. by superpulpsicle · · Score: 5, Insightful

      Personally I hate wasting time writing a function to do something only to find out 10 days later... the language already comes with a library that does the exact same thing. Experience do count there.

    2. Re:Very true. by jacksonj04 · · Score: 1

      In this case your friend is the manual. I've found that a quick flick through a decent manual (PHP has a very nice Windows help file, sorry *nix people) solves most things, especially if you have a feeling the language should do it built in.

      --
      How many people can read hex if only you and dead people can read hex?
    3. Re:Very true. by MidnightLog · · Score: 1

      Just as bad is using some built-in function that works perfectly (in the current langauge version) on my PC, but that doesn't work (in the previous version) on the server. D'ohh! I guess that "Since" section in the method detail is there for a reason.

      --

      To understand what's right and wrong, the lawyers work in shifts ...

    4. Re:Very true. by downbad · · Score: 1

      There are chm readers for UNIX.

  4. comments by PoopJuggler · · Score: 5, Insightful

    You can tell a great deal about the maturity of a programmer by the quantity, and quality, of comments.

    1. Re:comments by Rosco+P.+Coltrane · · Score: 5, Funny

      Funny, my colleague posted many good comments here while on the job and he finally got sacked...

      --
      "A door is what a dog is perpetually on the wrong side of" - Ogden Nash
    2. Re:comments by Suicyco · · Score: 4, Insightful

      This is absolutely true. The more you have worked on past software, horrible code, etc. the more you value proper commenting and documentation. Hence, the higher quality you produce, with full knowledge that it WILL be useful someday. Many times I spend just as much time carefully crafting comments and documentation, formatting the code, etc. so it reads as cleanly as possible.

      I suppose it also holds that once you have surpassed the threshold of super-duper quality commenting, you get to the point of such awesome code that it documents itself, so you come full circle.

    3. Re:Comments by dakara · · Score: 1

      Let me guess... you're part of the "big commenter" crowd? :-)

    4. Re:comments by Mumpsman · · Score: 3, Insightful

      Actually, what you can tell about a programmer from comments is the ability and understanding of his/her direct supervisor.
      Understanding the value of good code is one thing, but insulating your developers from top-down pressure and unreasonable deadlines which force them to "slap it together" allows programmers to prosper.
      If your shop is producing crap code it's because your management is crap.

      --
      No battles to the death are recalled. Mumpsman can hit to attack and cause brainsmashing.
    5. Re:comments by nkh · · Score: 2, Interesting

      with full knowledge that it WILL be useful someday.

      That's why you need Literate Programming! A very good book for all the family ;)

    6. Re:Comments by Feneric · · Score: 1

      Yes, when I first started coding I used a lot more comments than I do now. In time one realizes that comments can get out of date, too, and need to be maintained as much as the code...

      Now I make heavier use of expressive names for variables, classes, and methods, and tend to focus comments on interfaces and particularly tricky bits of logic.

      It's a pity there hasn't been more work with Literate Programming out in the world at large...

    7. Re:Comments by Anonymous Coward · · Score: 0

      I remember the first thing that my CS instructor said... comment everything.

      So I did

      #include // Add the headers for text output

      main() // The main function
      { // Begin main function
      cout "Hello World!"; // Will print "Hello World!"
      return 0; // Does not return an error
      } // End main function

    8. Re:Comments by Anonymous Coward · · Score: 0

      Big comment bad.

    9. Re:comments by EvanED · · Score: 1

      Hey, your parent didn't say what the indication was, only that it was an indication ;-)

    10. Re:Comments by jallen02 · · Score: 2, Insightful

      It all really depends. Ultimately I feel that you will learn to write code that explains itself to a large degree. There are two times I ask them to make comments.

      1.) The first time to comment is when you are doing something you know are not standard. Bitwise shifts to multiply, things you know are sub-optimal etc. Exceptional things that are not done how they shold be done, or are typically done.

      2.) When you want to explain how a relatively large block of code is working, or an entire classes purposes. Explaining a method or a class. Or a block of code to give an idea of flow.

      Another thing that I feel improves comment quality is to force them to be complete sentences. Try and keep the sentences brief and complete so that it clearly illustrates what you are trying to say without repeating. The "Do not Repeat Yourself" DRY principle applies to written communication as well as code.

      If you always refer back to these simple rules you will generally have code that is easier to maintain and that the comments don't go out of date on as quickly. I really think you could write an entire book on commenting code and naming variables and organizing code flow. Good Luck and happy coding!

      I will agree that developers go through phases in how and when they comment, but having someone lay out guidelines and telling you when to comment and giving you a few concerete examples makes a huge difference. For me its always about being a good leader and doing what I say. I have seen programmers come from mediocre/average just following a few simple "rules". Commenting is a huge part of it. Because if you can comment at an abstract/high level you can prove you know what the code should be doing. And if you write comments before you write the code.... ;-)

      Jeremy

    11. Re:Comments by jallen02 · · Score: 1

      (doing what I say as in.. practice what I preach :)

    12. Re:Comments by xee · · Score: 3, Interesting

      There's some nice calculus lurking in there. Something about approaching a number from either side. Oh wait! You might be saying there's an ideal amount of commenting and in large numbers programmers tend to converge on that amount. Interesting. This would make a good research topic.

      --
      Oh shit! I forgot to click "Post Anonymously"...
    13. Re:comments by Anonymous Coward · · Score: 0

      You can tell a great deal about the maturity of a programmer by the quantity, and quality, of comments.

      Good comments are at the first level of programming, writing code that doesn't require comments is the next level.

    14. Re:comments by PostItNote · · Score: 1

      Real world project comments...

      Your comments are giving me flashbacks.

    15. Re:comments by Anonymous Coward · · Score: 1, Insightful

      You can tell a great deal about the maturity of a programmer by the quantity, and quality, of comments.

      That is, the younger, less mature programmers are commenting tons and actually documenting their work because their teachers stressed how truly important it is. This is really boring. As the programmer matures, the comments decrease but the QUALITY of the comments increase, and end up being quite novel to read.

    16. Re:comments by Nefarious+Wheel · · Score: 1
      Yes. And when I write a piece of code, I generally don't want to revisit it after the first blush of admiration over it. I comment code to keep someone from trying to find me to fix it after 10 years. Comments are programming.

      One of my programmers was fighting an algorithm for the better part of a week. I told him to shut down the editor and write the comments first. He did -- and a moment's code-brain disconnect did the trick. After that little exercise he completed the function in about 15 minutes. Good coding practice or good psychology? Go figure. It ain't an exclusive-or.

      --
      Do not mock my vision of impractical footwear
    17. Re:comments by Suicyco · · Score: 1

      You are right on the money. I hadn't really thought of it that way, but I'd have to say that commenting is the true programming. Its the intent and description of the code. The implementation is arbitrary. The WHY's and WHAT's should be clearly spelled out. The HOW is almost secondary.

    18. Re:Comments by Anonymous Coward · · Score: 0

      Interesting..My thoughts on this are that when
      you know that your code is not just for yourself
      anymore you make an effort to chronicle what you
      think is going on if you care about your job, the
      other guy, and the relevance of your code to future
      programmers.

    19. Re:comments by jeanicinq · · Score: 1

      The maturity level of the programmer that reads quality code is significantly determined by the quantity of demands to comment such code.

      Comments are only needed were they are nothing less and nothing more than only needed.

      Rule of thumb taught by professors, if it takes a minute to figure out what a single line of code does than comment it. If you find that your code is full of comments, try a different line of work.

      To reduce comments, use fully functional prototypes. Take a class if you haven't learned about such precedences.

      Also, I have seen too many times that someone has tried to explain in their code what they want a function to accomplish only then read the code and find out it does not do as commented. N.B.

    20. Re:comments by Lacton · · Score: 1
      Real world project comments...

      Those examples are great. They really focus on what the code cannot express: the WHY we did it this way, and the WHY we didn't do it that way.

      I'm so tired of comments stating the obvious or, worse, comments explaining what a line of code does when a few rightly named variables would have made the comments redundant.

      Another kind of comment that I find useful is top-level comments that explain in a few words what's the purpose of the class/module/program. Although this information is implicitly contained in the code, it is too time-consuming to read everything if all you're doing is browsing a large code base, trying to find which class/module/program you need to edit.

    21. Re:comments by defile · · Score: 1

      One of my programmers was fighting an algorithm for the better part of a week. I told him to shut down the editor and write the comments first. He did -- and a moment's code-brain disconnect did the trick. After that little exercise he completed the function in about 15 minutes. Good coding practice or good psychology? Go figure. It ain't an exclusive-or.

      Out of curiousity, what was this monster impossible algorithm?/p>

    22. Re:comments by Jon_Aquino · · Score: 1

      Amen!

    23. Re:comments by Anonymous Coward · · Score: 0

      Dude, (and I don't mean anything homo by this) you sound like my kind of coder.

    24. Re:comments by mgcarley · · Score: 1

      Man, you think your comments are strange? I tend to inject humor in to my comments. I sometimes code while drunk. Not often though.

      An example:

      If you are reading this, this is commented out code. Use Linux. We do.

      It has a good preview function, so I know how fudged up it's going to look by changing a given element.

      I was going to put in the code to this to "format c:\" but decided not to after the initial reacti... err... out of lazyness and lack of code to do so

      If you want to steal, steal Mozilla. It's free with a four finger discount (some countries cut off your entire hand, you know... but I just take fingers)

      What an age we live in... mmmm donuts. Go Homer Simpson.

      If you got all the way to here, the comments in the code are better highlighted with something other than notepad.

      et al, ad infinitum!!

      --
      Founder & COO, Hayai India (hayai.in) / USA (hayaibroadband.com) // t: @mgcarley
    25. Re:comments by Anonymous Coward · · Score: 0

      Comments are important but do the right people really appreciate how important they are?

      If you were to look at (say) OpenBSD's source code and found large chunks (100s of lines) of new code almost bereft of comments, how would this change your perspective of their source code/operating system and the people behind it?

      Does this suddenly mean that despite it being revered for security, the people writing code are bad programmers? Is secure code more important than maintainable and understandable code?

      What I find most amusing about source code 'auditting' is that unless you have comments that define what a function's purpose is, how on earth can you audit it for correctness? How do you know if function X does what it's meant to do if the programmer doesn't state what their intent for it is?

      And for the obvious comments about "comments get out of date", well if the comments do not agree with the code, it is a bug. Updating code and invalidating comments is just as bad, programming wise, as writing code that does not function correctly.

    26. Re:comments by pommiekiwifruit · · Score: 1

      I unfortunately have comments such as this around certain statements

      // Stupid Stupid Microsoft VC6.0 /O2 generates bad code if you try

      // int value = data[i] | (data[i+1] << 8);

      // (generates mov dl,cl instead of mov dl,ch)

    27. Re:comments by bobaferret · · Score: 2, Funny

      Unlike everywhere else, here we're waiting for key-release instead of key-press because the operating environment has a race condition and posts them out of order! Go Sun!

      I have this one word for word in my own code. Kinda spooky to see it here, but also nice to know it's not just me.

    28. Re:comments by Anonymous Coward · · Score: 0

      you get to the point of such awesome code that it documents itself

      I don't think so, comments are writen in humane language, code is in computer language. Comments explains the idea behind the specific implementation that the code declares.
      After more than 25 years of C coding my prefered comment style is to explain every line of code with a single line comment, in a history-teller manner, that way even if you don't know about the computer language the code is writted on, you can still understand what's the idea being implemented.

    29. Re:comments by Anonymous Coward · · Score: 0

      He did -- and a moment's code-brain disconnect did the trick.

      My favourite trick to avoid mental-stalls is just to explain to another programmer exactly what are you trying to do... usually in the course of the explanation the problem becomes evident. Well I think they call it extreme-programming this days! :)

    30. Re:comments by Anonymous Coward · · Score: 0
      my prefered comment style is to explain every line of code with a single line comment,
      Holy fucking verbosity of maximally grotesque proportions Batman! You free source hippies go on doing all the stupid stuff you want with your little projects but you'd get fired for being so idiotic wasting time like that in the real world. No wonder you want to outlaw paid programming.
    31. Re:comments by EvanED · · Score: 1

      I've often wondered how that works. You can't figure out what's wrong with something (and not just code too), you go over it a bajillion times with a fine toothed comb, and you finally call someone over to look. You say "tell me if I screw something up" and start to go through it, then get to a point where you start to say what you did, stop, and go "ah ha, that's what's wrong."

      It doesn't work nearly as well if there's not an actual person there too.

    32. Re:comments by Nefarious+Wheel · · Score: 1

      It was about twenty years ago, a RSTS-E Basic+ function doing a bit of moderately complex parsing iirc. Accounting stuff, boring for the most part, but a challenge given the tools of the time.

      --
      Do not mock my vision of impractical footwear
    33. Re:comments by Anonymous Coward · · Score: 0

      I'm the new guy at my company (most of the other developers are 30+, and I'm just out of uni) but I'm the only one who comments the code.

      It's an absolute nightmare trying to understand what all these old guys were trying to do 20 years ago in their stupid code.

    34. Re:comments by aspx · · Score: 1

      I get more satisfaction out of crafting breathtaking memos. So help me god, nothing increases one's self esteem more than a buttery-ly written memo. I call it the purpose driven life.

  5. Literature by 14erCleaner · · Score: 4, Funny
    Chapter 1 introduces some of the basic tenets of the book, namely that code is literature and should be read as such.

    Unfortunately, some experienced programmers write like ee cummings, and others like avant-guard poets.

    --
    Have you read my blog lately?
    1. Re:Literature by Geoffreyerffoeg · · Score: 4, Funny

      HRESULT hReply = authEECummings (atTheLeast) vhlpDidNot vrbUse adjHungarian nNotation;

    2. Re:Literature by paulthomas · · Score: 1

      That would be avant-garde, unless you were trying to be, well... avant-garde.

    3. Re:Literature by Anonymous Coward · · Score: 0

      Win32 API? Is that you?

    4. Re:Literature by Anonymous Coward · · Score: 0

      Well let's face it, the entire concept of learning good programming style by reading open source code is surely some kind of early April Fool's joke. Most of it cannot even be read without the manual of non-standard gcc C++ extensions by your side.

  6. Hmm not sure by Rosco+P.+Coltrane · · Score: 4, Funny

    You can usually tell someone who's been writing a lot of code by how they write code.

    I looked at the slashcode once and I'm fairly sure Taco worked on debugging serial port line noise before starting /.

    --
    "A door is what a dog is perpetually on the wrong side of" - Ogden Nash
    1. Re:Hmm not sure by Anonymous Coward · · Score: 0

      > I looked at the slashcode once and I'm fairly sure Taco worked on debugging serial port line noise before starting /.

      Funny, it looks like ordinary Perl to me.

      Oh, wait...

  7. Comments by The+Amazing+Fish+Boy · · Score: 5, Insightful

    The amount of comments in code is interesting. It kind of starts at an extreme, then moves slowly to the middle, happy land.

    If you started programming, you either chose to comment a lot, or not at all. "A lot", because you were never sure what your code was doing, and always needed the reference. Or "not at all", because you could make sense of the code very well.

    Then you start your first big project. For the big commenter, he realizes after getting quite a bit of work done that a lot of time was "wasted" on comments. ("// This line increments the 'i' variable by 1".) Further, these comments seem way too obvious. For the non commenter, they get lost easily and wish they commented more.

    So it goes in the opposite direction from when it started. The big commenter comments way less, and the non commenter comments way more.

    Then it repeats. Eventually the programmer gets the happy medium of the right amount of comments.

    This has been my experience, in my own code, and checking other people's code. Thoughts?

  8. hmm... by CynicalGuy · · Score: 0

    If you know how to code, you don't need this book!

  9. On the topic by advb89 · · Score: 2, Funny

    Speaking of which, I was recently browsing sourceforge, and happened to notice this project which MUST be a good one since its home page has an error screen:

    Fatal error: Cannot redeclare fecha2mysql() in /home/groups/c/cp/cphp/htdocs/funciones.php on line 4

    Not to mention they misspelled 'functions'!
    This project can be found here, and there homepage here.
    Oh yeah, if you happen to be reading this, agustindondo, no offense intended :)

    --
    <overrated>Insert Sig Here</overrated>
    1. Re:On the topic by yoink00 · · Score: 1

      Just because you speak English that doesn't mean it's the only language in existance... I think you'll find funciones is Spanish. Stu

    2. Re:On the topic by krunk7 · · Score: 1

      Not if they're spanish they didn't:
      Spanish Dictionary

    3. Re:On the topic by cfsmp3 · · Score: 0

      funciones.php = functions.php (in Spanish)

      You're a bit dumb, aren't ya...

      --
      I would buy karma from ebay but I'm not sure I can trust the seller.
    4. Re:On the topic by patri26281 · · Score: 1

      It's spelled correctly. Funciones is spanish for functions in english. :-)

    5. Re:On the topic by mpupu · · Score: 1

      Not to mention they misspelled 'functions'!

      They just seem to be using a different language. In Spanish, fecha = date and funciones = functions.
      Agustin is also a Spanish name.

    6. Re:On the topic by advb89 · · Score: 1

      Leave me alone, i've got a c++ in my spanish 1 class. Wise you are!! (see, i can barely speak english)

      --
      <overrated>Insert Sig Here</overrated>
    7. Re:On the topic by Anonymous Coward · · Score: 0

      Very funny: the SQL code has variables named in spanish (or some funny language) and everything is hard-coded (the worst thing you could do for modularity!)

    8. Re:On the topic by advb89 · · Score: 1

      Unfortunatly as i mentioned before i have a c++ in spanish 1 (yes i said spanish 1). But that still brings me back to the point that a php board project has an error in the first place (on their own web page)

      --
      <overrated>Insert Sig Here</overrated>
    9. Re:On the topic by Jason+Ford · · Score: 2, Informative

      Hmmm, it could be that agustindondo is a Spanish speaker. 'Funciones' is Spanish for, you guessed it, 'functions.' Oh, and 'fecha' is 'date' en español.

      --
      I did not become a vegetarian for my health, I did it for the health of the chickens. --Isaac Bashevis Singer
    10. Re:On the topic by YellowElf · · Score: 1

      And "fecha" means date...

      --
      Insert witty saying or aphorism here.
    11. Re:On the topic by daremonai · · Score: 1
      Not to mention they misspelled 'functions'!
      Well... only if you consider Spanish to be misspelled English.
    12. Re:On the topic by javaxman · · Score: 2, Funny
      Unfortunatly as i mentioned before i have a c++ in spanish

      See, and here I was giving you the benefit of the doubt and thinking you were either being funny or trolling, but... well, unfortunatly you were just being dense. I hope you check your spelling in your own code better than you checked it in that last post, eh? Now I'm back to thinking you're funny again... if not intentionally.

    13. Re:On the topic by molecular · · Score: 0
      I think "funciones" might be espanol, portuges, italiano or something. so maybe it's not mispelled?

      Althought I object to localizing variable-names and such myself, you should acknowledge some people might feel more comfortable naming stuff in their native tongue. It tends to sound a little queer combined with the english keywords of the language itself:
      while (weitermachen) { tu_es(); }
      I am currently getting into a rather large navision-based database project. There, you have localized names for the database objects. In the code, you can use (in this project) either the english or german names. What a mess! I think this started when microsoft bought navision :)

    14. Re:On the topic by flibuste · · Score: 1

      Trouble with the IT industry is that even ignorance is allowed in coding and is allowed to voice out loud.
      Having said that, it rarely is a smart thing to write code in other language than english.

      You don't agree? Try debugging code written in dutch with comments in dutch, then you will!

      You still do not agree? I don't care, I'm french!

    15. Re:On the topic by r00t · · Score: 1

      Isn't it?

      They also mess up the grammar and pronunciation.

    16. Re:On the topic by Anonymous Coward · · Score: 0

      Not to mention they misspelled 'functions'!
      This project can be found here, and there homepage here.
      Oh yeah, if you happen to be reading this, agustindondo, no offense intended :)


      Not to mention you misspelled 'their'!
      The dictionary can be found here, and their entry for "their" is here.
      Oh yeah, if you happen to be reading this, offense intended :)

      (People in glass houses, and all that.)

    17. Re:On the topic by Miamicanes · · Score: 1

      Better yet, try editing a Java app that uses Unicode Han ("Chinese") characters for variable names... It would probably make the app more understandable to a beginning Chinese programmer, but leave just about everyone else raiding their office's jug of Advil LiquiGels...

    18. Re:On the topic by advb89 · · Score: 1

      Congratulations, your the 5th person to tell me that.

      --
      <overrated>Insert Sig Here</overrated>
    19. Re:On the topic by advb89 · · Score: 1

      Yeah, Yeah. As i mentioned, i'm a high school student. (i think i have a right to be ignorant) A developer of a php board should be able to spell (i was in fact making a joke - wasn't very funny though) but, the point was, that their own web page was not functioning. Also, i was typing a post on slashdot, not writing a piece of code. So, anonymous coward (and yes, i do realize that annonymous coward IS the name slash-based boards give to annonymous post-ers) the point is to RTFA. (or RTFP in this case)

      --
      <overrated>Insert Sig Here</overrated>
    20. Re:On the topic by molecular · · Score: 0

      shit maaan, it took me forever to write the comment. there was no answer when I started.

  10. Experience by kent,+knower+of+all · · Score: 1, Funny

    So the bottom line is experience? Then the following holds:

    Bad Code + Bad Code + Bad Code = Good Code!

    Yeah, right.

    --

    Select * from users where clue > 0
    0 rows selected

    1. Re:Experience by mabinogi · · Score: 1
      no it's
      while(experience < GOOD_PROGRAMMER) {
      code = writeNewCode();
      if(code.equals(BAD_CODE) {
      experience += consequences(code).lessonsLearnt();
      }
      }
      Obviously if you never learn from your mistakes, you'll never get better, but lots of bad code _can_ result in good code as long as you actually learn from your mistakes.

      (To the pedants - yes I know that nothing happens if the code is good above, and that there's likely to be errors in it regardless, but it's a stupid code analogy of a real world concept for the purpose of illustration only...WTF do you expect?)
      --
      Advanced users are users too!
    2. Re:Experience by Anonymous Coward · · Score: 0

      aha!, yes see - there were errors! I missed a ) from the if statement.

    3. Re:Experience by sik0fewl · · Score: 1

      They're talking about learning from experience, not adding it.

      --
      I remember when legal used to mean lawful, now it means some kind of loophole. - Leo Kessler
  11. I believe that what you are trying to say is that: by adolfojp · · Score: 3, Insightful

    The smart man learns from his mistakes ...

    ... but the wise man learns from other peoples mistakes.

    I guess that I am just kind of average :-P.

    Cheers,
    Adolfo

  12. Use comments only when needed by c0d3r · · Score: 5, Insightful

    I disagree when writing Java and C#. These languages are inherintley readable if you write clean, understandable code with good variable names. Comments should be used whey you implement something that you can't understand by reading the code. Its quickker for me to read clean code, and comments often get in the way and get outdated and hurt more than they help. Maintainance is the Iceburg.

    1. Re:Use comments only when needed by enjo13 · · Score: 3, Insightful

      You couldn't be more correct. Comments are often to blame for maintainibility problems, as dangling comments can absolutely destroy the readibility of code.

      I do beleive you can judge a programmer by the quality and quantity of comments.. A good programmer comments only when the code NEEDS commenting. No more, no less.

      --
      Turn s60 photos into awesome videos with mScrapbook for all S60 3rd edition phones!
    2. Re:Use comments only when needed by Anonymous Coward · · Score: 1, Interesting

      One big reason for putting in comments is to define what your doing at that step in the code. Often having the comment followed by readble code helps catch logic errors and make it easier for someone less familiar with the language, libraries, or the project involved. This also means, the comments need to address the concept involved, not just saying in text what the code does.

      For example, don't say /* increment i by 1 */ when /* advance to the next record */ is conceptually better.

    3. Re:Use comments only when needed by Anonymous Coward · · Score: 5, Insightful

      Just because it's obvious what your code is doing doesn't mean it's obvious why it's doing it. Commenting is still important.

    4. Re:Use comments only when needed by Viking+Coder · · Score: 4, Insightful

      Sure - everything works great if you are fortunate enough to start with clean code, and keep your code clean.

      But the rest of us work for a living. You know, for bosses who don't "Get It." =) We have to fight for the time to keep code clean, because that time could be spent adding features instead. It can be a hard battle.

      When you're in that kind of environment, comments can save your life. Or at least your ass.

      --
      Education is the silver bullet.
    5. Re:Use comments only when needed by 14erCleaner · · Score: 3, Insightful
      Its quickker for me to read clean code

      Maintainance is the Iceburg.

      It's really hard for me to nitpick spelling, but I can't help myself, so please forgive me...

      A good first step in writing clean, maintainable code is to be self-aware. Many experienced programmers don't realize that they write crappy code. Honest code reviews can help, but most people don't take criticism well, and negative style comments are ignored.

      (Of course, my code is perfect... :)

      --
      Have you read my blog lately?
    6. Re:Use comments only when needed by AuMatar · · Score: 4, Insightful

      Whats clear to you isn't clear to me, and vice versa. Whats clear to you now won't be clear to you in 6 months, much less 12. Thats why comments are good- in 6-12 months you will understand the comment, while you might not the code. And a thrid party is far more likely to get the comment than the code.

      As for comments getting outdated- thats why you update comments when you update code. If you don't do that, you're a poor programmer. Changing the code and not the comment is doing half the job.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    7. Re:Use comments only when needed by njcoder · · Score: 1
      I agree to a point. Within the method body, I don't comment too often, but there was one bit of advice I got once that I try and use as much as possible. Before you write your method, write the javadoc comment for it. It gives you a minute to think about what it actually is going to be doing and lets you think about the design before you start working on the implementation.

      Also commenting accessible members and methods makes coding on big projects a lot easier, as well as reuse further down the road more managable. Reuse especially should be a big factor which is a big reason why we should use these high level OO languages to begin with.

      With modern IDE's it's nice when you can start typing, and if you have a question about the implementation of a method, you can ctrl-space to have the java doc comment come up for the classes in your project. This is great, especially if you're working with other people's code as well. The docs say it does this this and this... no need to try and try and read their code to figure out what it does. Unless of course it doesn't do what it says :)

      Just knowing what parameters it takes, what it returns along with a descriptive name is usually enough but you can't but everything into the name like it may return an empty array instead of null when it doesn't find anything. Things like that help a lot.

    8. Re:Use comments only when needed by GileadGreene · · Score: 1
      Comments shouldn't be describing what code is doing - as you say, that should be obvious from the code - they should be describing why it's being done. Comments of that nature are far less likely yo go out of date in th face of implementation changes.

      And actually, I'd argue that most programming languages are "inherently readable" if you write clean code. In fact, I can think of several languages that are more readable in that regard than Java or C#.

    9. Re:Use comments only when needed by Phillup · · Score: 1

      I disagree when writing Java and C#. These languages are inherintley readable if you write clean, understandable code with good variable names.

      Yeah, with those constraints... so is Perl.

      --

      --Phillip

      Can you say BIRTH TAX
    10. Re:Use comments only when needed by Ardisson · · Score: 1

      Usual mistake : comments are not about *how* you do thing but about *why* you do them.

    11. Re:Use comments only when needed by rmccann · · Score: 1

      I Agree. Computer do exactly what you tell them to. Pure uncommented code is all you need to figure out what your code is doing. Comments are needed to tell people what the coder thought the programme was doing. That way if/when there's a bug (difference between what it's doing and what the coder wanted it to do), then you can track it down easier.

    12. Re:Use comments only when needed by gnuLNX · · Score: 1, Insightful

      Sorry, but i simply disagree with you. Comments are good, in moderation. Too many comments are a bad thing. People can learn to code in such a way that the code is readable and maintainable. If you can't write code that I can read with minimial effort then you are the bad coder, and If you can't read the code I write (most of it) then you are the bad coder. I go to great lengths to make my code as self documenting as possible. Yeah it isn't always possible and that is what the comments are for. I document the hell out of my header files, but the actual code has few and far between on the comments.

      --
      what?
    13. Re:Use comments only when needed by iabervon · · Score: 1

      The grandparent didn't specify that more comments indicates more maturity. I think it is unambiguously true (although a bit vacuous) to say that closer to the optimal number of comments indicates more maturity.

      Personally, I rarely comment my code. There are a couple of comments which substitute for statements (e.g., stating when I mean to fall through to the next case in a switch statement), and I occasionally comment some tricky statement (generally, inside a tricky conditional, I say what the intent of the test is). On the other hand, I extensively comment my declarations. Each C function gets some documentation in the header file (what are the units for the arguments; who is responsible for the memory; what happens in odd conditions; etc.), and most Java functions get javadoc (unless they are completely specified by the declaration in an interface or parent), because there's generally something that would require reading the code carefully to figure it out. Structure/class fields generally get the most documentation, because it's a real pain to figure out exactly how they behave by reading the code, since the code isn't structured that way. I've got fields where I exhaustively list all values the field can have and what they mean. If you're writing code to prepend a chunk of data to a self-resizing ring buffer, the best documentation is to explain exactly what the indices mean and give diagrams of the structure. The code documents itself, but the variable names can't tell you everything you need to know. Documenting declarations also has the advantage that you tend to kill (or update) the comment when you change the declaration, or at least orphan it in an obvious way, and declarations don't change as much anyway (because when you change them, you have to find and change everything that uses them).

    14. Re:Use comments only when needed by killjoe · · Score: 4, Insightful

      COmments are best when they explain WHY you are doing something, not just explaining WHAT you are doing.

      For example a comment that says "we have to make exceptions for clients whose names start with A because sales promised them a price cut" is very useful when somebody is scratching their head asking why there is a goofy if statement sitting there.

      --
      evil is as evil does
    15. Re:Use comments only when needed by Anonymous Coward · · Score: 0

      This reminds me of a code review I had. The company's policy was to hold a formal code review of the first piece of code any new hire writes. I commented where I thought it was necessary, but didn't really have too many of them when I was done. My manager's comment in the review was something along the lines of, "I was going to tell you it wasn't commented enough, but when I looked at it, I couldn't find any place that actually needed more. So, good job, and don't do it again!"

    16. Re:Use comments only when needed by AuMatar · · Score: 1

      And like I said- your opinion of whats readable and maintainable is NOT going to be the same as mine. It goes down to the fact that different people think in different ways, and have different level of experience with programming concepts and math constructs. Thats where comments come in- you make things clear to people who aren't you what you're doing.

      Trust me, I've done a lot of maintenance work, both on my own code years later and on others code- what people think of as clear HUGELY differs. A few comments and some documentation makes the difference between something you can figure out in minutes and something you need to track down the original author to get.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    17. Re:Use comments only when needed by Artifakt · · Score: 1

      One of the best comments I ever saw was along the lines of "Last Names are sorted into 27 groups, including "Mc".". It probably should have been more verbose, for as it turned out, an overseas developer still had no idea why that was being done and ignored it when modifying part of the code until the local prevalence of Scottish surnames was explained to him. Once someone who understood it read it though, both problem and solution became obvious.

      --
      Who is John Cabal?
    18. Re:Use comments only when needed by Grax · · Score: 1

      Boss: "How long will it take to create feature X?"
      Herbjorn the Programmer (to himself): "Hmmm. 22 minutes to implement feature X plus 4 solid hours of code cleaning plus upgrading my workstation"
      Herbjorn: "3 days, sir. I'll get right on it."

    19. Re:Use comments only when needed by Suicyco · · Score: 4, Insightful

      That is not the commenting at fault, it is the sloppy programmers who do not update them. Code NEEDS commenting, period. In any decent sized code base, it is not at all clear WHY things are being done at times. So you can read the code, any programmer should understand the syntax and conventions being used. That is not important. What is important is a concise, clean and understandable code structure with good comments. You can NEVER guess the level of future people reading this code. Just spell it out, what is the harm? Do not be sloppy, do not be arrogant and simply engineer good clean well documented code.

      The attitude that commenting is only something to be done if something isn't obvious to YOU is totally wrong and results in poor quality.

      The problem with not doing this, is if its not totally obvious WHY something is being done, it may get changed to something "better" which may break things. Perhaps that particularly ugly sort algorithm needs to be there because of extensive profiling done on the code. If that isn't spelled out, somebody may stroll along and think you were an idiot for obviously using the wrong sort and ruin the performance. For instance.

      ALL code NEEDS commenting at ALL times.

      I can always judge a programmer by the quality and quantity of the comments. A good programmer doesn't presume to know when the code NEEDS commenting based on his totally biased opinion. It always NEEDS it. A good programmer knows what to say to make things as clear as possible.

    20. Re:Use comments only when needed by PhotoBoy · · Score: 1

      Exactly, something like

      if (x.doIt())
      {
      //...
      }

      is unintelligable, but something like

      if (database.isConnected())
      {
      //...
      }

      doesn't require comments at all. I admit this is a stupidly simple example, but I think it demonstrates that the naming of objects and variables as well as code layout is far more important than including reams of comments that can be ambiguous or just plain wrong. And it's not as if all programmers can write comments legibly either, spelling, grammar and punctuation seem to be thrown out the window sometimes.

    21. Re:Use comments only when needed by Anonymous Coward · · Score: 0

      Mod Parent up, with the variety of skillsets out there future developers looking at your code may not deem obvious what you yourself deem obvious. (And other parts they might say, "Well Duh".) The best practice is to document as much as possible when initially writing and maintaining code AND comments when doing maintenance.

    22. Re:Use comments only when needed by mad.frog · · Score: 1
      These languages are inherintley readable if you write clean, understandable code with good variable names

      Hope I never have to work with your code.

    23. Re:Use comments only when needed by Anonymous Coward · · Score: 0

      Programming != documenting.
      Let's be honest for once.
      There are crackerjack hackers who
      couldn't formulate an intelligible
      paragraph.

      This onus of documentation is the
      result of persons realizing that the
      creator of a code section has a better
      idea of what the intended purpose is
      than 'Johnny off the street' come to
      replace him. Therefore document now to
      cement the code you wrote for profit into
      the margin of future profitability and not
      into the niche of 'inspired problem solving'
      or somesuch.

      My .02 cents.

    24. Re:Use comments only when needed by gnuLNX · · Score: 1, Insightful

      "And like I said- your opinion of whats readable and maintainable is NOT going to be the same as mine. It goes down to the fact that different people think in different ways,"

      Very true...but yet we all seem to be able to communicate with normal langauges without to much difficutly. If you and I both understand the programming language and the problem at hand..with a well thought out design then we should be able to code in such a way that we need mnimial english...or whatever language.

      Not to mention if we both have different coding styles then the whole experience turns into a learning experience since we are both forced to read more code...and in my opinion reading a lot code is almost as important as writing a lot of code if you really want to become good at it.

      Anyway I am not really disagreeing with you....I think that I am simply suggesting that development should be done closer to that "ideal" environment were all designs are well thought out and documented...I suspect you are talking more about maintenance and I also understand first hand how bad it is to maintain code that was not meant to be readable without comments...yuck!

      --
      what?
    25. Re:Use comments only when needed by FireballFreddy · · Score: 0

      I love a good programme. I also like eggs and hamme with toast and jamme.

      -FF

      --
      SQUEAK, the Death of Rats explained.
    26. Re:Use comments only when needed by PugMajere · · Score: 1

      If you have a need to say either, that should tell you something about how clear your code is.

      If you need the comment to explain how the code works, fix the code, then delete the now unnecessary comment.

      Nothing is worse than seeing code that says:

      /* if status == 1 */
      if (status == 1) {

      That comment does *absolutely* nothing for readability.

    27. Re:Use comments only when needed by berenddeboer · · Score: 1

      No, you can factor them all away. Just use a few variables:

      all_clients := ...
      clients_whose_name_starts_with_A := ....
      price_cut_promised_by_sales := clients_whose_name_starts_with_A
      No chance that comments get outdated. Because the comments are code it will be maintained. And it is quite readable. With a decent editor that does completion you have to type the variable names just once.
      --
      If I had a sig, I would put it here.
    28. Re:Use comments only when needed by Avenger546 · · Score: 1

      How about this then?

      /* status 1 indicates that the user's password has been locked out by the administrator */
      if (status == 1) {

      I'm fairly certain that Joe Bob will really appreciate that comment when he comes along and takes a look at the code for the first time. Yes, after he's been working with the program for a long time, he'll have all the statuses memorized, and this comment will be fairly useless to him. But until then?

    29. Re: Use comments only when needed by gidds · · Score: 1
      You're both wrong!

      Parent, you should be aware that that language you use, English, is named after a place: England. And that in some parts of the world (notably, the USA) you spell some words differently from* how we here in England do. (* You'll note that I didn't say 'differently than', which is an abomination.)

      And grandparent, you should be aware that even here where 'programme' is a valid spelling for general use, we still use 'program' when referring to a list of instructions controlling the operation of a computer; 'disk' and 'dialog' are also US spellings which we use in that context.

      So there.

      Getting back on topic, I'm with the grandparent. Code should be completely transparent as to what its doing, but it's usually an extremely good idea to comment why. To fill in the big picture, and this bit of code's place in it. I wonder if the main reason for much crap code is that the coder simply didn't know the big picture...

      --

      Ceterum censeo subscriptionem esse delendam.

    30. Re:Use comments only when needed by jerky · · Score: 4, Insightful
      Just write it as
      if (pw_status == ADMIN_LOCKED) {
      and leave out the comment.
    31. Re:Use comments only when needed by PugMajere · · Score: 1

      Exactly.

    32. Re:Use comments only when needed by mooingyak · · Score: 1

      I disagree when writing Java and C#.

      If you are already familiar with them, sure. If you're still new to either one, Java and C# can still be cryptic.

      ANY language is inherently readable if you "write clean understandable code with good variable names."

      I agree with the rest of what you say though.

      And as an aside, REALLY good coders can use language features you've never seen before and you'll quickly recognize what it does because it was used appropriately and cleanly.

      --
      William of Ockham had no beard. The most likely explanation is that it was chewed off by squirrels every morning.
    33. Re:Use comments only when needed by Anonymous Coward · · Score: 0
      ALL code NEEDS commenting at ALL times.
      Wow. Were you involved in the design of Java?
    34. Re:Use comments only when needed by Anonymous Coward · · Score: 0
      Or:

      /* advance to the next record */
      recordSet->next();

    35. Re:Use comments only when needed by buics · · Score: 0, Redundant

      I agree

    36. Re:Use comments only when needed by Brandybuck · · Score: 0, Offtopic

      I disagree when writing Java and C#.

      Hah. Hah. Hah hah hah. Hah. Hah. Hah hah hah. Hah. Hah. Hah hah hah. Hah. Hah. Hah hah hah. Hah. Hah. Hah hah hah

      Giggle snort chuckle

      [laughing coca cola out the nose]

      Hee hee hee.

      --
      Don't blame me, I didn't vote for either of them!
    37. Re:Use comments only when needed by Anonymous Coward · · Score: 0

      define what your doing

      "you're".

    38. Re:Use comments only when needed by Anonymous Coward · · Score: 0

      "There are crackerjack hackers who
      couldn't formulate an intelligible
      paragraph."

      Not to mention stupid idiots who put extraneous newlines in their paragraphs.

    39. Re:Use comments only when needed by Bill+Dog · · Score: 1
      what people think of as clear HUGELY differs. A few comments and some documentation makes the difference

      Your thesis assumes that the programmer who writes unclear code, but who doesn't recognize it as such, will somehow be able to write clear comments.

      --
      Attention zealots and haters: 00100 00100
    40. Re:Use comments only when needed by Anonymous Coward · · Score: 0

      I try and use as much as possible

      "try to use".

      Before you write your method, write the javadoc comment for it.

      Pyhton gives me a syntax error if I do that. So do LISP, ADA, and Visual Basic.

      With modern IDE's

      "IDEs".

      no need to try and try and read their code

      "to try and try to read".

    41. Re:Use comments only when needed by boris_the_hacker · · Score: 4, Insightful

      First rule: Nothing is obvious.
      Second rule: Nothing is easy.

      I was in a talk the other day and someone was explaining his research. He used the words obvious and easy more times than I have fingers, just on the first slide!

      Afterwards I took him to one side and explained to him that most things are obvious and easy when you have been working on them for 2 years. He agreed and re-worked his approach.

      It is the same with code, it is never obvious nor easy if you are not familiar with it.

      The code I write is clean, uses meaningful identifiers, remains conistent in both structure and layout (I try to be anal about it). However, going back to some code I wrote last year, I wouldn't have stood a chance of understanding it if it wasn't for the comment explaining the algorithm in the code. This isn't because it is bad code, but because it was complicated and doing intelligent tasks (I would guess complicated and intelligent tasks covers most code).

      Comments are required and are useful for understanding code, providing a bigger picture. Good comments compliment well good code. This is the same for any language.

      You can have bad comments, or too many comments, but if you follow the same set of basic rules for you comments that you do your code, things should be fine.

      --
      chris at darkrock dot co dot uk
      http colon slash slash www dot darkrock dot co dot uk
    42. Re:Use comments only when needed by God!+Awful+2 · · Score: 3, Interesting

      ALL code NEEDS commenting at ALL times.

      You, sir, are correct. The developers I work "with" who never write comments (and in fact argue against them), are the same ones who believe that all code not written by them is a big kludge and needs to be rewritten, and they are also the same ones who are always introducing subtle flaws because they modify code without understanding all the consequences.

      I also need to take issue with the submitter's comment that inaccurate documentation (or comments) is worse than none at all. At least a document/comment tells you what someone *thought* the code was supposed to do.

      An incorrect comment is verifiably false. Once you discover that the code doesn't match the comment, you can make an educated guess about which one is correct. On the other hand, when you are faced with suspicious code and no comments at all, you typically have no idea whether the code is broken or whether you just don't understand what it was intended to do (or in many cases *both*).

      -a

    43. Re:Use comments only when needed by ebbe11 · · Score: 1
      all_clients := ...
      clients_whose_name_starts_with_A := ....
      price_cut_promised_by_sales := clients_whose_name_starts_with_A

      This works only until someone decides to "optimize" the code:

      all_clients := ...
      price_cut_promised_by_sales := ....
      --

      My opinion? See above.
    44. Re:Use comments only when needed by Anonymous Coward · · Score: 0

      I can not disagree MORE on the topic "code needs comment". I thought THIS was already discussed in ancient TIMES and proven to be wrong.

      PS: I also USED capital words randomly

    45. Re:Use comments only when needed by Anonymous Coward · · Score: 0

      ALL code NEEDS commenting at ALL times.

      That's an extreme position and it's no longer widely in favour. Read Stroustrup, for instance. Of course, Stroustrup and all his followers could just be wrong but that's doubtful, don't you think?

      I can always judge a programmer by the quality and quantity of the comments

      Given your extreme dogmatic position on commenting, this can hardly be called judgement.

    46. Re:Use comments only when needed by Anonymous Coward · · Score: 0

      If you don't do that, you're a poor programmer

      There are a variety of reasons why comments don't get updated in practice. It's not as simple as being a "poor programmer". Any system that assumes programmers will never make mistakes is a system for propagating those mistakes. The "fewer comments" system mitigates the mistakes rather than ampilifying them. That makes sense.

    47. Re:Use comments only when needed by p3d0 · · Score: 2, Insightful

      Others have said why comments are important, so I'll just say this: if someone says "you can tell a great deal about the maturity of a programmer by the quantity, and quality, of comments" and you reply "nah, I don't think they're that important", what do you think that says about you?

      --
      Patrick Doyle
      I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
    48. Re:Use comments only when needed by arkanes · · Score: 1
      Here, let me show you why it's a stupidly simple example and why you should comment your code
      Say the code is as such:
      if (database.isConnected()) {
      ....
      if (!database.isConnected()) {
      database.connect();
      }
      }
      It's perfectly clear what this does but a year from now a maintenance programmer is going to see this, think the check is redudant and pull it out. Compare with this:
      if (database.isConnected()) {
      ....
      //An exception in the first statement can cause the connection to reset
      if (!database.isConnected()) {
      database.connect();
      }
      }
      ecode tag is stripping my indentation so you'll have to imagine it on your own.
    49. Re:Use comments only when needed by Anonymous Coward · · Score: 0
      Pyhton gives me a syntax error if

      There are no syntax checkers for "Pyhton", pedantic dork.

    50. Re:Use comments only when needed by boots@work · · Score: 1

      People always use that as a strawman, but I've never seen a comment like that, and I've seen some pretty bad code.

    51. Re:Use comments only when needed by PugMajere · · Score: 1

      I've actually seen it, within the last year, even.
      I translated it from Perl, to be more accessible, but it was:

      #+ # if support_agent EQ SalesForce
      #+ if ( $support_agent eq 'SalesForce' ) {

    52. Re:Use comments only when needed by Anonymous Coward · · Score: 0

      You're missing the point the grand-parent was making about using sensible names for things, they were not advocating not using comments at all, just that comments are pointless in some instances and illegible in others. Only comment when needed, simple stuff should not need it if your code is well structured and named.

      When the comments are useless readable code is your only hope. There are plenty of coders who can't spell to save their lives but can write superb code, I've met quite a few of them. And in this age of oursourcing where English isn't always the first language, well named structures, variables etc are vital.

    53. Re:Use comments only when needed by Tim+Browse · · Score: 1

      Disagree. That's fine if I want to know what each and every line of code is doing. However, sometimes I want to know what a few lines of code are doing without having to parse and understand every line in my head, keep track of variable usage, etc. Sometimes I want to work at a level slightly higher than the syntax.

      For that, a summary comment of the block's purpose is invaluable.

      And maintenance is where this comes in useful.

      It worries me that people can't see this, and still fall for the 'self-documenting code' myth.

      Write and document every function as though I'm just visiting because I'm trying to track down a bug, and I really don't want to have to learn the ins and outs of all your data structures/objects while I'm just there trying to satisfy myself that it's not the source of my problem. I'm usually not curling up with your code with a pipe and some cocoa at bedtime.

    54. Re:Use comments only when needed by Raunch · · Score: 1
      Just write it as
      if (pw_status == ADMIN_LOCKED) {
      and leave out the comment.


      I'm sorry, Your comment got modded up and I have no idea what you guys are talking about, but as someone who just read your code, I have a few questions:
      What the hell does 'pw' stand for in pw_status?
      If it stands for password, then does that mean that the user can't login?
      Does it mean that they can't change their password?
      Does it mean that they do not have ADMIN level permissions, or maybe only admin level permissions?
      Maybe they can only login as admin?
      Or did the administrator lock 'pw_status', whatever it means?
      --
      George II -- Spreading Freedom and American values, one bomb at a time.
    55. Re:Use comments only when needed by 2short · · Score: 1


      I've definitely seen comments like that. But most commonly I see comments like: /* status == 1 means the account is locked */
      if (accStat == "ModeAlpha5" || pwdS == 'Z') ...

    56. Re:Use comments only when needed by Anonymous Coward · · Score: 0

      Comment what you're trying to do and why, not how.

      Too few comments can be a problem, but too many comments decrease code density and readability.

      At least give a concise description of what each function/lambda/what-have-you does, but if you haven't done any magic in going from this description to the implementation, then the code body itself doesn't need documentation.

      A previous poster pointed out that sometimes a particular way of doing things is needed, for example when profiling shows the need for a different algorithm. In these cases, it should be documented.

    57. Re:Use comments only when needed by Anonymous Coward · · Score: 0

      ALL code NEEDS commenting at ALL times.

      You, sir, are correct.


      private boolean containsZero(char[] chars) {
      for ( int i = 0; i < chars.length; ++i ) {
      if ( chars[i] == '0' ) {
      return true;
      }
      }
      return false;
      }

      If that needs a comment, I'll eat my hat.

  13. So that is why my speling and gramor is so bad.... by Omega1045 · · Score: 1, Funny

    I am waiting for the intelliSense to suggest the word!

    --

    Great ideas often receive violent opposition from mediocre minds. - Albert Einstein

  14. Coding style by tjwhaynes · · Score: 5, Insightful
    After a while working on very large projects (>1Gb source code) I've begun to find that certain things which looked fine for personal projects are serious problems when you scale up.

    Most critical is managing complexity. Large, complex functions are bad - they have more bugs, they are harder to maintain, harder to bug fix (a change has more likelyhood of breaking something else). If a function has grown beyond a hundred lines of (real) code, it is almost certainly too large. If it has more than 4 levels of nesting, it is too large.

    Comments also matter. It's easy to code a couple of thousand lines of fresh code over a weekend if you get in the groove. It is almost impossible to unpick it one year later if you didn't comment it as you go.

    Variable and function names should be expressive. No single letter variable names! No obscure combinations of letters like words with no vowels (fnct could be function or function control, or even Function Numerical Constant Type). And personally I find that reverse Hungarian notation can be more trouble than it's worth. puiAnnoying!

    Build in automatic checks on everything. If a pointer to a function should never be null, check it and stop if it is. If a variable should only have values 1 -> maxIterations, then check it. If you (or anyone else) ever breaks that assumption, the code will flag it for you.

    Beyond that, nothing beats good design, especially designs where extending the original work is easy. So many designs end up as tangle knots of conflicts because they ended up trying to solve problems that the original code base never envisaged.

    Cheers,
    Toby Haynes

    --
    Anything I post is strictly my own thoughts and doesn't necessarily have anything to do with the opinions of IBM.
    1. Re:Coding style by nacturation · · Score: 1

      Judging from your sig, I take it you work for IBM. Out of curiosity, what projects had more than a gigabyte of source code? That's just massive! (To me, anyway.)

      --
      Want to improve your Karma? Instead of "Post Anonymously", try the "Post Humously" option.
    2. Re:Coding style by excesspwr · · Score: 4, Insightful

      You point out some very common problems my colleagues and myself have run into and discussed many times.

      Just to add some more to what you are stating. I've come to the realization that I must determine the final size of a project before starting. If, for instance, a program starts out as a simple Perl script for parsing an input file and later ends with a request for a GUI to be added and additional functionality I'm better off starting over and rethinking the final design then just pasting on the necessary changes to meet the new requirements. Otherwise, the project, although still small and maintainable over a week or two is complete chaos when revisited in say a month or two.

      Comments do matter, however; it does seem over commenting is just as much of a problem as no comments or under commenting. I have been handed projects from long gone developers that have had more comments than code. While it did give insight into what they were doing it became hard to find the code amongst all the comments, even with color coding turned on. It's an artistic poetry of having the right thing to say and saying it correctly. Which I am far from doing in this post.

      The automatic checks on everything that you mention, exception handling and such, should be designed into the project from the start. Grafting it on after the fact is a nightmare and I have pity for anyone that is asked to do this and especially with code that is not theirs.

      A good approach to design, I believe, trumps everything though. If you can hash out truly usable requiremets and implement a good personal software process and stick to it documenting as you go the end product always seems to turn out many notches above par even for small projects. However, none of this ever seems to occur where I work. Half baked requirements and a lack of time to properly design and implement seem to be the norm.

    3. Re:Coding style by AuMatar · · Score: 4, Insightful

      [quote]Most critical is managing complexity. Large, complex functions are bad - they have more bugs, they are harder to maintain, harder to bug fix (a change has more likelyhood of breaking something else). If a function has grown beyond a hundred lines of (real) code, it is almost certainly too large. If it has more than 4 levels of nesting, it is too large.[/quote]

      The problem with hard fast rules like that is they're frequently not right. Take a state machine for example. A simple one with 6 or 7 states will go over 100 lines, and will go over 4 nestings. Heck, you'll take one up with the loop and one with the switch alone. You can break it into functions and hide some of the nesting in functions, but when doing that you frequently end up with functions that don't make a lot of sense by themselves.

      A better rule than size IMHO is the one logical operation rule. A function should do one logical operation (read a file, write a file, run a state machine, calculate something, etc). They should contain all the logic needed to do that operation plus any debug and error handling that makes sense at that level of code. They should be broken up into subfunctions ONLY if those subfunctions themselves follow the logical operation rule, and only if that logical operation makes sense outside of the context of the higher function.

      Take the state machine example. If it needs to wait on a semaphore before each iteration, the wait should be its own function- waiting on a semaphore is a logical operation. The logic for each state should NOT be separate functions, they are part of the state machine and make no sense without the whole of the machine for context. Breaking them out results in harder to read code, even if you do lose the nesting. But if in case RUNNING_MOTOR you issue a stop command to the motor that probably makes sense to be its own function- how you actually stop the motor isn't part of the core logic of the machine.

      I guess my point is- lines of code isn't the enemy, some things are complex and need many lines to do. Nesting isn't the enemy, some things require many loops/ifs. The enemy is a lack of clear separation of functionality and lack of clear abstraction between parts. If you have separation and abstraction, it tends to hit the optimal readability. If you don't, it will fail either because you broke it up too much (too little context) or too little (too much context).

      --
      I still have more fans than freaks. WTF is wrong with you people?
    4. Re:Coding style by LiquidCoooled · · Score: 1

      Single letter/short variable names.

      I use them A LOT.

      Only in one instance however.
      I always use "a" "f" "idx" type variables when its entire definition/use is private and on the same page.
      Short loops etc.

      Wherever the scope is larger than a page or so, or its on a public interface I use full names.

      DocumentArea, PageTemplateStyle etc

      Makes sense, and doesn't confuse any of the other devs.
      I tend to keep functions compact and to the point.

      --
      liqbase :: faster than paper
    5. Re:Coding style by bloosqr · · Score: 2, Insightful

      Actually this is one of the great things about C++. If one codes in a subset of C++ (C style,
      w/ local functions) and adds in auto nulled
      pointers and auto bounds checking via templates
      and auto memory leak checking on assignments (via
      templates as well) such that those modes are on only as a compile time option you get the best of both worlds, error checking when you need it and when you are absolutely convinced that the code will work, you can turn it off and get C/Fortran
      type performance..

      -bloo

    6. Re:Coding style by Anonymous Coward · · Score: 0

      LMAO mod parent up as funny!

    7. Re:Coding style by Anonymous Coward · · Score: 1, Insightful

      Variable and function names should be expressive. No single letter variable names!

      I agree with that for most cases. My variables are usually very descriptive, as are the functions. However, for simple counters I find that using i or j or similar works quite well. After all, everybody understands a for loop with an i index -- calling it array_index_counter or some-such is (IMHO) pointless.

    8. Re:Coding style by Anonymous Coward · · Score: 0

      After a while working on very large projects (>1Gb source code)

      Just out of curiosity, I wanted to see what 1 gig of source code could work out too. 125 million 80 character lines.

    9. Re:Coding style by waveclaw · · Score: 2, Interesting
      The problem with hard fast rules like that is they're frequently not right.

      While I'm sure you've seen McCabe Metrics and the evil that is KLOC, hard and fast rules like
      If a function has grown beyond a hundred lines of (real) code, it is almost certainly too large. If it has more than 4 levels of nesting it is too large.

      are actually well-tested and well-known observations about the complexity of software code when read and written. Remember that unlike a computer, which knowns only its current state, a human can only track so many multiple states at once.

      Take a state machine for example. A simple one with 6 or 7 states will go over 100 lines, and will go over 4 nestings.

      Ah, the switch based state machine. You remind me of my college days learning formal automata for AI and compilers. If I saw a huge switch statement in the middle of parser code, I can be sure of how little training and experience the coder had when he/she wrote that. There are alternatives and they are so much more elegant.

      Swtich-based state matchers were a poor design then, and are a poor design now. By using maps, state tables, or even hashes your state machine can be 50-100 lines with thousands of states and easily readable code. Of course, the documentation of state transitions becomes very important. This information will be forced from the switch/case statement labels and into secondary documentation, such as *gasp* pictures of your state transition network. So, your state names will not be readily visible in the code (unless you are very good at reading sparse matrices and compressed linked-lists.) The compact and simple table-based code will be easier to maintain than a monstrous switch.

      Take the state machine example. If it needs to wait on a semaphore before each iteration, the wait should be its own function- waiting on a semaphore is a logical operation. The logic for each state should NOT be separate functions, they are part of the state machine and make no sense without the whole of the machine for context.

      From formal automata theory we know this to be incorrect. It sounds right, but leads to statements such as the intermingling of different functions as proposed here. Each state is independent of all other states. Each state does have incoming transitions and outgoing transitions. These transitions are completely isolated from the internal facts of those state from which they originate or terminate.

      Mealy machines perform actions only on transition. Moore machines perform actions only while in a state. Hybrids exist that do some of one and some of another. Even simple automata such as those show can have no well-defined state- or transition-based actions. None of these require implementations in code that break the 100-line and 4-depth rule. All of them can be implemented with a table and a transition function containing *gasp* no switch statements.

      There are a slew of Computer Science courses that delve deeper into a topic such as state machines and code readability. (I'm certain they must be terribly boring and useless to be overlooked by so many professional coders.) But, state transition is just as well known as other logic operations like array index math and -dare I say- waiting on a semaphore. These courses cover a lot of techniques, but all that have implementations that benefit from the 100-line and 4-depth rule above.
      --

      "You cannot have a General Will unless you have shared experiences. You cannot be fair to people you don't know."
    10. Re:Coding style by Linknoid · · Score: 1

      Talking about large complex functions being bad... I downloaded the source to Vim because I wanted to add a feature. I've spent quite a bit of my spare time trying to figure out exactly what areas I need to change, but the function I'm trying to modify is over 2000 lines long! Maybe I'll get it figured out eventually, but it would be nice if all that functionality were broken down into smaller pieces.

    11. Re:Coding style by iwadasn · · Score: 1

      No joking. Here are some hints for java newbies. Following (at least some of) these will help immensely to reduce those strange random bugs.

      1) Run findbugs, fix (almost) everything. Especially double checked locks, those are always wrong, and they will cause an error sooner or later.

      2) Always check all parameters to every function for range and nullness. You may think "Oh, but the next line throws a NPE if it's null.", and that may be true, right now. The problem is, code gets moved around, and 6 months later, you're wondering how a null member ended up in your supposedly not-null data structure. Always do all the checks. If they're too strict, you can back them off during testing.

      3) "static final *[]" is almost always wrong. Use Collections.unmodifiableList(Arrays.asList(....)) if you need to declare a constant array. It looks a little uglier, but you can at least be guaranteed that its contents are really constant. Also, in most of these cases a lot of for loops get written to find whether or not the array has a certain member. Collections.unmodifiableSortedSet(...) or Collections.unmodifiableSet(....) will be your friend here. Use a list and you don't have to write the search code (this is a good thing). Use a set, and you've more precisely declared the purpose of the array (ordering doesn't matter), and you don't have to write the search code, and your searching will be faster (for decently large sets). Use a sorted set, and you will also get things in a nice (alphabetical, for strings) order if you have to print them out. Also, last I checked, a TreeSet is faster than a HashSet for size less than about 100, when holding most types of strings. Sorted sets are much easier to debug, keep this in mind... "Quick, do these two sets with 500 elements each contain 'washington'?"....

      4) Throw some sort of exception when you get to a situation that should be impossible. This is better than a comment (as it is guaranteed to not be out of sync), and it will find all sorts of clever little bugs hiding in your code.

      5) Write if conditions as "if(null == x)" rather than "if(x == null)". If you ever end up writing in C, you'll find out all too quickly that "if(x = null)" can be valid, but incorrect code. Placing the constant first will cause an incorrect assignment instead of comparison to throw a compiler error in any language.

      6) Make things final whenever you can. Fields should be final when you don't modify them, if they are private (and maybe even if they're public or protected). Methods and classes should be final when you don't think anyone should override them. This helps the reader to easily establish where a function call is going "It's going here, because this method is final, so I know it isn't going to some subclass somewhere....", and makes life easier on the computers as well. Make parameters to methods final when you don't plan to modify them. You'll be surprised how many bugs this will uncover.

      7) Whenever possible, don't accept, or return mutable objects. Granted, this often isn't practical, but keep it in mind. Don't store mutable objects if you didn't create them yourself, or if you gave them out to the outside world. Also, try to convince sun to get rid of the Date.setTime(long) method, and finally remove all those deprecated methods. That would make Dates immutable, and help to find so many bugs it'd make your head spin.

      8) Don't use deprecated methods. Many of them were deprecated for subtle correctness issues, don't use them.

    12. Re:Coding style by Jeremi · · Score: 1
      Large, complex functions are bad - they have more bugs, they are harder to maintain, harder to bug fix (a change has more likelyhood of breaking something else). If a function has grown beyond a hundred lines of (real) code, it is almost certainly too large. If it has more than 4 levels of nesting, it is too large.


      I know the above is the conventional wisdom, but I don't necessarily agree. I think they key criteria for a function is that it should embody a single intuitive logical operation. If it takes a small amount of code to implement that operation, great -- if it takes a large amount of code, that's fine too. The key attributes of a function are that it has a well-defined interface, it can be called from different contexts and will do the things that its interface says it will. Code that has been split off into a separate function just to keep function size down to some arbitrary number of lines is schizophrenic code: it was designed to be called from only one context, but it's packaged as if it is callable from more than one context. That means that whenever you examine that code, you have to ask yourself "who calls this code? What do they expect from it? What precondition-state is necessary to have it work properly?". If the code is left as an inline part of a larger function, then that question doesn't come up -- you know there is exactly one place where that code can be executed. There is no way it can be called "from the wrong place". That is one less potential confounding factor to worry about when I am debugging/analyzing later on.


      As far as too many levels of nesting making things difficult to trace, I don't find that to be a problem in practice... as least not as long as my text editor has automatic bracket matching (and these days they all do).

      --


      I don't care if it's 90,000 hectares. That lake was not my doing.
    13. Re:Coding style by Anonymous Coward · · Score: 0

      Honestly, if you go over 100 lines in one function - you almost certainly have a lot code in that function that should be functions, and are logically either distinct, logical operations, or ought to be utility code.

      For example, I recently rewrote some code that one of my co-workers wrote. This code was over a hundred lines, WELL over, and it's length was due to the same code block being pasted over, and over, to do the same thing on seperate collections of objects.

      I rewrote it, writing functions for the things that were distinct, logical operations. The ending line count for the original function is 23 lines.

      The things that were originally inlined were operations like 'figure out if any foo exist' and 'get me the set of bar for this specifying value'. Just pasted, over and over and over - things that should obviously be a predicate function, or a utility function, etc.

      Anytime I see a function that's longer than 50 lines or so - and when they're longer, I almost always find lazy, cut & paste coding - and that kind of coding leads to unmaintainability.

      Code that has been split off into a separate function just to keep function size down to some arbitrary number of lines is schizophrenic code

      I would tend to agree - but it's because when that's done, the people that do it don't look at 'let's find what the logical operations that make sense are, and split -that- out' - they just chop stuff up into a function almost at random.

      In other words, if you keep your functions down to small logical operations, you'll find that you're almost never going above about a hundred lines or so in the first place - and because they are functions that make sense as a function, you don't run into your other objections.

    14. Re:Coding style by dutky · · Score: 4, Informative
      AuMatar wrote
      The problem with hard fast rules like that is they're frequently not right. Take a state machine for example. A simple one with 6 or 7 states will go over 100 lines, and will go over 4 nestings. Heck, you'll take one up with the loop and one with the switch alone.

      If you are coding state machines with switch statements, then you don't know what you're doing.

      The state transitions, transition functions and accepting states should be stored in tables (2-dimensional arrays) and the entire state machine is then coded in about a dozen lines:

      int next_state[NSTATES][NTOKENS]={{...}...};
      int state_trans[NSTATES][NTOKENS]={{...}...};
      int accept[NSTATES]={...};
      int retval[NSTATES]={...};
      int (*trans_func[NFUNCS])(...)={...}; /* syntax may be wrong */

      int state_machine(...)
      {
      int st = 0, tok = 0, err = 0;

      while(accept[st] == 0)
      {
      tok = get_token();
      err = trans_func[state_trans[st][tok]](...);
      if(err)
      return err;
      st = next_state[st][tok];
      }

      return retval[st];
      }

      All the real work is in the state tables and the transition functions referenced in the transfunc array. I've found it a hell of a lot easier to get the state tables right than to find all the mistakes in a giant, nested switch statement. In most circumstaces the state tables can be constructed from the state diagram by inspection. For anything big enough that you can't construct the state diagram by hand, there are automated tools.

      I guess my point is- lines of code isn't the enemy, some things are complex and need many lines to do. Nesting isn't the enemy, some things require many loops/ifs. The enemy is a lack of clear separation of functionality and lack of clear abstraction between parts.

      Lines of code or nesting depth may not be the enemy, but they're no ally either. It can be quite difficult to specify to a diverse team what is meant and expected by clear abstraction and separation of functionality, but almost anyone can wrap their brain around a LOC or nesting depth limit. If you don't want to make hard and fast rules, you can use these limits as warning signs during the code review.

      On the average you can say something like: "good code shouldn't have functions longer than two pages (120 lines) and no more than 4 or 5 levels of nesting" and hand out indulgences where needed. At least you might get some of the lower functioning members of the team to think before they code a 5000-line monstrosity.

    15. Re:Coding style by AuMatar · · Score: 1

      I'd refuse to work on a state machine that looks like that. Is it fewer lines? Sure. But its far, far harder to understand. The core logic of the machine- the transitions and per state logic- requires you to look up 4 arrays and n functions to figure out. That would be a fuckign nightmare to use. The first thing I'd do is rip it out, its overly complex at a loss of clarity. Its a great way to mathematicly define a state machine for an automata class, but its a horrible way to code one. Look at some real embedded code with hardware state machines- you won't find any of them coded like that. Look at VHDL code used to describe hardware state machines- they won't use it either. There's a reason why- there's easier ways to maintain.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    16. Re:Coding style by AuMatar · · Score: 1

      Also- you assume that the state machine can specify the successor state as a funcion of only the current state and the transition type. While there's a wide array of state machines that can be expressed easily that way, many can't be easily. Yes, its theoreticly possible to change any state machine into one that does with minor changes, but that frequently will end up with an unwieldly number of states. As I said above- there's a reason why people who use state machines seriously don't do it the way you show. In the real world the plain way works best.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    17. Re:Coding style by Anonymous Coward · · Score: 0

      5) Write if conditions as "if(null == x)" rather than "if(x == null)". If you ever end up writing in C, you'll find out all too quickly that "if(x = null)" can be valid, but incorrect code. Placing the constant first will cause an incorrect assignment instead of comparison to throw a compiler error in any language.

      That would be in the "purposely reducing readability to avoid beginner errors". Clearly shows you as a beginner.

    18. Re:Coding style by Anonymous Coward · · Score: 0

      If a function has grown beyond a hundred lines of (real) code, it is almost certainly too large. If it has more than 4 levels of nesting, it is too large

      I guess you've never had the experience of breaking a large function down into two functions which communicate using 1,024 parameters.

    19. Re:Coding style by Anonymous Coward · · Score: 0

      If you are coding state machines with switch statements, then you don't know what you're doing.

      If you're making sweeping generalizations like this, you don't understand programming.

    20. Re:Coding style by Mattintosh · · Score: 1

      There is exactly one place where a single letter variable is acceptable.

      for(x=0;x

      And that's only for languages besides C and others like it that require you to declare that at the top of the block.

    21. Re:Coding style by frank_adrian314159 · · Score: 1
      The state transitions, transition functions and accepting states should be stored in tables (2-dimensional arrays) and the entire state machine is then coded in about a dozen lines...

      Or, you can write it in a language having a decent macroing system like Lisp and have a fast-running state machine generated for you, obviating the need for the programmer to manually map state numbers to action routines, etc. (and in good Lisp environments, you can even deliver the state machine code with debugger hooks that let you debug at the state machine level, never seeing the underlying code - of course, with the option of drilling down if you need to see the code at that level).

      --
      That is all.
    22. Re:Coding style by Anonymous Coward · · Score: 0

      harder to figure out? You're stoned!

      A data-driven representation of the state transitions combined with function pointers is far easier to understand than the godawful biga** switch statement. In my experience, I've maintained code using both methods and the data-driven method is far easier to maintain because the transitions are spelled out explicitly. I think some people don't like the data-driven method for a combination of reasons:

      o either people think function calls and function pointers are too slow (stupid)
      o many experienced people don't understand function pointers (stupid++) or think they make understanding the code difficult (reasonable in one way since they add indirection but unreasonable in another since they invariably improve consistency)

      BTW, the most elegant and maintainable state machine I've ever seen used c++ template meta-programming. Remarkably, gcc3 generated damn efficient code for it as well.

    23. Re:Coding style by Anonymous Coward · · Score: 0

      If you are coding state machines with switch statements, then you don't know what you're doing.

      Then the people who wrote the TCP state machine for BSD didn't know what they were doing.

  15. Re:Cookie-cutter book? by Anonymous Coward · · Score: 1, Insightful

    Actually, the parent is neither off-topic nor flamebait. This book can be very good (and I think I'll buy it if I can) but this reviews lacked a comparison with another "Bibles" such as "Code Complete" (a Microsoft Press book!). Code Complete was to me the book that gave me another level of programming, exactly like this "Open Source Code Complete". The problem is really with the word "open source embedded in the title...

  16. QA by Anonymous Coward · · Score: 2, Informative

    I'm doing QA on all work delivered by contractors that is on our standing offer list (yes, I work for the government... and yes, there are a few good people here).

    First thing you notice is that they hardly ever read the statement of work before they start coding. The whole application becomes a hack.

    Second thing is the structure of the code. Indentation? What a heck is that? Some try doing indentation by just using the tab key. That looks great for someone who has the tab size set to six... after 13 levels (extreme, but I've seen it), you can't see the freaking code. My advice to someone who's in charge for a codebase... Standardize indentation, as well as the tab setting.

    Third thing you notice is that they've changed the structure of the database that you provided to them. Oh, great!.. There goes the lean structure, just so that the coder could perform a quick hack by duplicating the data throughout all the tables.

    If you want code to be maintainable, do QA, and do it good!

    1. Re:QA by Anonymous Coward · · Score: 0

      i've found CMMI, or at least some mature methodology is absolutely required for huge projects to not become more then hacks.

      heck, it's even good for medium sized projects.

      small projects need not apply (though some of the ideas are definitely applicable).

    2. Re:QA by Anonymous Coward · · Score: 1, Insightful

      If you encounter more than about 4 levels of indentation then the width of a tab is the least of your worries.

    3. Re:QA by PugMajere · · Score: 1

      You should only indent with the tab key - that lets other people change the look to fit their whims.

      Now, 13 levels of nesting with 8 character tabs? That's rough. But the fact that you can't see the code should tell you something - the code is structured wrong. :)

    4. Re:QA by Anonymous Coward · · Score: 0

      I suppose that it's not possible that your SOWs are confused and muddily written? Considering your /. post with dangling modifiers and adjectives posing as adverbs and such, you don't have a solid grasp on syntax and semantics.

      Not to mention your definition of "code structure" as indentation and tab settings. Geez, run it through a fucking prettyprinter (you're an AC, don't say "freaking") for the tab settings you want. Structure is about architecture, not the paint on the drywall.

  17. language bias detected by anomalous+cohort · · Score: 3, Insightful
    In Chapter 2, a number of concepts basic to any programming language are covered, including the basic flow-control units common to many languages. The book focuses on C, with additional coverage given using C++, Java, and a few other things thrown in for good measure. As such, these chapters -- in fact the whole book -- focuses on concepts common to these languages but absent in some other languages, like Scheme or LISP.

    Hmmm. What concepts, particularly what basic flow control concepts, are present in C, C++, or Java yet absent in Scheme or Lisp?

    1. Re:language bias detected by KenSeymour · · Score: 4, Funny

      I would say the concept of getting paid for programming.

      --
      "We can't solve problems by using the same kind of thinking we used when we created them." -- Albert Einstein
    2. Re:language bias detected by Jerf · · Score: 4, Insightful

      The author is probably referring to the way Scheme and LISP are "missing" static type checking, in much the same way I am "missing" a hole in the side of my head.

      The claim that something is missing would be more compelling if they weren't "missing" it on purpose, and the trend wasn't swinging in the dynamically-typed (or, as I think of it, "value typed" as opposed to "variable typed"; whatever you do it's wrong to call it "weakly typed") language's favor anyhow.

      (Variable-based-typing's only hope is that the type-inferencing languages penetrate into the mainstream before the recoginition that variable-based-typing isn't free does, that being the fundamental misconception keeping it afloat. (Once you ack. the obvious point that it is not free, and is in fact quite expensive, both in actual effort and in massively underestimated opportunity costs, you are suddenly able to consider it in terms of costs and benefits, and the cost/benefit analysis generally does not work out in its favor when done dispassionately, though there are exceptions.))

    3. Re:language bias detected by rubycodez · · Score: 1

      all the stinky ones, like goto and external iterators 8D

    4. Re:language bias detected by d1v1d3byz3r0 · · Score: 2, Insightful

      If they don't exist, you can always build them in. That's the beauty of Lisp.

      Off the top of my head, I can't think of any major flow control mechanisms missing from native Lisp. If they exist, I'm pretty sure there was a good reason that they don't exist in Lisp.

    5. Re:language bias detected by brpr · · Score: 1

      Common Lisp has goto. Scheme has call/cc which can be used to implement gotos.

      --
      Freedom is not increased by mere diminuation of government. Anarchy is freedom for the strong and slavery for the weak.
    6. Re:language bias detected by BoRictor · · Score: 1

      hahaha i laughed at this one! :p

    7. Re:language bias detected by r00t · · Score: 1

      This is why LISP and Scheme programs crash with
      runtime errors that would be caught by the compiler
      of a strongly-typed language.

      You can have your run-time crashes. No thanks!

    8. Re:language bias detected by benja · · Score: 2, Interesting

      Umh -- your comment would make sense if the author had indeed written missing, rather than the neutral absent. I can't detect the bias in saying that C includes concepts LISP doesn't and vice versa.

    9. Re:language bias detected by Anonymous Coward · · Score: 0

      If they don't exist, you can always build them, that's the beauty of x86

    10. Re:language bias detected by Jerf · · Score: 2, Informative

      I've been working in Perl and Python for years now, with large products running on very big scales, tens of thousands of users running mission-critical stuff, day in, day out, that sort of thing.

      I will let you know when this is an actual problem, rather than stories to scare the kiddies with. So far, while I can clearly see the costs (which, if you have never left the 'safety' of variable-based typing languages behind, you can't), I'm yet to see the benefits on any but the most extreme jobs.

      I've picked up quite a list of people I've made this promise to, but I don't bother actually keeping track, because it isn't going to happen. They keep promising doom, and I keep coding four or five times faster than they do, and that's just the linear speed-up, to say nothing of the improved re-factoring I get and the general benefits of flexibility. Fair trade, I suppose.

    11. Re:language bias detected by Anonymous Coward · · Score: 0

      Drawing a blank? I can think of several concepts that are common in C++ and Java (and many other languages) but that are absent in Lisp.

      For example, fixnums ("ints that overflow"). Or "numbers that start with '0' are in a different base". If you want something higher-level: lack of closures in the language (i.e., how to build closures out of pointers, classes, duct tape, or whatever else is handy). Note he never said "features" or even implied that these concepts were good! :-)

    12. Re:language bias detected by Anonymous Coward · · Score: 0

      But Lisp has goto. You can even use it with line numbers. Actual Common Lisp code (try it):

      (prog ()
      10 (print "i love basic!")
      20 (go 10))

      Put that in your pipe and smoke it, McCarthy.

    13. Re:language bias detected by Anonymous Coward · · Score: 0

      Oh get over it. There is no meaningful trend towards dynamic type checking. Dynamic type checking causes bugs. In terms of code verification, the moment you use dynamic type checking you are taking a step back 30 years in time.

      It's nonsense to say static type checking is kept afloat by a fundemental misconception. Static type checking is kept afloat by the fact it detects bugs at compile time. This is not free, no, but it has benefits in return for that cost. There is no misconception, you just don't understand how other people view the balance.

    14. Re:language bias detected by Anonymous Coward · · Score: 0

      As someone who uses one of these "large prodcuts running on very big scales" that was written by some idiot in Python, I can tell you that it crashes all the time with run-time type problems, and once we realised that Python programmers were "four or five times faster" because they were making five times more mistakes it went on my banned list.

      If you want a more direct example that anyone can look at, take Red Hat's python admin code. Yes, it's safe against black hats finding buffer overflows, but it can't handle anything but the simplest situations without encountering run-time errors and crashing, often while writing config files = critical system failure. Users eventually got tired of filing bugs about this, which is why there are so few open now, it was obvious that the author of e.g. redhat-config-date desperately needs TYPE CHECKING enforced earlier than "when it runs on a customer's computer" and no amount of bug-filing was going to teach him or her that.

    15. Re:language bias detected by rubycodez · · Score: 1

      heh, wrote LISP for $$$ in the 80's and never once used prog & progn and never used or heard of goto. were they there to make BASIC programmers feel at home?

    16. Re:language bias detected by brpr · · Score: 1

      Goto in common lisp isn't actually called goto (can't remember what it is called), but it's definitely in there -- how else would you write the macros for all the common control structures? The primitives of Common Lisp are actually very imperative in their flavour.

      --
      Freedom is not increased by mere diminuation of government. Anarchy is freedom for the strong and slavery for the weak.
    17. Re:language bias detected by Jerf · · Score: 1

      Idiots write code in any language.

      Your cited problem wasn't type checking. I've seen plenty of equal garbage in type-checked languages, therefore strong typing wasn't the solution, QED. Your problem was lack of unit testing and other good testing techniques.

      You see a problem, but you've already decided on the solution. Dogma, dogma, dogma, threat, threat, threat, blah, blah, blah. My code doesn't crash, and I don't give a shit how somebody else managed to shoot themselves in the foot or your inaccurate diagnosis about "why". You keep at it, one less developer I'm competing against.

  18. Amen by MHobbit · · Score: 2, Interesting

    Amen.

    I've been coding for a couple of years now, and always have been using comments. Mind you, I only started using a lot of them when I started with PHP code and other open-source, interpreted languages.

    Right now, I'm still a better C coder than PHP, and you can tell by what approach I take to solve various things.

    --
    Debugging? Klingons do not debug. Bugs are good for building character in the user.
  19. "Code is its own documentation, right?" by guitaristx · · Score: 5, Funny

    From someone who's had a hand in dealing with function pointers named StupidSuckingGlobalCallbackFunction, trust me, the subject of this post is very, very, very wrong.

    --
    I pity the foo that isn't metasyntactic
    1. Re:"Code is its own documentation, right?" by kraut · · Score: 1

      Just imagine if it had been called ssgcf ;)

      --
      no taxation without representation!
    2. Re:"Code is its own documentation, right?" by jayed_99 · · Score: 0, Offtopic

      You've maintained some of my code, I see.

    3. Re:"Code is its own documentation, right?" by Anonymous Coward · · Score: 0

      Indeed.

      void set_gayass_adjustment_for_lame_ass_popup_control_c oded_by_the_antichrist(struct dialog_data * dialog, short item_index, boolean adjust);

      Need I say more?

    4. Re:"Code is its own documentation, right?" by phek · · Score: 1

      i would rather have to maintain some code with variables like StupidSuckingGlobalCallbackFunction rather than when the variables a primarily named as whoopwhoop, beepbeep, barkbark, fluffyfishy, etc.

    5. Re:"Code is its own documentation, right?" by Brandybuck · · Score: 1

      I once wrote a function called "stoopid_backdoor". I was told during my code review that I had to rename it. So I renamed it to "bypass_security". That was acceptable.

      That was two years ago. Apparently I didn't open that door wide enough and I now have a must fix urgent priority bug. It seems that the time it takes for all of our support people to type in passwords for all of our systems out there comes to three *million* dollars a year. So tomorrow I'm removing the requirement for passwords to log in as root.

      I'm going to rename the function back the way it was...

      --
      Don't blame me, I didn't vote for either of them!
  20. Learning from decades-old code by shoppa · · Score: 4, Informative
    I've had many opportunities to work with code that has evolved over several decades. There are two common patterns:
    1. Project was originally a quick hack. It lives well past its prime, gets modded extensively to handle changes going on in the real world (new devices, competition, etc.). Abstractions are added where necessary. Some hacky ugliness lives at fringes, but after umpteen releases and way too much backwards compatibility customers are still buying it.
    2. Project was a grandiose dream by an analyst. Before any functionality exists, everything is abstracted to the max. 10-inch thick binders full of API's are published before the product actually does anything. The abstractions usually turn out to be wrong, and after many years (and little functionality) either the abstractions get twisted around at great expense to reach functionality, or the project dies in heaving paroxysms.
    . Reading the experienced coder's comments is always good. They know the history and want to pass on the lessons learned to whoever will look.
    1. Re:Learning from decades-old code by 14erCleaner · · Score: 1
      Reading the experienced coder's comments is always good. They know the history and want to pass on the lessons learned to whoever will look.

      I have to disagree with this. Just because a programmer is experienced, that doesn't mean he can write good code, or comments. I've worked with (and had to clean up after) many experienced programmers who were incapable of writing clear code, or clear comments explaining what their code was trying to do.

      Writing takes talent, not just mileage.

      --
      Have you read my blog lately?
    2. Re:Learning from decades-old code by Sweetshark · · Score: 1

      Actually you need a old type 1 Project to do the analysis for a good rewritten type 2 project dropping most unneeded backwards compability.

      (Example: type 1 sendmail, type 2 postfix)

    3. Re:Learning from decades-old code by excesspwr · · Score: 1

      I worked with a developer once who had many many years in the field. His code was the worst ever. No comments. Single character variable names. No comprehesion of OOP principles.

      I once saw a shell script he wrote. He aliased grep to gr. He only used grep once in the entire script. I have no idea what he was trying to accomplish with that.

    4. Re:Learning from decades-old code by 14erCleaner · · Score: 1
      He aliased grep to gr.

      Amazing! The Unix command wasn't cryptic enough for him?

      --
      Have you read my blog lately?
    5. Re:Learning from decades-old code by drxray · · Score: 1

      What's it like working in Redmond?

      --
      Slashdot - Mutual Assured Discussion
    6. Re:Learning from decades-old code by PugMajere · · Score: 1

      A friend of mine once wrote a script that used grep.

      His script was called "grep".

      "." was in the path. :)

  21. Code format by Anonymous Coward · · Score: 0

    All I gotta say is that if you use {
    this {
    style {
    of indention
    }
    }
    }

    You are a newbie.

    Use standard
    {
    ANSI formatting
    {
    you kiddies
    }
    }

    1. Re:Code format by Cthefuture · · Score: 3, Insightful

      I have to say that I agree with you to a certain degree.

      I'll go one more step though. It's about white space. You can almost always recognize a good programmer by how clean the code looks because of proper use of white space. If the code is all crammed together and cluttered looking then you know that programmer sucks. White space does not make your code slower guys!

      Note that I said this is a way to recognize a good programmers. Often experience plays a role but I see a ton of fairly experienced programmers that write ass crappy code.

      I see a lot of people saying comments are also a sign but I have to disagree. Well written code is easy to read and figure out. I would much rather have nicely written code than comments. (Note that it is my job to fix other people's code so I have a lot of experience with this)

      --
      The ratio of people to cake is too big
    2. Re:Code format by sqlrob · · Score: 1

      Right Braces = Good in inline in headers
      Left Braces = seperate files

    3. Re:Code format by Anonymous Coward · · Score: 0

      There is a rat in separate.

    4. Re:Code format by kclittle · · Score: 2, Insightful

      This style
      {
      is better by far
      {
      because the braces 'belong' to
      the following block of code
      }
      not the
      {
      preceeding guard statement
      }
      }

      Sincerely,
      An OFP (Old Fart Progammer)

      --
      Generally, bash is superior to python in those environments where python is not installed.
    5. Re:Code format by Decaff · · Score: 4, Insightful

      All I gotta say is that if you use {
      this {
      style {
      of indention
      }
      }
      }

      You are a newbie.


      No way! I have been coding for 30 years...

      It makes more sense to code

      if (test) {
      statement1
      } else {
      statement2
      }

      because the eye can immediately see from the 'if' and 'else' statements alone that a block of conditional code follows. Having the braces on the same line also marks out the lines as special: flow control code. I find that

      if (test)
      {
      statement1
      }
      else
      {
      statement2
      }

      simply adds pointless extra lines to code, with no gain in readability.

    6. Re:Code format by Anonymous Coward · · Score: 0

      I agree.
      I think back in the fortran days I did something like

      if (foo) do
      statements
      enddo

      it was perfectly natural to change do/enddo to braces.

      if (foo) {
      statements
      }

      Any other newbies remember this from fortran or am I just high again ?

    7. Re:Code format by Decaff · · Score: 1

      ok, maybe not a newb, but your code still looks like crap.

      <jar-jar>How Woood!</jar-jar>

      I have explained clearly and logically why the code I showed is easier to read....

      if(condition)
      {

      in Java/C++/C#

      Is as dumb as

      IF condition
      THEN

      in more verbose languages

      You don't split up IF .. THEN, so you should not split up if(..){

    8. Re:Code format by Decaff · · Score: 1

      Any other newbies remember this from fortran or am I just high again ?

      I remember :). Sheesh, I even remember Algol!

    9. Re:Code format by Cthefuture · · Score: 1

      I have used this style extensively in the past and I agree.

      I don't tend to use that format though because it's so rare that people crap their pants when they see it and start complaining. It takes a little getting used to but once you get used to it, it works a lot better.

      These days I use whatever style the project is written in but I much prefer your style or ANSI style. I usually just use ANSI style so that other programmers will at least accept it.

      --
      The ratio of people to cake is too big
    10. Re:Code format by An+Onerous+Coward · · Score: 1

      Out of curiosity, when you sit down to a fresh, steaming pile of someone else's code, do you start by running the whole thing through a pretty printer? I'm half way through a class on compilers, and it looks fairly straightforward to write one. I've always had a hunch that it would be a good way to enforce certain coding standards for a project.

      So what's your experience been?

      --

      You want the truthiness? You can't handle the truthiness!

    11. Re:Code format by Cthefuture · · Score: 1

      Not often, but sometimes. I try to keep the same style if possible. Engineers seem especially bad about writing cryptic, compressed, broken code.

      Artistic Style (astyle) is what I use to reformat code.

      --
      The ratio of people to cake is too big
    12. Re:Code format by Merdalors · · Score: 0, Flamebait

      Absolutely! Never end a line with the opening brace!
      I fail to see the point of this:

      if(condition) {
      expression1;
      expression2;
      } // you gotta work hard to match the opening brace

      --
      Slashdot entertains. Windows pays the mortgage.
    13. Re:Code format by mad.frog · · Score: 1

      Wish I had mod points to mod you up.

      As a rule, I avoid modding up Anon Cowards, but in this case, I'll make an exception.

    14. Re:Code format by Anonymous Coward · · Score: 0

      you are right
      but a language
      that forces you to do this
      reveals its internal structure
      is easier to read
      and taps you on the shoulder when you take it too far

      so
      have your cake
      and eat it too

    15. Re:Code format by Anonymous Coward · · Score: 0

      Easier for you to read, not for others. Amazing that this is a personal preference!

    16. Re:Code format by Ponce17 · · Score: 1

      I cannot agree more. In fact, I have become somewhat of a code-nazi when it comes to this. Well spaced code allows it to be easier to read, like words and paragraphs.

    17. Re:Code format by Anonymous Coward · · Score: 0

      Actually,

      if(condition)
      {
      // code
      }

      Is a lot easier on my eyes than

      if(condition) {
      // code
      }

      The braces being by themselves on a line gives a visual break that lends definition to the code block.

      The 'useless and unnecessary lines' is a bogus justification. if that were the only consideration we'd only ever see:

      if (condition) { foo(); bar(); baz(); if(anothercondition) { bey(); } } else { dothefandango(); }

      on one line.

      Also ->
      You don't split up IF .. THEN, so you should not split up if(..){

      This is a bogus argument as well. The curly braces define a block, the block is not part of the if in the way THEN is in languages that have IF ... THEN

      e.g., a block is a block, and an if can work on either a statement or a block. You're pulling a rule out of thin air, just randomly deciding that the opening brace, which defines the start of the block, AND IS THUS PART OF THE BLOCK, somehow belongs to the if.

    18. Re:Code format by Anonymous Coward · · Score: 1, Interesting

      Funny, the argument works better the other way:

      No way! I have been coding for 30 years...

      It makes more sense to code

      if (test)
      {
      statement1
      }
      else
      {
      statement2
      }

      because the eye can immediately see from the BRACES alone that a block of conditional code follows. Having the braces vertically aligned also marks the contained lines as special: flow control code. I find that

      if (test) {
      statement1
      } else {
      statement2
      }

      renders most control-flow logic completely unreadable since there's no white space to set off conditionals from other forms of code. White-space is cheap, if you're still using a 25-line green-phosphor terminal to edit code I highly suggest you look into retirement; let those crazy youngsters with 1600x1200 color bitmapped displays write the code (with all due respect).

    19. Re:Code format by Anonymous Coward · · Score: 0

      These days I use whatever style the project is written

      And that, to me, is the mark of a pro.

      There's nothing I can't stand more than inconsistent style within a code tree.

    20. Re:Code format by Anonymous Coward · · Score: 0

      I immediately hit a key combination that I have bound to kick off emacs' indenter, with settings that enforce our company standard coding conventions.

      Which about four of our programmers actually follow.

      *sigh*

    21. Re:Code format by hyperstation · · Score: 1

      i agree. also, if i have a sql statement:

      $some_q = " SELECT *
      FROM x.table
      JOIN y.table USING(a)
      WHERE b = 0";

      so that the statements (most much larger than this) are more readable. tabs only please, set to 4 spaces.

    22. Re:Code format by Chemisor · · Score: 1
      > The braces being by themselves on a line gives a visual break

      That's because you look at the braces. I look at the indentation to provide visual breaks. A brace on its own line is confusing when you are used to the cuddled kind because it creates an extra block. My brain automatically sees the if as a one-liner followed by an unrelated block. In other words, I would interpret it thus:
      if (condition);
      {
      cout << "Do something else" << endl;
      }
    23. Re:Code format by kz45 · · Score: 1


      You are a newbie.

      I would say just the opposite. The people I know that are just being taught how to program use the ansi style format. The veterans who have been coding for awhile use the other non-standard format (for readability..I prefer the non-Ansi format of commenting).

    24. Re:Code format by Anonymous Coward · · Score: 0

      arrrg.
      you are a newb.
      You've obviously not only been coding for 30 years.
      But coding THE SAME WAY for 30 years.
      While linux & K & R may all have made some great stuff, all the code I ever dealt with written in this style is crap. Yes, it has its advantages, and you should use it when those advantages make it the right choice. Now, for a look at blindly applying your style of coding, check out the ipdrlibs at www.ipdrlibs.org. Written by your friends at Infosys.
      Same goes for people who think it's cool to prematurely optimize.
      You write string processing/parsing code in straight C because "it'll make it fast", when C++/STL has had a standard string type for *years*, and to top it off you:
      Use idioms like this:

      while( *ptr++ != NULL ) count++;

      Because you think it's cool and fast.
      And then do something like this:

      for( int i = 0; i < strlen(file); ++i )

      Where file is a character array of the contents of a 13MB file (or larger).
      But it'll run fast coz you did it in C right?
      And you did it in the K&R style right?
      Then run Doxygen, because you want to seem like you've learned something in the past 30 years, but not bother to write comments using doxygen tags. And think you did a good job....
      jfc.
      The problem with people who use the OTB style that I've seen is that they are usually people who mindlessly ape others, and never grow and learn. Yes, there are very *OBVIOUS* exceptions. But they do what they do for very good reasons. Like them, you could be different. But since you blindly state OTB is *always* better, I'm guessing no. But I'll the code I've had to deal with that had OTB was crap. But no, I've never hacked at the kernel or Apache, which are probably excellent examples of K&R people who actually *think* *why* they do things....
      oh and btw, OTB style pisses me off because it makes it hard to match up braces for nested control statements (when your fixing somebody else's crap). Especially when the nesting is more then a few screens... So there is a gain, it's not pointlessly adding lines...

    25. Re:Code format by kclittle · · Score: 1
      I work on such large projects, with code from who knows how many groups and hands, that hoping to have the entire tree in one style is futile.

      Within a logical section of the code (a 'subsystem', for example) I do expect consistency, and I will adhere to the style found therein. But if given a choice (I'm creating the subsytem), I'll use the above. It's just vastly cleaner to the eye.

      --
      Generally, bash is superior to python in those environments where python is not installed.
    26. Re:Code format by Kwil · · Score: 2, Interesting
      I've only seen this done a few places, but I find the format
      if(test)
      { statement1
      }
      else
      { statement2
      }
      works very well.

      Especially when you get into nested..
      if(test1)
      { statement1
      statement2
      statement3
      if (test2)
      { statement 4
      statement 5
      }
      statement6
      }
      Bringing the brace down, but not adding the extra line conserves the space lost with the latter method and keeps the connection between the test and the block, but at the same time makes visual "chunking" of the code blocks that much easier by having the open and closing braces in the same column.
      --

      That Jesus Christ guy is getting some terrible lag... it took him 3 days to respawn! -NJ CoolBreeze

    27. Re:Code format by Anonymous Coward · · Score: 0

      I'll go one more step though. It's about white space. You can almost always recognize a good programmer by how clean the code looks because of proper use of white space. If the code is all crammed together and cluttered looking then you know that programmer sucks.

      I use the IDE's code formatter if available, does that automatically make me a better programmer because the IDE pretties up my code?

      But I agree.. I see other coders with cluttered code, and they don't even use the code formatter that would solve this problem!

      But don't get me started on the sucky coders I have to work with.

    28. Re:Code format by Anonymous Coward · · Score: 1, Interesting
      The problem is that it's not consistent. Don't forget that a single statement (without brackets) is also a valid C conditional. It extends nicely to the bracketed form. For example:
      if (condition)
      function();

      if (condition)
      {
      function();
      }
      Your dangling use of { } brackets tends to hide them and any version control system will mark the conditional line as having changed simply by adding the brackets. Eg:
      if (condition)
      function();

      if (condition) {
      function();
      }
      The distinction between bracketed and unbracketed form is far less clear. Since brackets are important to code flow, I believe they should be treated with importance and given their own lines. And you shouldn't care if this pads your source file out a bit (given that the world has code folding editors, high resolution screens - and almost nobody uses hard copy anymore).

      Because your style of brackets merges the bracketed code and the conditional into one blob, you also can't quickly comment out the conditional (leaving the code). For example:
      //if (condition)
      {
      function();
      }
      ..vs having to mess with the end bracket as well:
      //if (condition) {
      function();
      //}
      Anyway, my 2 cents.
    29. Re:Code format by Bill+Dog · · Score: 1
      > The braces being by themselves on a line gives a visual break

      That's because you look at the braces. I look at the indentation to provide visual breaks.

      That's not smart. Indentation can (and where I work, quite often does) get messed up. But the braces never lie. (Similar to comments vs. code.)

      Also, if your brain tends to interpret that bracing style that way, how often do you come across a stand-alone, unconditional, embedded pair of braces within say a function body?

      --
      Attention zealots and haters: 00100 00100
    30. Re:Code format by Bill+Dog · · Score: 1
      OTB style pisses me off because it makes it hard to match up braces for nested control statements (when your fixing somebody else's crap). Especially when the nesting is more then a few screens

      Exactly. I've had to wrangle with multi-page behemoths at my first job, and it's a lot easier to find the brace missing his buddy by using the IDE's "jump to matching brace" hotkey while watching the column # display in the status bar. With the style of matching braces not in the same column, you can't use this technique to help you.

      --
      Attention zealots and haters: 00100 00100
    31. Re:Code format by Decaff · · Score: 1

      arrrg.
      you are a newb.
      You've obviously not only been coding for 30 years.
      But coding THE SAME WAY for 30 years.


      Amazing! Your ability to determine the details of long software engineering career simply based on the position of brackets in code...

      You write string processing/parsing code in straight C because "it'll make it fast", when C++/STL has had a standard string type for *years*, and to top it off you:
      Use idioms like this:

      while( *ptr++ != NULL ) count++;


      I can't believe I am reading this arrogant and offensive rubbish.

      OTB style pisses me off because it makes it hard to match up braces for nested control statements (when your fixing somebody else's crap).

      There is something called INDENTATION.

      You realise all this is irrelevant anyway, as almost all good IDEs will allow the formatting to be changed anyway you like?

    32. Re:Code format by Decaff · · Score: 1

      if (condition)
      function();


      I tend to do

      if (condition) {
      function();
      }

      always, even for single lines, as this is consistent and I always read if () { as 'if..then'

    33. Re:Code format by Decaff · · Score: 1

      Easier for you to read, not for others. Amazing that this is a personal preference!

      No. Many share my view, including Linus himself.

    34. Re:Code format by SLOGEN · · Score: 1

      I can't even post your proposed equivalent of

      class F {
      int X {
      get {
      if ( disposed )
      throw new DisposedException();
      else
      return x;
      }
      }
      }

      I keep getting:

      Your comment violated the "postercomment" compression filter. Try less whitespace and/or less repetition. Comment aborted.

      While whitespace, when used properly, is good for readability, the "{}"'s on seperate lines reduces readability by eating screen realestate with empty lines.

      --
      SLOGEN [ http://ungdomshus.nu : Sebastian cover music]
    35. Re:Code format by Anonymous Coward · · Score: 0

      That is exactly the problem with Python. That plus its half-assed regex implementation (if I wanted it to be hard I would use C or C++!) makes for a crap-ass language.

    36. Re:Code format by Chemisor · · Score: 1

      > Indentation can (and where I work, quite often does) get messed up.

      How can it possibly get messed up? Nearly every editor has autoindenting mode, so if you want to mess up indentation you really have to try hard. Then, if it gets messed up, you should fix it. It's just like the comments vs. code: comments don't make the code good, they just make bad code better.

      > how often do you come across a stand-alone,
      > unconditional, embedded pair of braces

      Not often, but it is sometimes useful to create an explicit scope as a precursor to pulling out a function. Its rarity is what makes standalone braces so jarring to my eye. Thankfully, I have indent, which takes care of that problem very nicely.

    37. Re:Code format by Anonymous Coward · · Score: 0

      Amazing! Your ability to determine the details of long software engineering career simply based on the position of brackets in code...

      hmm... no more what got me was your making it a hard and fast rule

      I can't believe I am reading this arrogant and offensive rubbish.

      I can't believe it either. I was just venting after a long night of coding. haha.
      But I noticed you took that out of context there... The point was made in the next statement, the code I was working on was just using idioms, and not thinking about what they where doing.

      You realise all this is irrelevant anyway, as almost all good IDEs will allow the formatting to be changed anyway you like?

      Not all of us have the luxury of working in an environment with a good IDE :(

      It's all good, though. I'll grant you probably are right. I haven't really had a long career or anything. Just needed to vent. Can't believe you took it that seriously though.

    38. Re:Code format by Bill+Dog · · Score: 1
      Indentation can (and where I work, quite often does) get messed up.

      How can it possibly get messed up?

      I imagine it's due to people having their editors set to different-sized tabs, or differing values of the "use real tabs" vs. "insert spaces for tabs" toggle. Someone can go ahead and "fix" the alignment problem so it looks right to him, but in someone else's editor it'll just look all messed up (and that person might end up "fixing it back").

      Theoretically this could be cured if we had a standard (and everyone stuck to it!), as in theory comments would be great if no one ever let them get out of sync with the code, but the point is theory doesn't always pan out, and when a less error-prone, actually fool-proof, method is available (looking at the braces instead of the indentation/looking at the (self-documenting) code instead of the comments), that's much better to use.

      We all strive for having comments that are synchronized with the code, and indentation that's not misleading, but ultimately they cannot be relied upon.

      --
      Attention zealots and haters: 00100 00100
    39. Re:Code format by Deven · · Score: 1
      The rule I use is simple. If a nested statement (the body of an if/else, while, for, etc.) is not on the same line as the control structure, then always use braces even if they're not logically necessary.

      Thus, this is acceptable:
      if (condition) function();
      or this:
      if (condition) {
      function();
      }
      but never this:
      if (condition)
      function();
      There was a time when I didn't worry about this issue, but one day I spent hours debugging a problem in someone else's code (a Unix Appletalk implementation) that broke because a line of code had been added to the start of a loop body which didn't contain braces. Of course, this pushed the original loop body out of the loop! But because both were indented as if they were in the loop, and logically belonged there, it was a very subtle and difficult bug to track down.

      Ever since that experience, I automatically use braces if the statement spans multiple lines. I don't ever want to have to debug something so stupid again.
      --

      Deven

      "Simple things should be simple, and complex things should be possible." - Alan Kay

    40. Re:Code format by Deven · · Score: 1
      I've only seen this done a few places, but I find the format
      if(test)
      { statement1
      }
      else
      { statement2
      }
      works very well.
      Never use this style!

      No offense, but this is the most retarded brace style I've ever seen. While you may think it looks good on paper, it's much harder to maintain. I've had the misfortune to be stuck maintaining such code, and invariably I find myself needing to insert a new statement at the start of a block, or delete the first statement in the block, or otherwise rearrange the statements. But you still need to keep the brace at the start of the block (and indent properly), so it becomes a real pain in the ass to modify the code now that line-oriented editing operations won't work.

      It's just not worth it. The K&R brace style saves just as much room on paper or screen and remains maintainable. Moreover, proper indentation makes it quite easy to see where the blocks are -- there's no reason to highlight the braces by giving them a line of their own unnecessarily. (But Python takes it too far by eliminating the braces entirely.)
      --

      Deven

      "Simple things should be simple, and complex things should be possible." - Alan Kay

    41. Re:Code format by Decaff · · Score: 1

      Not all of us have the luxury of working in an environment with a good IDE :(

      Emacs will do it... I guess!

      If not, then a few hundred lines of PERL :)

      It's all good, though. I'll grant you probably are right. I haven't really had a long career or anything. Just needed to vent. Can't believe you took it that seriously though.

      Well, it was way harsh! Perhaps I should not have taken it so seriously. Sorry.

    42. Re:Code format by Deven · · Score: 1
      Braces are important to code flow, but they don't require a line by themselves any more than semicolons do. The fact that you're inside a conditional (or loop) is important, and made quite clear by proper indentation. The braces delimit the block, but they're not actually interesting in and of themselves, so they don't deserve to take up all that extra space.

      By your argument, we might as well write code like this:
      if
      (
      condition
      )
      {
      function()
      ;
      }
      The interesting part of the code is the part that implements the program logic. The braces are syntax, no more. They're not interesting and shouldn't be highlighted.

      Also, if you want to comment out the conditional in K&R style, you don't have to comment out the ending brace; you can just add an opening one:
      {//if (condition) {
      function();
      }
      That's not a compelling reason to put the brace on a line by itself.
      --

      Deven

      "Simple things should be simple, and complex things should be possible." - Alan Kay

    43. Re:Code format by Chemisor · · Score: 1

      > it's due to people having their editors set to different-sized tabs

      Now this is exactly the attitude I don't understand. Every project must have a standard coding style. It's the job of whoever is in charge to provide one and to ensure it is followed by everyone touching the code. It is done during code reviews (which should also be mandatory, preferably for everyone, but at the very least for the new people), when conformance to the coding style must be a prerequisite to a checkin.

      Everyone here seems to think that there is nothing to be done about the situation; that each team member should be allowed to do whatever he damn pleases, with no oversight. How are any of these people still in business?

      If I were your project leader, I'd tell you exactly, in a comprehensive written policy, how you should format your code, whether you should use exceptions or returns, which documetation parser to target, and what sort of comments to write. Standards must exist, and they must be enforced. There is no room for opinions and preferences after the standard has been decided upon, because a standard, even a bad one, is better than a hodgepodge mixture of styles that results otherwise. You follow the standard or you're fired. Period.

      This goes for open source projects as well. Whenever I'm running one, you don't contribute unless it's in the proper style. I might rewrite your patch if I think it's worth the effort, but usually the answer would be "no". Specify a standard and make sure all patches are reviewed by you or someone you trust for compliance with that standard.

      Yes, I am angry; all this multiculturalism bullshit really pisses me off. Programming is not a "politically correct" occupation where you have to take into consideration people's feelings. If I'm on your team, I'll follow your standard, even if I dislike it, and make everyone else do the same. The code is either good or it isn't. If it isn't, you fix it, or get off my team.

    44. Re:Code format by Bill+Dog · · Score: 1
      Braces are important to code flow, but they don't require a line by themselves any more than semicolons do.

      Semi-colons do when the body of a loop is empty:

      /* skip to the next field */
      for ( char* p = pRecord; *p != ',' && *p != '\0'; p++ )
      ; /* no body */

      The fact that you're inside a conditional (or loop) is important, and made quite clear by proper indentation.

      But you cannot always rely on proper indentation, as you admit you've experienced yourself in your immediately prior post: "But because both were indented as if they were in the loop, and logically belonged there, it was a very subtle and difficult bug to track down." The compiler looks at the braces, and so should you.

      you don't have to comment out the ending brace; you can just add an opening one

      I don't even have to do that:

      //if (condition)
      {
      function();
      }
      If you really feel that braces should not be on a line by themselves, you should take that to its logical conclusion and advocate:
      if (condition) {
      function(); }
      --
      Attention zealots and haters: 00100 00100
    45. Re:Code format by Anonymous Coward · · Score: 0

      <em>That's because you look at the braces. I look at the indentation</em>

      You presume to know me well enough to know that I look at the braces, but not the indentation? ;)

      I never said indentation wasn't important. It is. The stark blankness of the braces on a line by themselves drives the point home - it's both elements together, not a single element alone.

      For example, I would find:

      if(condition)
      {
      foo();
      }

      utterly annoying.

      <em>My brain automatically sees the if as a one-liner followed by an unrelated block.</em>

      Ok. I suppose maybe your brain sees things that way - but when, honestly, do you have an if statement followed by braces, where the if is a single statement all by itself?

      A when, maybe. But an if?

      Style preferences aside, I've seen you mention elsewhere in this thread that projects should have consistently applied standards, and that, I agree with. If I were to work on a project of yours, I would use your style - you wouldn't have to ask, nor mandate, at least in my case. And I'd expect the same were you working on a project of mine.

      There is nothing more evil than someone with so much pride, or the desire to be right, that they stuff code that doesn't match the rest of the project's style into the codebase ...

    46. Re:Code format by 1110110001 · · Score: 1

      I'm coding for maybe 10 years so I'm a newbie in your eyes. Still I find it better readable to have the braces in the same line with if and else.

      And 1600x1200 will never fit on my 12inch Powerbook. But that's the size that fits in my backpack nicely. Thus I still have only 50 lines on my screen and I don't want these 50 lines filled with lines with a single brace.

      b4n

    47. Re:Code format by Anonymous Coward · · Score: 0

      No, the { } are equivalent to
      BEGIN

      END

      IF condition THEN
      BEGIN
      Statement Block
      Statement Block
      END

      IF condition THEN
      Single Statement

      THEN is the same as using parenthesis to delimit the condition in C-style.

    48. Re:Code format by Decaff · · Score: 1

      No, the { } are equivalent to
      BEGIN

      END


      There is nothing to say what they are equivalent - we are free to interpret them in any way we choose.

    49. Re:Code format by Deven · · Score: 1
      Your empty statement example only reinforces my point. You aren't putting that semicolon on its own line because the semicolon syntax is of any particular interest. You're doing it because the empty statement is of interest. The bare semicolon just happens to be a required part of the syntax of an empty statement, and the only visible indication of the empty statement, but the semicolon itself isn't interesting per se. For non-empty statements, you don't give the terminating semicolon its own line, do you?

      As for indentation, if you have improperly indented code, it obscures the structure of the code. Braces alone don't really help visualize the code structure, it's the indentation that does it. Seeing the braces only serves as a confirmation. Try eliminating all indentation and newlines and rely on the braces alone to see where the blocks lie. Just how well does that work?

      As for your form of commenting out an "if" block being easier, I didn't deny that it was. I just disputed the claim that you need to find the closing brace to comment it out. I don't think the ability to comment out the if conditional conveniently is sufficiently important to drive the decision of what brace style to use.

      As for the "logical" conclusion of using this style:
      if (condition) {
      function(); }
      That style is just as bad as this style:
      if (condition)
      { function();
      }
      The reasons are much the same. You can't operate on statements as lines anymore. If you insert, delete or rearrange lines where the brace is merged with a line of the block, you have to repair the brace, which is a major nuisance. If you keep the opening brace at the end of the "if" line, it never needs to move, so it's not an issue.

      And I'm not advocating reserving a line for the closing brace. It's the end the "if" statement as a whole that calls for the newline after that closing brace. When "else" blocks are used, you merge the lines quite efficiently:
      if (condition1) {
      function1();
      } else if (condition2) {
      function2();
      } else if (condition3) {
      function3();
      } else {
      function4();
      }
      That's certainly more space-efficient and easier to read than this annoying style:
      if (condition1)
      {
      function1();
      }
      else
      if (condition2)
      {
      function2();
      }
      else
      if (condition3)
      {
      function3();
      }
      else
      {
      function4();
      }
      I'd rather read code using K&R's "One True Brace" style any day...
      --

      Deven

      "Simple things should be simple, and complex things should be possible." - Alan Kay

  22. comments by defile · · Score: 5, Insightful

    If the expression itself requires a comment, then it is not being expressed clearly enough. It should be rewritten.

    If the expression is clear, but does not make sense in the context, appears suboptimal, or otherwise thwarts the reader's expectations, THEN I'll comment.

    Real world project comments...

    • We're using this byte[] array wrapper because Java won't hash identical byte arrays to the same value.
    • This is in fact a bubble sort. I'd call qsort(), but it's nowhere to be found and I'm not going to implement it myself just for this. Additionally, it doesn't matter since it sorts at most 100 records, and it's called very rarely.
    • Why yes, it IS a giant waste of space to represent an 8-bit value in a 16-bit quantity. But someone thought it was a good idea to leave out unsigned.
    • Unlike everywhere else, here we're waiting for key-release instead of key-press because the operating environment has a race condition and posts them out of order! Go Sun!
  23. editor? by Anonymous Coward · · Score: 0

    What editor they use,

    You can judge how good a programmer is by what editor they use? Well, I use that method to rate authors before even reading a word of their work. And, when I'm a judge at the olympics, I just see who has the best bike and give them the best time.

    1. Re:editor? by Hhhhh · · Score: 1

      YES. You can tell because a good programmer will use the best tool for each thing. None of that stupid editor religiosity ("Visual Studio is better!" "No, Emacs!" "Vim is the way to go!"). That is plainly stupid.

    2. Re:editor? by Anonymous Coward · · Score: 0
      You can judge how good a programmer is by what editor they use

      You wouldn't believe, but there are programmers that use joe! Usually, when they are AFK, I kuickly replace their joe with a symlink to vi, hehe ;-)

    3. Re:editor? by Ponce17 · · Score: 1

      I know this is off topic, but...

      Sometimes what is construed as the 'best' tool for the particular task at hand for one, might not be for another.

      I'm particular about vim. Now, this does not mean I'm on a 'religiosity' rant, if you want to use emacs, or any other particular IDE, that's fine with me. It's just that I have used various IDEs that are more particular to the language at hand (namely, eclipse and netbeans), and have found that I'm more productive using vim.

    4. Re:editor? by condensate · · Score: 1

      You can tell a good tool from a bad only if you saw the person handling it. Some are good on vi, some on joe, some on emacs. Whatever you use, you must feel comfortable about it, I think. If one editor is cool just because it features a column-editing mode, then if you can achieve the same with just a few keystrokes in the same time, then what is the difference?. Its personal taste, really, so we can now go on discussing the best personal taste...

      --
      Black holes were created when god tried to divide by zero
  24. The art of code by achacha · · Score: 2, Insightful

    There is a lot of truth to coding style that is not necessarily related to open source. Seasoned programmers work very hard to keep naming, patterns and even formatting consistent. It makes it easier to read.

    The open source angle is that the code will be viewed by many people and thus there is a greater detail to presentation, it's a form of ego stroking and seems to work quite well.

    I do code reviews all the time and I can tell a novice developer from someone who has done it for a while, it's a hard thing to explain, it's like a difference between good and bad art. And just like with art, you can have decent artists and you can have great artists with very little in-between. Go figure :)

    1. Re:The art of code by Anonymous Coward · · Score: 0

      it's a hard thing to explain, it's like a difference between good and bad art.

      so Cmdr. Taco is basically Jackson Pollack?

    2. Re:The art of code by donmccoy · · Score: 1

      I can tell a novice developer from someone who has done it for a while, it's a hard thing to explain

      It's like trying to define the difference between pornography and art -- "I'll know it when I see it!"

      Surely we can do better than that!

      But seriously, what's a code review? :)

    3. Re:The art of code by cratermoon · · Score: 2, Insightful
      It's not that hard to quantify the differences between a novice's code and an expert's. Here are some.
      1. Novice code is longer. There will be three statements when one will suffice.
      2. Novice code has duplication. You'll see the same thing done two ever-so-slightly different ways in two different place. An expert will abstract out the common code and vary on the thing that changes.
      3. A novice will write redundant conditions and handlers where an expert will be concise. To give a Java example, in a catch clause, checking that the exception is not null (!)
      4. Novices will code for all sort of imaginative things that *might* occur in some speculative future. Expert code will contain nothing that is not pertinent to the task at hand.
    4. Re:The art of code by webhat · · Score: 1

      I'm not sure I entirely agree with 3 and 4, but generally think you're right.

      3. I have actually had an Exception be null, this was due to a race condition in the code, so the check wouldn't have been needed except for his fact.

      4. I've seen a couple of high end programs, which write error logs to disk, not checking for EFBIG or ENOSPC after writting. Or if they actually check errno they call the error log function, regardless of the value of errno, and try to write the message to disk.

      Some of the code the novice writes in 4, will be created by the experts after they run tests on the code. The novice just overcompensates for his lack of experience.

      --
      'I am become Shiva, destroyer of worlds'
    5. Re:The art of code by cratermoon · · Score: 1

      3. I just knew that someone would bring up the complications of threads. Of course you are right -- but if a novice is solely responsible for tricky multi-threaded code, there's bigger problems! 4. Checking for possible but rare error conditions is robustness, and not what I had in mind. I wish I had a good example. Suffice to say that novices can come up with the most imaginative and oddball ideas about what users might want to do with the program someday.

    6. Re:The art of code by webhat · · Score: 1


      I think you answered you comments to 3 with your comments to 4. ;)

      Checking for possible but rare error conditions is robustness

      --
      'I am become Shiva, destroyer of worlds'
    7. Re:The art of code by haruchai · · Score: 1

      Whoa, I hadn't seen a reference to Remo Williams in many years.

      --
      Pain is merely failure leaving the body
    8. Re:The art of code by webhat · · Score: 1

      Perhaps I'm dim, Remo Williams??? The TV series?

      --
      'I am become Shiva, destroyer of worlds'
    9. Re:The art of code by cratermoon · · Score: 1

      For #4 you wrote about an error hander not checking for EFBIG or ENOSPC after writing to the error log. While it's certainly maximally robust to check that, in modern enterprise-scale systems it's going to be very rare. Now certainly I can imagine some context (say, Martian rovers...) where this kind of check would be much more necessary, I stand by my assertion that it's possible but rare.

      The kind of thing I had in mind for novices writing speculative code is more related to what I call programmer-induced feature creep. In the worst cases this code for things that "might be needed in some future" is so buggy as to break the necessary features. Otherwise known as "gold plating"

    10. Re:The art of code by webhat · · Score: 1

      I actually meant:

      In reply to 3 you said:

      I just knew that someone would bring up the complications of threads.

      Then in reply to 4 you said:

      Checking for possible but rare error conditions is robustness

      I was trying to make a joke that you comment wasn't robust, because you didn't take into account that somebody would bring up threads. ;)

      --
      'I am become Shiva, destroyer of worlds'
  25. MOD PARENT UP by guitaristx · · Score: 2, Interesting

    Believe me, this is ever so often the truth. I can't count the number of times where I thought "WTF was this programmer thinking?" while maintaining legacy code, only to find out that the offending code, after tracing through the authors and check-in logs, was driven solely by a manager cracking the whip for a quick-and-dirty solution.

    --
    I pity the foo that isn't metasyntactic
  26. Bad docs better than none by Acius · · Score: 2, Insightful

    Having worked on some terribly buggy code with buggy docs, I'm going to suggest that even bad docs are better than none. Sure, you get burned once or twice, but you quickly learn not to trust the docs as canon. And while the docs often don't tell you what the code does, it tells you what the developer WANTED it to do, which is golden information when you're trying to debug.

    --
    Acius the unfamous
  27. What about COBOL? by HeighYew · · Score: 2, Funny

    I write COBOL code. Since COBOL is just like writing in English, why should I need to comment?

    ... on second thought...

    Hooray for self-documenting code!!! :)

    --
    There are 10 kinds of people in the world, those who understand binary and those who don't...what about the other 8?
  28. Comments need structure by yintercept · · Score: 3, Informative

    It seems to me that documation needs a structure. Structures like records of revision and design documents are useful. Free form comments in the code turn into white noise. Since I am far more interested in what a piece of code does, I pretty much ignore all documentation in the code. It seems like the majority of documentation in code becomes obsolete as people modify the code. For example, if a person has a problematic part in their code, they add copious notes document. When the problem finally clarifies in their mind and the find the code, they end up leaving obsolete documentation that just confuses people at a later date.

    Personally, I think a person should document the interface, maintain a record of revision. The code itself should only be documented when the code is doing something out of the ordinary.

    So, when I am learning a language, I put a great deal of notes in the code. As I learn the typical flow of the programs, I write less documentation in the code. When I have a strong feel for the language and reading the code is more informative than reading notes, my notes all but disappear. I've noticed many other programmers seem to have the same tendency. They write less documentation in code and they learn the language.

    Having supported a large number of applications. I greatly appreciate good design documention, but discard notes in the code.

    1. Re:Comments need structure by gnuLNX · · Score: 0

      I agree 100%. I only document header files unless I am doing something particularly different. My main reason is that the code changes often enough that most documentation ends up being totally worthless.

      --
      what?
    2. Re:Comments need structure by Anonymous Coward · · Score: 1, Insightful

      I find it useful to tell why I am doing something. A decent programmer can figure out what the code is doing, but even I have trouble 6 months later figuring out just why exactly it was that I did this, when this seems to be a better solution. Then I try the "better" solution, immediately realize why I went with the one I did. Saves me a lot of time in the long run to just document right there I did this b/c of that.

    3. Re:Comments need structure by yintercept · · Score: 1
      I find it useful to tell why I am doing something.

      The "whys" generally live in the design documents. Most all whys should be settled before coding begins. The problem with a methodology where the documentation lives in a different structured file than the code is that the two files are easily separated.

      This problem is especially acute with open source development. Preparing code for publication is a completely different art than just coding for compilation. When I know that people are likely to support a particular piece of code, it gets a ton of documentation.

      figuring out just why exactly it was that I did this, when this seems to be a better solution.

      I do place comments on anything that is out of my standard coding style. Which gets back to why I was agreeing with the parent post to my first post. Before, I have an establishing coding style in a language, I usually leave more notes than when I have a good grasp of the language and an established style. This is contrary to the comments of the article that said the number of notes goes up as people gain proficiency in a language.

      Now then, the article might be focusing on code written for publication. This guy is obviously reading code that was given to him so that he can read the code. A person with a ton of experience in a given language is likely to have more to say about what was done in a piece of code and why. When I give someone code to review or otherwise publish, I put in more comments.

      In other words, experience does not lead to more comments. It leads to learning where comments help and where they are just wasted key strokes.

    4. Re:Comments need structure by Anonymous Coward · · Score: 0

      You don't write very complicated programs then, do you? Multithreaded programs with semaphore hierarchies and asynchronous interfaces require comments to understand. Anything simpler is just practise for this case.

      Out of date comments are as bad as buggy code. I class them as bugs, too.

      You're either a genius, full of shit, or a script kiddie. I believe it's the latter.

    5. Re:Comments need structure by yintercept · · Score: 1

      I have yet to write a piece of code that was more than a simple logical statement...so I pretty much fit in that latter category.

      Multithreaded programs with semaphore hierarchies and asynchronous interfaces require comments to understand.

      Seems ta me that, by definition, the complexity of semaphores, hierarchies and multithreaded programs all lie in the interface.

      I openly admit I am a full of shit script kiddie. I have never written a single procedure that executes in more than one thread at a given time. When I've want multithreaded program, I've always copped out and used more than one procedure. I've never put a hierarchy in an object, although I have put objects in hierarchies. I've only used semaphores to communicate between objects.

      Every program I've ever written has just been a string of simple logical statements. Being of a petty bourgeoisie mindset, I doubt I will ever write a program that is other than a string of logical statements. The nasty documentation needing stuff seems to happen when all the different programs talk to eachother.

    6. Re:Comments need structure by Homology · · Score: 1
      Seems ta me that, by definition, the complexity of semaphores, hierarchies and multithreaded programs all lie in the interface.

      That pretty much cover all software. Multihreaded programs can be quite hard to understand, despite good interfaces. In non-trivial multithreaded programs you'll often see much infrastructure dedicated just to make multithreaded programming more safe. These structures may at first glance seem very peculiar, but they are the results of many subtle mistakes made before. Proper documentation with rationale of these structures are important, of course.

    7. Re:Comments need structure by Anonymous Coward · · Score: 0

      Your humor's too subtle to get a funny mod.

    8. Re:Comments need structure by Anonymous Coward · · Score: 0

      The question is whether or not the documentation should be comments in the code or design documents outside the code. I see comments in the code in the code as cautionary. For example, it might read: "Stop, don't change the following line. You don't know what you are doing."

      The whys should make it into the design documentation.

    9. Re:Comments need structure by Raunch · · Score: 1

      It sounds as though you (and others) comment your code exclusively for yourselves. IE, as you learn more about the language you comment less, so theoretically, when you know entire volumes about the code you won't need comments at all.

      Good call. Nothing ensures job security like a program that is only commented in your mind.

      --
      George II -- Spreading Freedom and American values, one bomb at a time.
  29. Re:Indentation by Feneric · · Score: 1

    One of the good things about the Python language is that it forces indentation. And it doesn't have insignificant indentation that can lead to bugs. Two, two of the good things about Python are...

    Seriously though I've seen enough cases of buggy things like:

    if (condition)
    statement one;
    statement two;

    that were meant to be:

    if (condition) {
    statment one;
    statement two;
    }

    to appreciate a language that doesn't encourage one to meaninglessly indent code but instead actually uses the indentation to determine blocks.

    (Unfortunately /.'s ecode tag doesn't seem to preserve leading spaces, so you can't actually see the indents -- I'm guessing though that most readers will know where they're supposed to be.)

  30. Re:I believe that what you are trying to say is th by Anonymous Coward · · Score: 0

    so, everyone who makes mistakes is a teacher to some?

  31. Re:Blogging entails responsibilities... by dj_cel · · Score: 1

    Before everyone goes into a tirade about the parent comment, I will point out a couple things. He is right in one sense, they laugh because we are different. I think it's funny to them that you could actually have a philanthropic attitude about something and produce because you like it, like art. I think programming requires a certain ammount of skill, and to do it correctly and efficiently is an artform of sorts. Posts like these are the only recourse against an army of those who have beyond the skill necessary to do the job. Yes sir, enjoy your "shiny car" and the hooker you apparently go home to everynight. It won't last forever. Besides that, it's funny about this outsourcing thing you know, because you might find yourself with a pink notice.

    --
    Those who can make you believe absurdities can make you commit atrocities. - Voltaire
  32. Anyone have a "free as in beer" copy by Anonymous Coward · · Score: 0

    please post it here, i mean this is slashdot right, the face of the free movement

  33. Re:So that is why my speling and gramor is so bad. by Anonymous Coward · · Score: 0

    I am waiting for the intelliSense to suggest the word!

    Not exactly classic flamebait. I'm trying to get incensed by the comment but it isn't working for me. I guess that's why I'm not a moderator.

  34. Indeed! by kraksmokr · · Score: 2, Insightful

    After spending many years as a programmer, and writing thousands of lines of code, I have learned so much about coding that these days I find myself not writing code at all, or very little code.

    As a young freshly trained programmer, you are walking around with a hammer, and a lot of things look like nails.

    You think you are a badass because of the power and precision with which you hit the nails.

    Then one day and you see you are building a house. And there are a lot of other people whose work is instrumental to getting the house built.

    So after a while you start telling other people how to hit their nails, and before you know it, you are building entire tracts of homes.

    1. Re:Indeed! by sylvandb · · Score: 2, Insightful

      After spending many years as a programmer, and writing thousands of lines of code, I have learned so much about coding that these days I find myself not writing code at all, or very little code. ...
      So after a while you start telling other people how to hit their nails, and before you know it, you are building entire tracts of homes.


      But that isn't the end. Suddenly you find yourself hating the way everyone else hits those nails (just when someone starts to get good they leave) and the subsequent lack of quality* to which your name is attached. You come to realize that either you care about lots of houses with your name attached, or you care about the quality of each house with your name attached. It cannot be both.

      Now you choose. Do it yourself and do it right; or just take all you can, while you can, and move on up the management ladder. What do you value?

      * - see "Zen and the Art of Motorcycle Maintenance" by Pirsig

      sdb

  35. HAHAHAH! Everybody's an idiot but me! by Thud457 · · Score: 1

    Don't get me started about projects architechted by interns and implemented by highschool dropouts!

    --

    the preceding comment is my own and in no way reflects the opinion of the Joint Chiefs of Staff

  36. my technique by SQLz · · Score: 2, Informative

    I'm a scripter (php, python, perl, java etc) and I work with other scripters. I notice a big difference in code depending on the age of the programmer and what programming language they started with.

    My technique is pretty much opposite from anyone elses where I worl, although, I don't know of this is a good thing or not.

    I start off with making tons of functions. I go crazy with functions and usually put them into related objects/packages with static methods just for organization purposes....so I quickly know where to look when I want to edit the behavior. I always maintain the PerlDOC/PHPDoc/JavaDOC comments even when I first start out because my IDE reads and pops up nice little hints when I forget arguments but other than that I don't comment too much unless I'm doing something dicey. Once I've coded enough, I start to see the places where I can refactor and abstract a lot of the functions away and weed out any inconsistancies really quick.

    Others tend to make one gigantic script with little or any functions and tons of global structures and arrays then refactor it to a more sane style later on.

    Their moto is "first get it working, then get it working right". My reply is "that doesn't mean you throw good programming practice out the window.";

    1. Re:my technique by EnderWiggin99 · · Score: 1

      Well terminated! :)

  37. Re:I believe that what you are trying to say is th by adolfojp · · Score: 1

    Wait... let me write that down :-).

    Get an account AC and harvest some karma.

    Cheers,
    Adolfo

  38. some code by Anonymous Coward · · Score: 0

    // crap about my ex
    private int guys_she_screwed=2;
    if (guys_she_screwed >= 1)
    {
    MessageBox.Show("You have STD");
    }

    1. Re:some code by Anonymous Coward · · Score: 0

      "if (guys_she_screwed >= 1)"

      Your code implies YOU gave her the STD (assuming YOU actually got to screw her...) because even with only one screwing (assuming that you got to screw her...) you give the STD output :)

      Executive Summary; you have an STD, and you cannot code for toffee!

  39. Even Worse by Anonymous Coward · · Score: 0

    // Begin Comment Header // Comment Author: // John Smith // Programmer Analyst // john.smith@company.com // Comment Version: // 0.0.1 // Comment Date: // 2005.03.08 // End Comment Header // Begin Comment // increment i by 1
    i++;

  40. What I do as a programmer by Anthony+Boyd · · Score: 3, Informative

    As a PHP/Perl/JavaScript/HTML developer, here are some of the things I think I do well:

    • I use liberal comments in most of my projects. I always try to use /* and */ to make multiline comments that are easy to quickly add to without worrying about a lot of pretty formatting.
    • I have recently started to play with PHPDoc to create self-documenting code.
    • When creating any character(s) implying "open" I immediately create the "closed" character(s) too. For example, I type "if () { }" and then fill it in. As I write this, my LI tags are all already typed, I am just filling in text now.
    • I use text editors with syntax highlighting, such as HTML-Kit -- no drag & drop GUIs.
    • I use tools like WinMerge, Subversion (only a little, not so good at it) and ReplaceEm to maintain large codebases.

    Where I fail at coding:

    • I know OOP, but it isn't natural for me, so I'm still a procedural boy, even when Object-Oriented Programming might help.
    • I have no idea what vectors and matrixes are.
    • I'm self-taught, my schooling is as an English major. So I have absolutely no Computer Science education behind what I do. While I try to do well, my solution to a deep and complicated problem is going to be basic compared to a guy who spent years of his life learning algorithms.
    1. Re:What I do as a programmer by jt2190 · · Score: 1

      I have recently started to play with PHPDoc to create self-documenting code.

      That's not quite self-documenting code. That's source code that contains documentation.

      I use tools like WinMerge, Subversion (only a little, not so good at it) and ReplaceEm to maintain large codebases.

      Keep practicing... it'll come to you. You might also want to look for a copy of Pragmatic Version Control Using Subversion.

      I know OOP, but it isn't natural for me, so I'm still a procedural boy, even when Object-Oriented Programming might help.

      OOP is not an overnight thing. It takes quite a while to get the "feel" for it.

      I have no idea what vectors and matrixes are.

      So, quit making excuses... go and learn them!

      I'm self-taught, my schooling is as an English major. So I have absolutely no Computer Science education behind what I do. While I try to do well, my solution to a deep and complicated problem is going to be basic compared to a guy who spent years of his life learning algorithms.

      The reason people spend years of their lives learning algorithms is so that THEY can produce basic solutions to deep and complicated problems. One elegant algorhithm can save you a lot of tricky coding.

      You're not the first "artsy" to ply the coding waters. Those english skills will pay off down the road. Just ask Richard P. Gabriel.

    2. Re:What I do as a programmer by Brandybuck · · Score: 1

      ...my solution to a deep and complicated problem is going to be basic compared to a guy who spent years of his life learning algorithms.

      I'm a literature major as well, whose ended up a software engineer. I did minor in computer science, and have had those algorithms classes. Thus, having seen both sides of the issues, I can assure you that nine times out of ten the simple basic straight forward solutions are superior to the fancy algorithms. For the rest of the problems you can just grab the algorithm off the net.

      You should know SOMETHING about algorithms though. You wouldn't want to use a bubblesort for example. Or spend your time rediscovering all the gotchas of binary trees.

      --
      Don't blame me, I didn't vote for either of them!
    3. Re:What I do as a programmer by witte · · Score: 1

      Vector :
      A list that dynamically grows by a predefined size when you keep adding stuff to it. Much like an array.
      Allocating extra memory is managed without you having to specifically code it.
      (In a mathematical context, it's something entirely different though.)

      Matrix :
      A twodimensional array of numbers, with a predefined size, eg. a 3*4 matrix has 12 numbers in it.
      (Calculations with matrices form a particular field of mathematics; mostly used for efficiently solving sets of equations, and bugging the hell out of mathematically challenged students.)

    4. Re:What I do as a programmer by mr_z_beeblebrox · · Score: 2, Funny

      I use liberal comments in most of my projects

      Where precisely does something like "The Bush administration has no right to detain American Citizens as enemy combatants" fit into your projects. I guess it is better (IMHO) than commenting conservatively.

  41. Objective-C by bonch · · Score: 2, Insightful

    One of my favorite aspects of Objective-C is the way methods are self-documenting. "[Object doThis:something toThis:something]" is easy to figure out.

    1. Re:Objective-C by guet · · Score: 1

      yep, though some Objective-C coders have the unfortunate habit of writing things like

      object = [[objectfoo dothis:[[objectfie alloc] initWithObject:[[objectfoe getThis] autorelease]] autorelease];

      Any language can be rendered illegible if you're determined enough. :)

  42. Chapter 7 is sure to be controversial by Anonymous Coward · · Score: 3, Funny
    Chapter 7 is sure to be controversial for some people: it covers "Coding Standards and Conventions."

    I don't understand

    why it would be so
    controversial.

  43. Uh,why does plain old text fail sometimes? by Anonymous Coward · · Score: 1, Insightful

    // Begin Comment Header
    // Comment Author:
    // John Smith
    // Programmer Analyst
    // john.smith@company.com
    // Comment Version:
    // 0.0.1
    // Comment Date:
    // 2005.03.08
    // End Comment Header
    // Begin Comment
    // increment i by 1
    i++;

  44. Bad documentation *is* better than none. by Anonymous Coward · · Score: 1, Insightful
    Misleading docs can be worse than no docs at all, since someone without docs will have to dig through the code in front of them to understand it. Someone with bad docs will rely on the docs and wonder what's broken when things go awry.


    If the code doesn't match the documentation, then you have found a bug! Either the documentation or the code is flawed: you need to revisit the actual requirements to determine which is the case. This may require revisiting the problem at it's source to determine the business, hardware, or safety requirements. When you find out the required behaviour, code it correctly, and then document it correctly!


    If you blithely rely on either the code *OR* the documentation to be correct, you're being far too trusting...

    1. Re:Bad documentation *is* better than none. by Anonymous Coward · · Score: 0

      Documentation is like sex: When it's good, it's REALLY good. And when it's bad... enh, it's better than nothing.

  45. Re:Indentation by AuMatar · · Score: 1

    The opposite argument also works- the one time I was forced to use python (maintenance work of a contractor who loved the language) I spent 3 days tracking down a problem. The problem was he didn't indent when he meant to, making something outside the if.

    The there was the problem when our prettyizer fucked up the master by changing the spacing on check in. That was a nightmare. And of course ithe fact I like to use 2 spaces to indent and he used 4 caused problems.

    WHich is why indentation is a BAD way of doing nesting. It ought to be done in such a way that meaningless differences in writing style like indentation and spacing don't matter. Perl gets it right- ignore spacing and require {} pairs on all nesting statements.

    --
    I still have more fans than freaks. WTF is wrong with you people?
  46. How will this help me write Prolog and Lisp Code? by Anonymous Coward · · Score: 1, Interesting

    The title says it all.

  47. Comments: they are documentation in the source by wintermute42 · · Score: 3, Insightful

    I've tried to work on projects where we developed new software as much as possible. However, taken all together I think I've probably spent many months of aggregate time reading other peoples code, modifying it, adding new features and fixing bugs. I hate doing this work, not only because of poorly designed software but because most software I've worked on is almost entirely undocumented (e.g., no comments and no external documentation).

    Some posters have mentioned comments and documentation in this thread. But in my opinion, it has not been discussed in strong enough terms. For a long rant on this topic, see my essay Software and Documentation. I'll summarize some of the points I try to make in this essay here.

    There were only a few people in this thread who wrote that they think that software source code is self documenting. This is a good sign. In the past this was a widely held view. Perhaps it is becoming less popular. Perhaps pigs are becoming airborne.

    To those of you who wrote that your code is self documenting: you are simply lazy and unprofessional.

    Sure I can understand what well written code does. But I cannot understand why it does what it does. I can show you three hundred lines of wavelet signal processing code. You can immediately understand what the code is doing. But you will have no clue what-so-ever about why it does what it does unless you understand the thinking behind the code. The same is true of any complex software.

    Another problem is that even though I might understand what components do and perhaps even why they are doing what they do, getting an overall understanding of the architecture of a large application can be difficult and time consuming.

    By not writing comments in your code and, for large applications, providing external documentation on the architecture, you are saving your time and effort, but forcing others to spend effort that you could have saved them.

    Even if you have no consideration for anyone else who must maintain the application after you write it, comments will help you find bugs in your own code. Again and again I have found that when I explain my code in a comment I am forced to look over it again. In doing this I have found that the code does not do what I intended or that I left something out.

    When it comes to documentation there is rarely enough. Even if you make an effort to document your code, when you are in the middle of it you will not document things that you find obvious. When you return later, these obvious issues will have been forgotten and are not obscure.

    Documentation must be maintained along with the code. And it should be extended where it is incomplete or unclear. English (or what ever your language is): it's another kind of software.

    Developers seem to fall into two camps: those who believe documentation is important and who do it and those who do not. I've managed software groups where I mentioned documentation in people's performace reviews and it still did not good. So far I have not been able to get someone who does not document to do it.

    I have thought that perhaps one solution would be to hold code reviews where one of the major features that was looked at was understandability in the code. But I have not experimented enough to know if this will actually get people to document their software.

    Literate programming not only involves writing well designed and well informed algorithms. It also includes writing documentation that explains these algorithms.

    1. Re:Comments: they are documentation in the source by rzebram · · Score: 1

      My IRC experiences make me wary of clicking on any link to "bearcave.com," no matter how intelligent the rest of your post may be.

    2. Re:Comments: they are documentation in the source by wintermute42 · · Score: 1

      Is there something I don't know about my domain, bearcave.com? I don't understand the IRC reference. There was a bearcave.ORG, which was a site for hairy gay men and bearcave.NET, a site run by network savy "Bears". Some of these are discussed here (another one of those bearcave links).

      Anyway, would you care to let me know if I've missed something? You can reach me at iank at bearcave.com. Thanks.

    3. Re:Comments: they are documentation in the source by bobaferret · · Score: 1

      I have thought that perhaps one solution would be to hold code reviews where one of the major features that was looked at was understandability in the code. But I have not experimented enough to know if this will actually get people to document their software.

      We do this and its effect varies from person to person. Generally as with most things you will see a spike, but then they will drift backwards. I've found that the only way to do this is constant review. While someone is comming up to speed or whatever, you revire their code a little evryday. This gets them in the habbit of conforming shop standards and what not. And because you are interupting their train of thought everyday for a week or two they build the habbit quickly so that they can just right some code without having to deal with you.

  48. Re:Blogging entails responsibilities... by balon · · Score: 0, Offtopic

    Ahem. Queef Latina, um, pardonay mwah, but, uh, you have a booger hanging off the tip of your nose. Not sure how you got it there.... Don't worry, we respect you every bit as much as we EVER did. Seriously.

    Awesome job not biting your tongue off, though. Your parents must be very proud.

    ---Bruce

    --
    There was this frog once, taught me everything I knew. I've learned this since: never listen to frogs that speak.
  49. Re:I don't understand (but I do) by Anonymous Coward · · Score: 0

    xcart is a tool of the devil!

  50. Nonsense. by dwheeler · · Score: 4, Informative
    I'll use whatever the indentation style of a current project is, and carry on. If you like that style, then go ahead, use it. I'll go along, too, if you're the project lead.

    But many "newbies" such as Kernighan, Ritchie, and Torvalds all highly recommend the One True Brace (OTB) style. It's the one used in the K&R's C book, among other things. In other words, some of the people MOST exerienced with C use this style.

    There are serious advantages to the OTB style. In particular, it eliminates useless white space so that you can actually see more vertical text simultaneously -- even with big screens that's helpful.

    If you want to use a different style, go ahead! If you're the lead, I'll gladly use your style. But in programs I lead, I'll continue to use OTB and expect others to follow suit. Oh, and I've been using C since 1985, so !newbie.

    --
    - David A. Wheeler (see my Secure Programming HOWTO)
    1. Re:Nonsense. by Qbertino · · Score: 1

      That's what I love about Python. It end's such discussions instantaniously. :- )
      Unless you get some prick that mixes spaces and tabs for indentation, that is. ' haven't run into someone like that though.

      --
      We suffer more in our imagination than in reality. - Seneca
  51. some newbies by r00t · · Score: 4, Informative
    authors of 1999 ISO C standard (section 6.8.3 example 3, etc.)

    Linus Torvalds (Linux kernel)

    W. Richard Stevens (Advanced Programming in the UNIX Environment and UNIX Network Programming)

    Brian W. Kernighan (C Programming Language co-author)

    Dennis Ritchie (C Programming Language co-author)

    Gamma, Helm, Johnson, and Vlissides (Design Patterns)

    Hmmm. You are a newbie. Kernighan and Ritchie wrote the book on C, literally, and the ISO C standard still uses their style. The opening brace is only by itself when starting a function body. In all other cases, it shares the line.

    1. Re:some newbies by Anonymous Coward · · Score: 0

      Haha, this is classic newbie stuff. K&R were newbies when they came up that style. No one had been programming much back then. We have come a long way since then.

      And Linus was a total newbie when he wrote the kernel. He was a college student. I've seen college students produce some of the crappiest code out there.

    2. Re:some newbies by pigwin32 · · Score: 1

      The story I heard (which may be Urban Legend) is that K&R used the style in order to fit more code on the page. It has subsequently been adopted by all and sundry because K&R are gods and so must be correct. Personally I hate it; the information content to the reader is practically nil. Many years ago I was an advocate of kclittle's indented braces and I agree it makes good sense, the preceding statement is immediately more readable. I gave it up because every IDE I've used tries not to indent braces, plus working in a team resulted in a mishmash of styles, reformatting source files is not my idea of a fun time. The answer is obvious.

    3. Re:some newbies by corysama · · Score: 2, Interesting

      It is my understanding that it wasn't even K&R's choice to lay out the code that way. It was a demand from the publisher to save paper. It may be a urban legend, but assuming it's true it makes me laugh when I see programmers get zealous defending a standard designed by a bean counter who was just trying to trim his dead tree budget.

    4. Re:some newbies by belmolis · · Score: 1

      I don't think it was just that. Around 1983 I picked up a set of C coding standards developed by the folks at Bell Labs' Indian Hill site. I can't immediately lay my hands on my copy, but here is a version of it that at a glance doesn't seem very different. It advocated the One True Style of K&R.

  52. Obligatory quote by jagne · · Score: 5, Insightful

    From Structure and Interpretation of Computer Programs by Abelson and Sussman:

    "Programs should be written for people to read, and only incidentally for machines to execute."

    1. Re:Obligatory quote by lexluther · · Score: 2, Informative

      This is a Knuth quote. "Programs are meant to be read by humans and only incidentally for computers to execute".

  53. Dr. Dobbs by Audacious · · Score: 1

    A long time ago (I know I'm dating myself here!) Dr. Dobbs had a book called:

    Dobbs (extracts from Dr. Dobbs Journal)
    Dr. Dobb's Toolbox of C
    Prentice-Hall 1986

    This book laid out the various methods which they used in the creation of Small C. I took those lessons to heart and programed by them. Although a lot of other methods have been forced down my throat by would-be managers or people who knew something about coding - these techniques have been, IMHO, the most help I have ever had when it comes to coding software.

    The book explained the WHY of "why should you indent", and WHY you should use meaningful names for variables. In fact, it explained a lot of the WHYs and WHEREFOREs of programming.

    If you can get your hands on a copy of this book - you should do so. Mine died a sudden death when, around Christmas time, the ceiling in my computer room came down. I was living in an apartment at the time and a water leak caused the ceiling to collapse. Know what gypsum becomes with some water? GLUE! So several of my really good books died that day from being glued together. Unfortunately, Dr. Dobb's book was one of them.

    Luckily, the ceiling collapsed where the books were stacked and not where the computers were stacked. That would have been an even worse nightmare. :-/

    To bring this back on topic: I haven't read this new book, but from the overview - it sounds a lot like Dr. Dobb's book. So I may be off to buy it soon just to check it out. :-)

    --
    Someone put a black hole in my pocket and now I'm broke. :-)
    1. Re:Dr. Dobbs by eclectro · · Score: 1

      A long time ago (I know I'm dating myself here!) Dr. Dobbs had a book called...

      Many of us on slashdot date by ourselves. It's ok.

      --
      Take the cheese to sickbay, the doctor should see it as soon as possible - B'Elanna Torres, "Learning Curve"
    2. Re:Dr. Dobbs by Audacious · · Score: 1

      I used to date myself - but then I found out what I was like and stopped doing it! ;-)

      --
      Someone put a black hole in my pocket and now I'm broke. :-)
  54. Other useful words and phrases in Spanish... by rafael_es_son · · Score: 1

    After visiting the local Sr. Frogs last night I think of the following words and phrases as useful to the average United Statian: Cultura means "culture", gringo is often reserved for United Statians -or whatever they should call themselves-, and the phrase no conocen de otras means "are ignorant of other". There's also gringuitas ricas, which translate roughly to something like "nice, young, united-statian college girls".

    --
    HAD
    1. Re:Other useful words and phrases in Spanish... by Grax · · Score: 1

      We call ourselves Americans. I realize this makes no sense because there are like 23 countries (or so) in the Americas. However, United Statesian sounds totally weird and besides it could also apply to citizens from the United States of Mexico (Estados Unidoes de Mejico).

      So I give up. Call me a Nebraskan.

    2. Re:Other useful words and phrases in Spanish... by rafael_es_son · · Score: 1

      Lol, I love Nebraskan minorities! They also form part of the vast minority of Below-Canada-Above Mexicoans.

      --
      HAD
    3. Re:Other useful words and phrases in Spanish... by Grax · · Score: 2, Funny

      I am a mix of Cuban-American-Scottish-English-Irish-etc. I applied for minority status for Cuban-American-Scottish-English-Irish-etc's but they told me that there wasn't enough of us to form our own minority.

      To all the other Cuban-American-Scottish-English-Irish-etc's out there I say "stand with me. power to the Cuban-American-Scottish-English-Irish-etc's"

  55. Deliberate Mess by ukleafer · · Score: 1

    Once I was asked to code something for a project that I knew I was about to be forcibly removed from.

    I named functions and variables the most obscure things I possibly could, left as little whitespace as possible, and used x ? y : z, instead of if(x) { y; } else { z; }.

    Those bastards learned nothing from me.

    1. Re:Deliberate Mess by phek · · Score: 1

      you wouldnt happen to know who came up with the x ? y : z syntax would you? I have a baseball bat who would like to meet him. or should i say

      $baseball_bat ? $his_face : $the_rest_of_his_family

    2. Re:Deliberate Mess by hyperstation · · Score: 1

      you wouldnt happen to know who came up with the x ? y : z syntax would you? I have a baseball bat who would like to meet him. or should i say

      why? i use that all the time. if someone else comes along to change it and doesn't know what that means, they shouldn't be there.

    3. Re:Deliberate Mess by Anonymous Coward · · Score: 0

      You think that's bad?

      I heard about a guy at G.E. who named all the variables in a relatively important piece of software after American warships.

      The more significant the variable was, the larger and more historically interesting the warship would be. Related variables were named after ships in the same battle group, or ships that fought in the same naval engagement.

      He was a history buff. Nobody else could do anything with the code, so the company had to keep him around.

      It's kind of amazing, really. I was like, WOW.

  56. Average reviews on Amazon by Anonymous Coward · · Score: 0

    Can anyone recommend a good, up to date, well written design patterns book for the person who has good OO knowledge but has missed a few years of being in the industry apart from hacking out Perl as necessary?

  57. joe kicks ass by r00t · · Score: 2, Funny

    WordStar kicks ass, and joe is like WordStar.
    Therefore, joe kicks ass. Alan Cox uses joe.

    Unlike vi, joe is easy to operate over all sorts
    of defective terminal emulators. For example, vi
    users are screwed w/o the escape key. I've seen
    that twice, on a real DECstation (OK, you could
    use the F11 key to get an escape...) and on a
    telnet program for the Mac.

    No problem for joe!

    Don't get me started on emacs...

    1. Re:joe kicks ass by Anonymous Coward · · Score: 0

      For example, vi users are screwed w/o the escape key.

      You're only screwed without the escape key if you use a Televideo 950 (and the escape key is broken). On everything else, you can press CTRL-[ to get an escape. On the TVI 950, somebody decided that whenever you press CTRL-[, you should get CTL-], regardless of the state of the shift key (on the 950, [ and ] are on the same key).

    2. Re:joe kicks ass by zhiwenchong · · Score: 1

      On vi, many people use Ctrl-C in place of Esc, so their hands don't have to leave the alphabet part of the keyboard.

      So no, Esc is not absolutely necessary.

    3. Re:joe kicks ass by kybred · · Score: 1
      Don't you mean
      <ctrl>-[
      That generates the same ascii code as the escape key (0x1b).
    4. Re:joe kicks ass by zhiwenchong · · Score: 1

      You could be right, i've never tried that.
      But no, I meant Ctrl-C. For mode switching in vi.

  58. I am an experienced programmer... by Anonymous Coward · · Score: 0

    Check out my new php code:
    <?
    echo "I am teh";
    print(' leet ');
    printf("php codez0r");
    while($x!=1)
    {
    print("{$x++}");
    echo(' ');
    }
    ?>

  59. Re:Indentation by Heretik · · Score: 1

    This is why there are python "guidelines" for how you should indent. (IMO it should be standard and forced to avoid these problems)

    Hopefully more languages will get this strict and we'll actually be able to read other people's code in general in the future.

    People's petty little preferences and habits aside, it is a good thing, and you know it. ;)

  60. Re:Indentation by AuMatar · · Score: 2, Insightful

    So you need guidelines to make a bad design decision work. This is what is generally called a "hack". The real solution is to not give semantic meaning to whitespace in the first place.

    --
    I still have more fans than freaks. WTF is wrong with you people?
  61. Vetenari by Nefarious+Wheel · · Score: 2, Funny
    ...namely that code is literature and should be read as such...

    Ah, like Vetinari, The Patrician ... he enjoyed reading music. He didn't want to play it, or listen to all that noise, merely to read it.

    --
    Do not mock my vision of impractical footwear
  62. Consistency, good comments, and short code by Grax · · Score: 4, Insightful

    Both consistency and good comments are good traits. I find understandable function and variable names are essential as well.

    I believe that language familiarity has little to nothing to do with being a good programmer. A more familiar programmer can program faster but programming principles remain the same across all languages.

    Smaller, simpler code is inherently less likely to contain bugs, runs faster, and is easier to troubleshoot.

    If programmer A develops 1000 lines of code per day and programmer B develops 10 lines of code per day and both programs do the same thing I will pick programmer B every time (normal lines of code, not contest entries with runon lines and things)

  63. Re:How will this help me write Prolog and Lisp Cod by r00t · · Score: 1, Funny

    If you write Prolog or LISP, nothing can help you.

  64. Understand my code! by Sir_Jeff · · Score: 1

    Who cares - as long as nobody understands my code, my job is safe :)

    --
    --Sir_-_Jeff--
    1. Re:Understand my code! by witte · · Score: 1

      You could also comment in some incomprehensible language like Finnish, or morse code, or ebonics.

  65. No, perl is still ugly. by Anonymous Coward · · Score: 0

    You are talking about a language where functions don't take arguments, and you have to waste time validating an array of args. It also has lots of "time savers" that make code completely unreadable, stupid crap like @_ abounds in perl.

    1. Re:No, perl is still ugly. by Phillup · · Score: 1

      Actually, I'm talking about the OP's point of writing clean, understandable code with good variable names.

      Something you can do with Perl, if you so desired.

      My point, which flew over your tiny little head, was that this wasn't an integral part of the language... but rather a style of coding that can be used in most languages.

      Even Perl.

      --

      --Phillip

      Can you say BIRTH TAX
  66. Re:Use comments only when needed = nonsense! by Maow · · Score: 0
    I disagree ...

    I disagree with your disagreement.

    Comments should be used whey you implement something that you can't understand by reading the code.

    Comments are for WHY things happen, which is virually never obvious from code.

    comments often get in the way and get outdated and hurt more than they help.

    I'll agree with the first two points - comments can get out of date.

    I find Perl's POD to be the solution for me - a change in code requires a change to comments within a couple of lines of the code.

    Simple, elegant, workable.

  67. Re:Indentation by Anonymous Coward · · Score: 0

    One bad thing about python is that if I use emacs with TAB set to four spaces, and my friend uses vi and types in four spaces . . .

    We need to run our code through a script to convert all TAB characters to four spaces.

    It's just another needless task in a world full of so much meaningless bullshit.

    Python can go to hell, I don't particularly care to examine every library I download to see if the author is using TABS or spaces, and then fixing it to work with my code.

  68. "plain old text" is not plain text by r00t · · Score: 1

    Excepting HTML maybe, none of the Slashdot posting
    options make any sense. They don't do the obvious,
    at least not fully, and the oddities are not
    documented.

    Try filing a bug in the Slashcode Bugzilla.

  69. Commenting in Eyecandy, ERP Modules & Space Cr by Qbertino · · Score: 2, Insightful

    When I programm ERP Modules (in Python) I start with a large comment on what the module is supposed to do. I actually started doing this quite from the beginning. I write a litte summary of what the module does and comment heavily throughout the source. I even have debugging sessions were I only work on comments - often detailing them further.
    I also do a lot of other programming (ActionScript rich media and stuff). I don't do opening or other comments there that much.
    Why that?
    If a multimedia app doesn't work I get an e-mail or a call asking to check into it within the next 24 hrs. The customer is anoyed or says that this comes bad with the end-user. We talk a little, I et to work and fix it within the next 10 hrs.
    If a ERP module doesn't do what it's supposed to, I get a call on my mobile, with the CEO at the other end telling me that he's losing 200 Euro an hour because order processing has gone haywire.
    This is a good point to end all discussion wether commenting is good or bad. When you are debugging a piece of code that keeps 3 people breathing you shure as well want it to be well commented.
    The Lockheed Software Group, the people who write code for the space shuttle and other things, take this to the all-out extreme. They write EVERYTHING in a sort of human readable meta code, meta-comment THAT and then tranfer that to real code. They've had 3 bugs in 25 years - so I've heard. One of them being a counter problem that once would have nearly locked down a com-dish on an orbiter and prevented it from following it's target on earth after having rotated a certain amount. Figure: A millisecond of timing error in their code has the orbiter off course by 3 miles. I hear their comment line/code line ratio is about 7 to 1.

    So much for "overcommenting is unprofessional".

    --
    We suffer more in our imagination than in reality. - Seneca
  70. What about version control? by Spy+der+Mann · · Score: 1

    CVS usage should be at the beginning of the book. CVS has saved hours of work for me. Why isn't it part of standard programming education?

    1. Re:What about version control? by oo_waratah · · Score: 1

      Because real businesses have no need to look back at themistakes they made in the past. They only need to go forward.

      Forget college, why don't most businesses do this properly.

    2. Re:What about version control? by Diomidis+Spinellis · · Score: 2, Interesting
      I discuss revision control systems in Chapter 6 of the Code Reading book, titled Tackling Large Projects. I also present revision control in the elective course Software Comprehension and Maintenance I am teaching. In that course students have to contribute to an open source project, in order to pass the course.

      You are right, version control should be part of "programming" education, and should probably be taught in a software engineering course.

      Diomidis

  71. No, this is completely wrong. by Anonymous Coward · · Score: 0

    Python proves conclusively what a stupid idea significant whitespace is. Any reasonable language has handy little curly braces (or something else at least) enclosing blocks. You still have "guidelines" on how you should indent. The difference is with perl if someone ignores those guidelines, it still works fine, and I can run an automated tool to re-indent everything to the project standard, since its based on curly braces so its easy to parse. When someone ignores the guidelines with python, you get bugs that are insanely hard to track down, and can be completely invisible since so many python people insist on using spaces to do the very purpose tab exists for.

  72. code is... by oneishy · · Score: 1

    I have to quote the wordpress moto here

    "Code is poetry"

    It's what I live by now.

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

      It's funny that the Wordpress code is such a horrible mess. That one always gets me :P. Not that it's particularly bad code, it's just not very pretty or elegant.

    2. Re:code is... by oneishy · · Score: 1

      Interesting point, and well said. There are parts of wordpress code that I don't like; but at the same time I think it follows the principle of being built in a fashion geared towards extensibility. (think plugins, and custom template pages).

      Hopefully - as they say - the 1.5 will be even closer to 'code is poetry' all the way around :-)

      But I digress

  73. static typing is good. by Anonymous Coward · · Score: 0

    If you don't know what kind of variable something should be, then you shouldn't be coding it. The misconception that you can code faster without static typing is because people compare C and C++ to python and ruby. Compare python or ruby with pike and see how wonderful static typing can be. The languages are all of a similar level, so its a decent comparison.

  74. You know what I love about python? by Anonymous Coward · · Score: 0

    Not using it because its completely fucking broken all because captain shitforbrains thought having a logical language that can be easily parsed and formatted was bad. Python's significant whitespace creates a whole set of problems, and solves nothing. Instead of bitching about good languages letting two people indent differently, man indent.

  75. Call everything by its right name by blackhedd · · Score: 4, Insightful

    To think of code as literature is actually a non-obvious and striking idea.
    The essence of literature is communication. I've been writing C and C++ for years, constantly fine-tuning and refining code and documentation, line by line, paragraph by paragraph. And how apropos to realize that the point is to express the thought so clearly and concisely that any reader (including yourself three weeks from now) will grasp it as close to immediately as possible.
    That means you have to think clearly in order to code clearly. This matters more than almost anything else.
    Too much documentation is just as bad as too little, since it obscures the intent of the code. How much is just enough? It takes years of thoughtful practice to know that.
    Everyone is posting their favorite rules about coding standards. Most young programmers apply standards as rigid as they are incomplete. I have only two rules:
    1) Call everything by its right name. Functions are verbs, variables are nouns. The name you give a object should express what it is or does, no more and no less, and be readable in English (or whatever your spoken language is). If you add something to a function that doesn't fit the function's name, it either belongs in a different function or else you misnamed the function in the first place. This takes constant review of your code, from a literary point of view.
    2) Rules are made to be broken. All great writers unhesitatingly break the rules in order to communicate more clearly.

    Languages are for communicating, and computer languages are no different. Keep that in mind at all times, and you'll become a wizard.

    1. Re:Call everything by its right name by webhat · · Score: 1

      Coming in hungover and actually trying to read the code you wrote the day before is a great equalizer. (What can I say, don't schedule office parties for weekdays. ;)

      One time, after sitting at my desk with my pint of coffee for an hour thinking: "What the fuck was I trying to say here?" I deleted the contents of the function and rewrote it in a children's story way.

      I don't want to say it was the best code I've ever written, but it was a hell of a lot better than the code I'd replaced and somehow managed to compile first time. (I didn't believe it either and spend the next day testing it just to be sure.)

      DISCLAMER: Obviously I checked it when I was sober and had backups.

      The reason I posted this as a reply to this comment eludes me now, but I'm sure I had one. Probably the literature comment. Thinking about it I probably couldn't read Dostojevski hungover either.

      --
      'I am become Shiva, destroyer of worlds'
    2. Re:Call everything by its right name by blackhedd · · Score: 1

      Shiva the destroyer of worlds reminded me of another point:
      Try reading your code out loud, as silly as that sounds. Not only will that immediately cure you of identifiers-without-vowels and the evil curse of hungarian notation, but you'll almost instantly know whether it makes logical sense. Just try it before you flame, especially if you're a young guy who already knows everything ;-). My C/C++ and Java almost always compiles the first time. You wipe out a whole class of stupid errors with this technique.
      Reading code out loud is the next best thing to reading it to someone else.

      Shiva: were you in the Manhattan Project or something? :-)

  76. Responsible Laziness by jhohm · · Score: 1

    Responsible laziness is key here. Be responsible enough to comment unclear code; but be lazy enough to prefer rewriting the code for clarity to banging out a comment.

    My best C++ code has no comments. All the names are pronouncable and meaningful. The code is just as readable as a comment would be, but it can't get out of date with the code like a comment does.

    I make an exception for class-level comments giving the code context in the program; those are good.

  77. A lot of programmers here say they document... by ulatekh · · Score: 1

    ...to which I can only ask, "Where the hell have you all been for my entire career?!?!"

    I only meet the morons that can barely code, much less comment or design.

    --
    "Once we've identified and embraced our sickness, we'll have strength...and that's when we get dangerous." - John Waters
  78. Re:Commenting in Eyecandy, ERP Modules & Space by Anthony+Liguori · · Score: 1

    The Lockheed Software Group, the people who write code for the space shuttle and other things, take this to the all-out extreme. They write EVERYTHING in a sort of human readable meta code, meta-comment THAT and then tranfer that to real code.

    Not quite. What differs from most other shops is that they rigorously do design reviews, code reviews, unit testing, and integration testing. A product stays in a maintaince phase for years before ever being shipped.

    There's not that much more commenting in the code than in any other large software product.

  79. Don't bash hungarian by Chemisor · · Score: 1

    While I find the full Hungarian notation excessive, a subset of it specifying only the location of the variable can be very valuable. When you are looking at a variable, one of the most common things you want to know about it is where it is declared. With hungarian m_, g_, and s_ prefixes it is immediately clear where to look for the declaration if you need it.

    1. Re: Don't bash hungarian by gidds · · Score: 2, Interesting
      Agreed. Full Hungarian notation is an abomination. A variable's type has no business being in its name; not only does that preclude changing the type at some point, but the type is usually clear from the context anyway.

      Whether the scope should be there probably depends on the language and system. In C, like you I've found p_ (for function parameters), g_ (for system-wide globals) and m_ (for module-level variables) useful; also s_ (for 4GL screen fields). That way, you know where to look for the definition, so you can find anything else out there. (Local variables get no prefix.)

      In Java, though, I find scope is usually obvious. Methods tend to be short enough that parameters are usually obvious; class names should start in upper case, which should make them obvious (and you can track them down from import statements); fields in other classes are always obvious from context; and there are no globals to worry about. The only confusion is between local variables and class fields; for a while I used a single underscore prefix for fields, but I really don't find it necessary.

      I'm sure that other languages have their own needs.

      While we're here, might as well repeat my own principle for meaningful variable names: The length of a variable name should be directly proportional to its scope. A variable that's only used for a couple of lines after it's defined is best kept to a few characters; but one that's used throughout the system should have a name long enough to make its function clear.

      --

      Ceterum censeo subscriptionem esse delendam.

    2. Re: Don't bash hungarian by hachete · · Score: 1

      I find the clearer the name, the better my ideas behind the algorithm. Typically, when writing something, I might start off with variable names that are worthless. As the code progress, the names jell and become clearer.

      I can always tell a suspect piece of code: the names are ill-thought out and have little contextual meaning.

      I'll certainly use that idea of scope.

      I use logging *a lot* and I find that logging can obviate some of the need for comments.

      But, however well names are given, they cannot convey some of my assumptions behind the code, which is what should be documented. Big time.

      --
      Patriotism is a virtue of the vicious
  80. It's not wrong. by Chemisor · · Score: 2, Informative

    > dealing with function pointers named StupidSuckingGlobalCallbackFunction

    When you have functions named like that, don't write documentation for them. Rename them. It takes a lot less effort to write code so its meaning is obvious then to write documentation explaining why you didn't do that.

  81. Enough of the 'comments' already. by dubbayu_d_40 · · Score: 1

    Comments are poor substitutes for readable code. Not bashing comments, but frankly, 95% of comments are useless drivel.

  82. Re:dating yourself by Chemisor · · Score: 2, Funny

    > (I know I'm dating myself here!)

    Don't worry, we all do.

  83. Another issue by Lifewish · · Score: 0, Redundant

    I'm currently trying to get the hang of the C/C++ programming languages - I'm a mathmo so haven't had to deal with it til now. Now, I run linux and am exposed to a decent amount of raw C code, so one would have thought I'd figure out what was going on quite quickly.

    Wrong! Evidently the people writing the code I read have tried to make it self-documenting. They use what are apparently standard names for variables and structures, and fail to provide any comments whatsoever.

    This is completely useless for me since I have *no idea* wtf these names refer to. Animal, mineral, vegetable or pointer? Who knows? The code is completely illegible to me, and as such is completely useless regards the FOSS secondary purpose of education.

    When I started the maths/computer projects I am required to do for my course, my dad gave me an interesting piece of advice. "Son," (he said), "I measure the value of code by weight. The more comments the better." This was obviously a simplification and resulted in my producing Python code that was 2/3 comment - complete overkill.

    However, I'm reasonably confident that no-one could read my code without realising what was going on, whether they knew the Python language or not. In addition, I'm pretty sure that it's possible to learn at least the basics of Python by studying my code.

    I intend to keep this habit as I get more experienced at programming. Possibly a few FOSS developers could stand to do the same?

    --
    For the love of God, please learn to spell "ridiculous"!!!
  84. Oh, no! A Java programmer. by Chemisor · · Score: 1
    I can tell you are a Java programmer. A C++ programmer would never create a function called "equals".
    while (experience < GOOD_PROGRAMMER)
    if ((code = writeNewCode()) == BAD_CODE)
    experience += consequences(code).lessonsLearned();
    1. Re:Oh, no! A Java programmer. by mabinogi · · Score: 1

      Actually, I'm a C programmer who now writes Java.
      As such I have completely avoided any taint implicit in operator overloading, and have managed to keep reference equality and logical equality as separate concepts ;)

      By the way, I predict that leaving out the braces may have the consequence that a future edit may overlook that fact and introduce a bug, resulting in the lesson learnt that clarity is sometimes preferable to brevity.

      --
      Advanced users are users too!
    2. Re:Oh, no! A Java programmer. by mrjohnson · · Score: 1

      Ah, but (this is on topic) perhaps the author uses emacs and trusts it to align the code correctly, which would make missing braces an obvious error.

      We have learned about him from his code. :-)

  85. Chapter 12 by balford · · Score: 1

    For those who don't feel like reading 1 through 11.

  86. reading rule of thumb by recharged95 · · Score: 2, Insightful
    You'll notice good code is when you're reading the code and see comments at points when you question (yourself) the control flow from an architectural perspective. Then the developer's comments explain why he/she chose that path (i.e. the solution/algorithm/paradigm) and the pros&cons of his/her choice.

    Hence, simple algorithms will likely have no comments in the implementation.

    More of the time, comments that "supplement" the code usually add to the confusion for most advance developers.

  87. Worse than pointless by bluGill · · Score: 2, Interesting

    or simple counters I find that using i or j or similar works quite well. After all, everybody understands a for loop with an i index -- calling it array_index_counter or some-such is (IMHO) pointless.

    No, array_index_counter is worse than pointless, using i or j is recognizable to any good programmer, no though required. Using array_index_counter implies that there is something other than a loop index going on with the variable and causes all good programmers to pause for a moment to figure out what that is. (Only to be annoyed when they realize it is just a loop index)

    There is one other program with descriptive loop indexes: they take up too much space. The example you gave it 19 letters, and in a typical C for statement will be repeated three times. That works out to 57 letters. Add in a few for the other required parts, and indentation, and you are longer than the typical terminal line, and all hope of easy readability is lost. (Unless you expand the window, but that assumes you do all your editing in a graphical environment, which isn't always true)

  88. no holes in the sides of your head? by StandardDeviant · · Score: 1

    You must have one bitch of a time hearing. ;)

  89. I agree. Great book! by JerseyTom · · Score: 1


    I've been programming since 1985 and I still learned a lot from this book.

    I've recommended it to many people and I just get blank stares like, "why would anyone want a book on code reading?" I have to put it in front of their face for them to understand.

  90. Re:Blogging entails responsibilities... by Anonymous Coward · · Score: 0
    Posts like these are the only recourse against an army of those who have beyond the skill necessary to do the job.
    Then you missed the point entirely: Suits don't need any skills, because they know how to play the game, and because most people are like them, and not us. Which is why nerd projects like linux on the desktop is so pathetically unreachable and wishful thinking. They don't laugh at us because they envy our l33t skills, dork, they laugh at us because they're the ones that make all the money and drive nice cars and have actually seen a vagina in person!
  91. Re:Commenting in Eyecandy, ERP Modules & Space by Bean9000 · · Score: 1
    I hear their comment line/code line ratio is about 7 to 1.

    If this number is correct, most likely the "7" refers to all the documentation behind the code. Requirements, design, review comments, testing, actual comments etc. So i wouldn't be at all surprised to hear a 7:1 documentation to code ratio. But a 7:1 comments ratio just for comments in the actual code seems highly unlikely; it would make the code almost unreadable. Imagine trying to read a story when between every sentence there are a few pages of pictures.

  92. Re:Blogging entails responsibilities... by zootread · · Score: 2, Funny

    We might not lend ourselves well to sympathetic portrals in commercials and other media, but every night we can come home in a shiny expensive car, to a nice furnished apartment, and eat some pussy before going to bed.

    Eat some pussy before going to bed? You sound pretty whipped to me. I either get my dick sucked by my girl or stick my dick in a pussy and blow a giant load in her mouth or pussy (and sometimes in her ass). I never ever have to eat her pussy. Eating pussy is for lesbians.

    I think the idea that geeks can't get laid is a huge misconception. Eventually some woman gives us a chance, and after years of masturbating we have such good sexual control and technique that we're able to make her cum like she's never cum before. That's what happened to me anyways. Having said that, though, having someone to fuck is really not that big of a deal, I don't know why people act like it is and put down people who can't get laid. Yes, sex can be really fucking good, but it doesn't improve you as a person to be getting it. If you were a stupid fuck before getting laid, you're a stupid fuck after getting laid.

    And yes, I am one of those open source hippies. But I get paid for leveraging open source technologies. And I get laid. Boo-yah!

    --
    Zoot!
  93. comments are overrated by menem · · Score: 2, Insightful

    Have you ever been in a code review that was a comment review? Where the reviewers, unwilling or unable to find problems in the code, nitpicked about how the comments looked like? Too many managers and second tier programmers spend their time worrying about the details of the comments and coding style because that is all they understand.

    What good are great comments if the code doesn't work? Sure, comments matter, but all of the comments in the world aren't going to make buggy software run better. It will just make the next programmer understand how screwed up the original programmer was.

  94. Not commenting by pgarcia · · Score: 1

    Sometimes, like in my case, it is not usefull to coment the code I write. I try to go beyond that and even make it as unreadable as posible. Writting unreadable-unmantainable code make your self unfireable. What happen if no body else but you is able to keep on working the modules you have written. I just keep clean the interfaces. Their inside is mine and just mine and nobody else should be ever able to understand a word. It keep my workplace safe.

    1. Re:Not commenting by mr.mighty · · Score: 1

      I'd fire your ass. It will be better in the long run to recode the stuff you did already than to put up with your obfuscated code, only to have you quit after 5 years.

      Besides, if you make it that bad, you'll have just as much trouble figuring it out as someone else will when it comes time to fix it.

    2. Re:Not commenting by witte · · Score: 1

      I would fire someone with such an attitude as soon as possible.

      Not that i would personally dislike you, but i can't have people playing the "information-is-power" game in my team.
      In the end it harms the team and the client/company more than it benefits you personally.

    3. Re:Not commenting by pgarcia · · Score: 1

      But what if this not-commenting right-line is behing commanded by my inmediate boss, in order to keep the algorithms being developed in our team secret against other in-company-but-in-conpetence teams?.

      This is a real scenario in a very-very big company. And I know, not commenting is against all software-engineering methodologies, but what if you are suppose to do like that?

      greets

    4. Re:Not commenting by witte · · Score: 1

      Well, that's a very specific problem.
      (...are you perhaps a freelancing developer there ?)

      Anyway. If you insist; such sourcecode could still contain comments that deal with technical issues that are not documented in the functional/technical specs of the unit/app/system in question.

      eg. you would comment
      "Allocate byte extra for these strings, need backward compatibility with ExoticPlatform zero point fossilized"
      but not comment with pseudocode, that would be in your documentation.
      (If your docs are done allright, you are able to recreate the whole shebang from scratch based on the docs.)

      If you have to maintain or bugfix, docs + technical comments in the code have to suffice as complete documentation, for you or any dev on your team.

      I still don't think it is a good idea to not comment your code, though.
      You really should have your superiors deal with the internal politics, and not have to care about internal political crap like that.
      (Unless, you are an external developer and you want lock-in with the client company. But I advise against that, even.)

  95. I have a comment about your post by Anonymous Coward · · Score: 0

    > You can tell a great deal about the maturity of a programmer by the quantity, and quality, of comments.

    Yo mama.

  96. Re:I believe that what you are trying to say is th by Anonymous Coward · · Score: 0

    Yes, but the true programmer makes mistakes intentionally- Just to see what the compiler will do.

  97. MOD PARENT UP !!!!! by Anonymous Coward · · Score: 0

    +1 insightful, +1 informative (especially the coke out of the nose part), +1 underrated, -1 not funny, +1/-1 apparently schizophrenic.

  98. Vocabulary by The+Grassy+Knoll · · Score: 0

    It mostly boils down to learning a new vocabulary - just as in learning a foreign language; once you've learnt the grammar, you need to slog away at the vocab before you can use it in any meaningful interaction.

    In the late 80s, it was fashionable to suggest that Language graduates would make good programmers. As a late 80s Language graduate now a programmer I agree!

    --
    They will never know the simple pleasure of a monkey knife fight
  99. Why ? can't you read code ? by Anonymous Coward · · Score: 0

    comments in code get out of sync REAL quick and can generally be more a curse than a blessing.

    If code is well written and clean then it is easy to read.

    If it is not easy to read, you are probably not thinking the problem through clearly.

    1. Re:Why ? can't you read code ? by Suicyco · · Score: 1

      Its not about how easy it is to read. Any beginning programmer should be able to read it.

      The issue is understanding it. Perhaps this piece of code is has drastic ramifications on some ancient code elsewhere which cannot be changed (ie. binary only) which may not be totally obvious. Perhaps, perhaps, perhaps. The point is, if there is some fact about the code not immediately obvious from reading the code itself, it needs to be stated. Very little code can be said to be self documenting in a very clear way.

      Remember, its not about HOW the code does what it does. Its WHY.

  100. Commenting tools by dreadlock9 · · Score: 1

    I've been programming in PHP for about 2 years, and programming in general for 16 years. I've always commented my code since I started programming BASIC on my Apple IIe. I would usually put stuff mostly for my own reference. When I release my source code, I usually go in and add more comments.

    http://phpdoc.org/
    PHPDoc (inspired by JavaDoc) helps me write better comments by formatting my comments using tags. It makes a reference manual for my code in multiple formats. Now instead of comments, I make DocBlocks. Page level DocBlocks describe the general purpose of the file. You can group files together in packages. It helps to see how it all looks from the user's perspective, no matter what language you are using.

  101. Read Code, *NOT* Comments! by andr0meda · · Score: 2, Interesting


    There is a lot of emphasis on comments here, and while I agree that the commenting style and opportunity seized by a programmer gives away a lot about the insight of programming, I just felt it necessary to add that commenting is not the holy grail either, and certainly not the final and decissive way to judge a programmer. Comments have the annoying property to become outdated. Especially when code ownership is blurry, comments in code tend to become obsolete or unapplicable. Despite all good intentions of the programmer.

    It is better to 'read the code' instead. And if you 'can`t read the code', it means that the code sucks! Plain and simple. Then it`s time to refactor, and make sure that you can read the code as if it tells you a story about what happens with data, and why. Real good programmers know how to abstract and describe this process using architectural elements and design patterns, and without the need for a lot of extra commenting.

    There is no algorithm that is so complex that it can not be put in a more or less readable form in code. Use abstractions and propper long names for classes, variables and fucntions. Describe with code what you are doing, and use small comments in-between to explain the progression within the algorithm, but refrain from writing large texts and function header comment blocks or whatever. They will become incorrect and misleading, and they are a drag to keep updated.

    The only reason where I could think of using extensive comment sections in your code is to feed document system code parsers like Doxygen or Doc++ etc.., but that is only usefull if you`re writing an API, and when you know that 90% of that API is stable and will not change much.

    --
    With great power comes great electricity bills.
  102. I Found the book dissapointing by Kubla+Khan · · Score: 1

    I picked up code reading about a year ago and began to devour it, only to walk away dissapointed. This is a book I wish someone had handed me when i was fresh out of college, but anyone with a few years of experience of working on large codebases is probably going to find little of value in here. Being told what if statements mean can be a little patronising. The section of the book that compares and contrasts structures from different languages can be useful if you are making a transition to a new language. The text is well written , but I would advise anyone who is thinking of picking up a copy to browse it in a bookstore first to make sure there is some valuable material for them in there before parting with their cash.

    --
    "In Xanadu did Kubla Khan a stately pleasure dome decree"
  103. Brace style does not matter by oo_waratah · · Score: 1

    If you cannot run it through indent to format the code to your standard if you absolutely cannot read the particular brace style then you are newbie.

    If you mix brace styles in the one source file or break a standard on a project THEN you are newbie.

    I will stick to K&R formatting, I find your style irritating as you find my style. I get doubly irritated when people pointlessly reformat my code to make a 1 line change. Ever tried to QA that code and figure out what the real change is.

  104. Have it, loved it by webhat · · Score: 1

    I actually have this book and learned a bit from it, even though I've been coding from the age of 6, not in c obviously. It actually contained examples of a few of the mistakes I made and enough of the examples allowed me to pat myself on the back.

    I never got as far as the chapter on tools, but I'd like to add a note here on what I do for code readability:

    As I have my own style I like to and can easily read code in that style, this is neither the BSD or Linux style, so I fire up the old indent program an convert it to the format I use. (It took me hours to tweak until I had the right settings.) Then I can read it in the style I find useful.

    When I realease code I run indent over it to convert it to the style most used by most of the people in the project, or as in some projects the style that was defined as the project style.

    I most note that sometimes I find myself typing functions as:

    int func(var1,var2,var3)
    int var1;
    int var2;
    int var3;
    { // cuz I'm a bit of a nut...
    }

    which I then have to change for the release versions.

    --
    'I am become Shiva, destroyer of worlds'
  105. comments and code by willCode4Beer.com · · Score: 1

    Although I understand your point most best practices say:
    Your code should say what you are doing
    The comments should say why

    Your post suggests that you've got the first part (having clear code with sensible variable and method names).

    --
    ----- If communism is a system where the government owns business, what do you call a system where business owns govern
  106. Re:Indentation by Heretik · · Score: 1

    No, the real solution is to strictly enforce exactly what one indentation level of whitespace is.

    Vasstly differing code styles between people writing in the same language is nothing but a nuisance, and productivity/cooperation killer.

  107. Bad Coders Are Arrogant by Anonymous Coward · · Score: 0

    I recently started a programming contract for a major investment bank in Sydney, programming Perl.

    After 5 weeks I had to stop because the boss was off his rocker. He kept making comments about how great he was, how he got all these web pages going in several hours, etc etc.

    His code was messy, uncommented, and most importantly, incredibly unsafe.. no type checking, no input checking.

    And my task was to maintain that code.

    The arrogant bastard would criticise how long it would take for me to maintain his code. So I started taking shortcuts and belting out code quickly (and under stress). Then he gets upset that it doesn't do what it should do so he starts to prove me wrong by debugging.. and discovers the error in a function he wrote in another library. Then still gets off telling me how his side effect shouldn't have been triggered anyway.

    Really pissed me off, but hey I was being paid $450 a day so didn't say anything to him.

    When I quit he gave me a lecture about being unprofessional. Pfftt I almost laughed but hey business is business and the boss can believe whatever he wants.

  108. I have news for you by p3d0 · · Score: 1
    Why yes, it IS a giant waste of space to represent an 8-bit value in a 16-bit quantity. But someone thought it was a good idea to leave out unsigned.
    Are you talking about Java? I think JVMs allocate 32 bits for all fields (even a boolean) anyway, so there is no difference between byte and short (unless you're talking about arrays).

    It's a vicious cycle. JVM developers say "nobody uses bytes or shorts anyway so we're not going to put a lot of effort into object layout optimizations that don't buy us anything". Then Java developers say "changing this int into a short doesn't make the object any smaller, so I might as well use the int for everything and not worry about overflow".

    Maybe embedded JVMs are different, I don't know.

    --
    Patrick Doyle
    I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
  109. Re:Learning from decades-old code -Data not code! by ahodgkinson · · Score: 1
    Interesting in this thread is that most people are harping on comments and the style of code itself, with no attention is being spent on the data that the code is (presumably) moving around. The code can be found directly in the source files, but the enlightenment on the organization of the data can be spread over source files, include files, data specification files, etc.

    In my experience (over 30 years), the effort that has the best pay-back in terms of reducing the risk and difficulty of new and maintenance programming is to design suitable (meaning appropriate given the tools, project size, and staff skills) data structures and data handling techniques, and communicate them effectively. The communicating part is best done in writing and this can be in design documents, README files, or as comments in the code itself. I've noticed that as I've aged, I have changed from attempting to write complete formal, well-formatted documents (which you never get to finish), over to informal README files and ascii documentation. The goal being to get something in writing for the next poor guy that's going to have to work on the code.

    Picking on comments and coding styles, in my opinion, is a sign of lack of understanding. Sure there are crappy programming styles, and it's a shame when everyone on the team writes in their own personal style, but that's missing the big picture. While it's annoying, it's usually a sign of a much larger problem, namely that there's no thought behind the code and it's all a big hack.

    Much more effort should be spent on documenting the data and data structures. In fact, early in my career I once heard an old timer say that if you understand the data and can invent sensible subroutine and variable names, the code more or less writes itself.

    --
    ---- It won't be as bad as you fear or as good as you hope, but it will take twice as long as you plan.
  110. I Learned How Not To Code by jac1962 · · Score: 1

    . . . by reading Microsoft Visual C++ .NET examples.

    --
    "I worked hard for it. I deserve it. And I have it," Campbell said. "It's all mine."
  111. Type checking (in PERL) by Anonymous Coward · · Score: 0

    However, a non-typed or loosely typed language (e.g. PERL) can make things a LOT more difficult to read. Sometimes your problem space is best defined as a complex data structure. In perl, you need to put the right brackets and the right prepending symbol to get the perl program to understand just what you are trying to create in the data realm.

    Ina strongly typed language you don't have to do this because you have explicitly told it what your structure is and it is evident.

    Depends on the problem space.

  112. //increment i by one by Anonymous Coward · · Score: 0

    Why is it that everyone who argues for less comments uses

    i++; // increment i by one

    as an example of over-commenting? So far, of all the code I've ever looked at in my life, I've yet to actually see someone do this. Even the people who write tons and tons of comments don't do this.

    My basic rule for commenting is that any time the english language rendering of a piece of code looks much different than the piece of code itself, it deserves a comment. For example, it makes no sense to write a comment like this,

    x = (i + j) / 2.0; // add i and j together and divide the result by two

    However, it does make sense to write a comment like this:

    x = (i + j) / 2.0; // find the average of i and j

    Of course, if you make it obvious what you are doing through the use of variable names, then the comment becomes unimportant. e.g.,

    average = (i + j) / 2.0;

    Similarly, if you write a piece of code like this

    if ( myObj.needsUpdating() )
    {
    myObj.update()
    }

    You don't need a comment that says "if myObj needs updating, then update it".

    So, obviously there is some things you can say in code that don't need commenting. But when people say something like "my code is self-documenting, so it doesn't need comments", I have a hard time believing that. I work with some people who write great code that's concise, well engineered, has descriptive variable names, short functions,etcetera. And still, I can't understand their code when they don't put in comments.

    The fact of the matter is that oftentimes something that you can say in one sentence will take 10 lines of code to actually do. So, if you put the explanation in *before* the 10 lines of code, then someone only has to read the code if they actually care about *how* you are doing it instead of just caring about what you are trying to accomplish.

  113. False, humane language is not computer language. by Anonymous Coward · · Score: 0

    You will be right the day computers will be programmed in humane language, meanwhile there's a semantic gap between code and the reason to write that code.

    AC posting because /. forbids loging from public ADSL Inktomy cache servers.

  114. Re:Commenting in Eyecandy, ERP Modules & Space by el_chicano · · Score: 1
    Imagine trying to read a story when between every sentence there are a few pages of pictures.
    Well, if it works for President Bush then it really can't be all that bad!
    --
    A man who wants nothing is invincible
  115. Who cares? by 97percent · · Score: 1

    Honestly, who cares what brace style K&R used in their 17+ year-old book.

    I seem to remember these guys also peppered their code examples with one letter variable names and avoided checking array bounds like the plague. Almost every string handling example had a potential buffer overflow in it. Should we keep these practices too because K&R popularized them? Are K&R that infallible?

    Anyway, here you go, directly from the book:

    "The position of braces is less important (than indentation is), although people hold passionate beliefs. We have chosen one of several popular styles. Pick a style that suits you, then use it consistently." -- The C Programming Language, page 10.

    Thanks K&R for your permission! BSD style it is!

  116. Bug fix comments by Aardvark99 · · Score: 1

    Code comments I find worthless and distracting are statements of who wrote the code, what bug number it fixes, and when it was done. Often I find "mature" (ok, old) code is filled with this type of stuff.
    For example (from a random file from the system I work on now): // 7/13/00 default conversion type is BCD
    ConversionType = BCC_BCD;

    Who CARES the on 7/13/00 this change was made! Often these type of comments may include version numbers of the product (better, but still bad). Even worse I'll see JUST version info/dates: // 2.5
    if (m_bSomeNewFlag)

    Maybe this was helpful for the developer working on these v2.5 changes but don't leave these breadcrumbs around.

    Names or initials are bad as well, especially bad when only used alone: // MCW // MikeW

    OK, thanks Mike W. for all your hard work!

    One issue with this type of stuff is that it's hard to maintain. How do you tell where the code added on "7/13/00" ends? What if I change that line, or add code near it? Do I change the date? Add my name to that code? There's 1000's of lines w/o names on them, who wrote those, and who cares?

    Also, how the system worked in the past and how it's been changed can seem, in theory, to be useful... but what is the real benefit? A history lesson? I feel the code is not the best place for this. Often these type of comments included the commented old code, which I find very distracting from what the code IS doing. Even worse is commented code w/ no explanation of why it was commented and not just removed outright - but that's a bit off topic.

    The who's, what's, and when's of code changes should be tracked in your SOURCE CONTROL and BUG TRACKING system, period. If those two systems work together, all the better. If you don't have one that can do this job, get one. Make sure it's easy, people are trained on it, accessible to everyone, and fast.

  117. Other means of judging a programmer's skills by kbielefe · · Score: 1
    There are other means to judge the skills of programmers in addition to reading their code:
    • How well do they use the development tools available to them? For example, when debugging a segmentation fault do they employ endless cycles of inserting print statements, rebuilding, and rerunning or do they use a debugger? How many times has a coworker asked me to help them debug a core dump when the first thing they did was to rm that "pesky" core file?
    • How well do they use the revision control system? My biggest pet peeve is programmers who comment out a section of code and then check it in to revision control. This just shows a lack of confidence in your decision to remove the code and a lack of understanding of revision control. Also, does the code work after every commit or at the very least compile?
    --
    This space intentionally left blank.
  118. Python == no indent style complaints? Naaaah. by dwheeler · · Score: 1
    There are still style issues in Python. Heck, even indent style complaints. Do you use tabs or spaces? And if it's spaces, how many spaces per indent? If it's a continued line, what do you deal with the continuation?

    And there's more to style than indenting, anyway.

    Nope, you won't be able to avoid style decisions just because you use Python.

    --
    - David A. Wheeler (see my Secure Programming HOWTO)