Comments On Code Comments?
theodp writes "It seems like comments are on programmers' minds these days. The problem with comments, as Zachary Voase sees it, is that our editors display comments in such a way as to be ignored by the programmer. And over at Scripting News, Dave Winer shares some comments on comments, noting how outlining features allow programmers to see and hide comments as desired. 'The important thing is that with elision (expand/collapse),' explains Winer, 'comments don't take up visual space so there's no penalty for fully explaining the work. Without this ability there's an impossible tradeoff between comments and the clarity of comment-free code.' Winer also makes the case for providing links in his code to external 'worknotes.' So, what are your thoughts on useful commenting practices or features, either implemented or on your wishlist?"
Changing the color of the comments, or making them collapsible/non-collapsible isn't going to have any meaningful impact. A rushed or sloppy coder is going to ignore them either way. And a conscientious coder is going to read them regardless.
The real problem with comments isn't their color, it's when they AREN'T THERE AT ALL. You could have the damn things flashing in rainbow colors and it still wouldn't change the fact that the legacy code I'm going over was done by a sloppy piece of shit who never wrote any comments in the first place, or who wrote cryptic/indecipherable comments that would take a linguist 10 years to translate into meaningful English.
Now, if you'll excuse me, I've got to go play Sherlock Holmes with some strange method written by an Indian contractor whose only comment on it was "This move thing around."
What political party do you join when you don't like Bible-thumpers *or* hippies?
If your aim is to make something more visible, don't pick a yellow-on-white colour scheme.
Bogtha Bogtha Bogtha
In order to better utilize synergies and business genius patterns of excellence, comments need to be stored as XML in a cloud-based LDAP database that partners, stakeholders, clients and yourmom can access via an iPhone app. If you don't do this you are a monkey, or maybe a horsepig.
UNITE with the Campaign for a Free Internet because today, our future begins with tomorrow!
The reason editors let you collapse comments is that you sometimes have to make really ugly code -- whether it's for performance or time constraints. And the only way to really describe it actually larger inline blocks that can obfuscate the code. So they make them collapsible for those who have read them already.
Winer also makes the case for providing links in his code to external 'worknotes.'
Yeah, we use an internal wiki.
So, what are your thoughts on useful commenting practices or features, either implemented or on your wishlist?
The biggest complaint I have is people who use comments to explain bad object/procedure/function/method/script/class/whatever naming. For example, a guy I worked with calls everything a "driver." Main method? That's a driver. Class holding the main method? Of course DriverClass. Package? Of course YYY.ZZZ.NNN.Driver. On it goes. Another guy likes to use the verb "interrogate" where as I like to use the verb "inspect" and I think that's just more about your origins (I think he's Spring background while I'm a little more on the Ruby/Groovy side of things). A common and well defined vocabulary inside your team and embedded in your actual code will take you much further than trying to explain it all out in the comments.
My work here is dung.
Use vi. Always works for me.
...because most organizations are total failures that make you write and maintain thousands of pages of "design" documents that are actually just the code-base itself converted line-by-line to English sentences. Thus, no comments are ever written, because the developers are already maintaining two instances of the entire code-base.
At my current job, most of the developers think commenting is weak. I've dealt with this problem before, but it's awkward when I'm the only one that wants to comment. Funny thing is, every time we hit a program that a former developer wrote that my boss can't understand, he makes us rewrite it. Having comments in the code might save a lot of development time.
When I managed a team, I required commented code. It saved our butts more times than I can count. I also use it to look for bugs. It's amazing what code review can do a few weeks after you wrote something or having another developer look at. When code doesn't match comments, there's a bug.
MidnightBSD: The BSD for Everyone
>> It seems like comments are on programmers' minds these days
Really? I'll bet the new round of browsers, iOS, Windows 8 (have you seen how many APIs and visual paradigms are broken?) and any number of other major platform changes are much, much more on the minds of programmers these days.
>> Winer also makes the case for providing links in his code to external 'worknotes.'
Oh God - one of those people.
I don't really understand why we're going over this for the 50 thousandth time on slashdot, but as always, good comments are good, bad comments are bad. Comments that describe the interface of the function you created and how its supposed to be used are good. Comments that say "increment the variable" are worthless and perhaps worse than worthless as they add maintenance problems when the underlying code is later changed and nobody bothers to change the comments as well.
Comment first, fill in the code later.
My God, it's Full of Source!
OUTSIDE_IP=$(dig +short my.ip @outsideip.net)
Without this ability there's an impossible tradeoff between comments and the clarity of comment-free code
As far as I'm concerned, there's no such thing as comment-free code that is clear.
There's also nothing worse than a comment that states the bloody obvious. If I'm clearing a register to zero I don't need a comment next to the SR 6,6 or XR 6,6 that is performing that action. I can read the code to see what the bloody code is doing.
The time that code needs a comment is when you're shifting bits or multiplying something by a funky/obscure value for a sensible reason but the reason isn't obvious by simply reading the code.
Also remember you don't get the comments in the post mortem storage dumps when you're trying to fix someone's programming error at 2:30am with a few managers breathing down your neck panicing that it won't be fixed and running by 8:00am.
Sigs. We don't need no steenking sigs.
I think all code needs comments, unless it's something incredibly basic. However, keep the comments short and to the point. Don't write a paragraph when all you need is a sentence. Also, don't use slang unless it's extremely well known.
Hey asshole, I don't know about you, but I make my comments on Slashdort , where they are appreciated and honored by the Slashdort community, whereas you are a noxious pigfart sniffer and dogsmoocher.
UNITE with the Campaign for a Free Internet because today, our future begins with tomorrow!
I also think that comments describing interfaces are better than comments describing processes. This is the old thing of "describe what the module does and leave the description of how the module does what it does to reading the actual code." So preambles describing the parameters a function takes and valid ranges on those parameters are most useful.
The other thing about comments is not so much the writing of them but the keeping them up to date. The compiler doesn't check that the comment is still relevant to a function you have changed.
I'm a mechanical engineer. Our "code" is models and drawings. These are what represent the real world objects in our designs. But you don't just deliver a set of drawings as a product. You have Analysis Reports, Design Manuals, Operation Manuals, Maintenance Manuals, Parts Lists, Concept of Operations, and about 20 other documents that describe the system you built. Sometimes a good engineer can pick up the drawing package and figure out how the thing works. But if you really want to understand the design you have to read the other products. If those products don't exist you end up reverse engineering from the design.
I love Jesus, except for his foreign policy.
For me, when it comes to comments, is it's about who wrote them.
There are people I work with, who, no matter how much commenting they do, I still don't trust they knew what they were doing. So I'll always step through and analyze what the code is doing myself. Could that be classified as "Don't judge a book by it's cover." ?
Here's a question, if the code is written well... doesn't it document itself? I mean, as a developer/programmer, shouldn't I be able to read/speak that language fluently enough that I don't need a full english translation?
I used to put a lot of comments in my code. Then I read the book Clean Code, and it changed the way I look at comments. Basically, every comment you leave in your code is an admission of defeat: you were unable to write your code clear enough to eliminate the need for the comment. Today, I write my code with comments, and then I go back and try to eliminate each comment by making the code clearer instead. So instead of
do_args(&argc, &argv); // process command line arguments
I do this:
processCommandLineArguments(&argc, &argv);
and the comment is no longer needed.
Today, my code has far fewer comments, but is easier to read and understand. The few comments that are left are usually block comments that explain why something is done, or outlining how the code could be improved or expanded in the future.
"This does not work"
"What the f*** is this doing?"
"TODO: fix"
All of the above are useless comments, yet they seem to sneak into everything. Worse still are comments that are meaningless to anyone who did not write them, or comments that make reference to undocumented conversations (e.g. "This is the implementation we spoke about on Tuesday").
Don't waste time writing useless comments. If you do not have time to fix a function, the comment should explain what needs fixing so that someone else can do it without first spending half a day debugging.
Palm trees and 8
I'm just here for the Comments on Comments on Code Comments.
Then you can read what the code is supposed to do and understand how it is supposed to work.
Next, you uncollapse the comments, see what the code actually does, and fix it.
Ok, it's not a list per se, but what I would like to see is an editor that automagically makes the comments on any given lines a tooltip when you mouse over that line. To me, it seems the most intuitive and unobtrusive way to deal with comments, but maybe I'm wrong.
In my experience, comments are usually as clever as the writer, and as good as his code. When it's my code and my comments by the way the quality of the comments seems to diminishes as the code ages, even with the file timestamp not changing.
// Validación de cuenta bancaria
Anyway I remember discussing comments vs self-explaining code with a coworker. Eventually we ended discussing magic numbers (usually they warrant SOME explanation), he just told me he used #defines which made thing a lot more clearer. After the coffee, I checked some of his code:
#define ONCE 11
#define DOCE 12
(In Spain bank accounts have a simple check embedded so you can easily verify is a bank account number is incorrect, and the algorithm requires to validate the results of the calculation with the values in positions 11 and 12).
When I was in grad school my thesis guru believed in a tool called fweave and ftangle. You write code in a c like syntax, along with comments that are regular TeX or LaTeX files. Then send the code through fweave and you get a regular TeX formatted document that can be viewed in ghostscript or printed postscript. Send the code through ftangle, you get a valid FORTRAN code that can be compiled and run.
It worked for him because he keeps getting a stream of grad students and the code project has to be perfectly documented for the next student to continue the work. But in companies where technical specialists can occupy a position for many many years along with constant pressure to add features, the first thing that get dropped is code documentation.
For example I have been shipping my product for 16 years now. So many of the functions I write are fleeting and have low half-life. They often start out as a debug function to help me understand some issue, which might not even get checked in. But a few get checked in, first invoked in debug builds alone, then in release builds under env flags, then slowly they morph into sanity check function or an audit method, then a verification procedure, then eventually a special case detector for some feature. When it was first written it does not appear to be worth commenting well. By the time it is part of the feature, it is considered too late to spend resources to comment it.
sed -e 's/Chuck Norris/Rajnikant/g' joke > fact
I have a tendency to be terse with comments, but say enough to make it clear, if I don't feel the code does. Sometimes though, I add in a joke or pun (like, in AIRC, I have a comment "play the server game of ping-pong").
-uso.
What you hear in the ear, preach from the rooftop Matthew 10.27b
Some people like to ensure that operations would be hindered should they be fired.
Code comments should only be used to explain why you are doing something not what you are doing, The what should be self explanatory by good coding/variable naming. A comment should not say " loop through all the variables adding 1 to each" it should be more like "Need to shuffle the nodes down by one in order to make room for a new one at the top". When reading the code I can get all the information provided in comment one from the code, however I may be left guessing or baffled as to why they just did that. Where is comment two lets me know exactly what the author was intending and I can see if the code is doing what they wanted or if there is a better way.
Subtle clues tell me how much code I'm probably going to have to fix in the maintenance of an application. Comments could tell me if the programmer considered a section of code to be temporary with replacement needed, or if the function I'm looking at is a crucial part of the application. One of the best projects I've ever worked on had the requirements that had driven each function at the front of the function. That made it very easy to focus design and refactoring efforts where they were really needed.
I recently inherited a ten-year-old heap of perl code, on top of which someone had piled a ruby wrapper. There's a lot of functionality that's duplicated between the modules of both languages, and refactoring it all is going to be a nightmare. The code could be in a transitional state where the design is not where I want it for easily a couple of years. I've liberally sprinkled it with todos and comments where I'm putting new code, so the next poor sucker who gets this thing maybe doesn't have to start completely from scratch.
I'm trying to teach myself to set people on fire with my mind... Is it hot in here?
Because I don't write code. I do neither. But both. Confused? I use literate programming -- your code is you commentary. They can't get out of sync. And, as a bonus, rubber ducky debugging is built in.
If it's good enough for Donald Erwin Knuth, it's good enough for me.
Do you even lift?
These aren't the 'roids you're looking for.
For example, Eclipse gives a nice preview of methods and pulls in the javadoc into the tooltip when hovering over the comment. Therefore, I try to keep these up to date.
On the other hand, comments that just say the method name, or cannot be expected to be maintained, should not be created.
On the point of good code, yes you can write good code and reduce the need for comments, but there are just times when a comment is necessary. For example, there may be code for something that programmers (or humans in general) are not intuitively familiar with. Industry specific items in science, financials, etc. would qualify. If you ever expect a new person to come on and modify your code, you need to make sure they can jump in quickly. A quick comment as to what an industry specific item is, can go a long way to reducing the learning curve and allowing the contractor/new employee/etc to focus on what they are good at (coding).
I have never worked on a program where I did not find comments that were flat out wrong, causing me to (1) waste time discovering the comments were wrong, and then (2) trying to figure out what the program was really doing. As a result, I have become a fan of minimalist comments and better quality coding.
To ensure that important information springs to the foreground, comments should exist primarily to document something which is not obvious from the code itself: requirements justifying the code, rationale for a particular approach, explanation of complex logic, and the occasional TODOs and FIXMEs.
For example, a method on Person called setName() does not need a comment "This sets the name of the person."
Additionally, there is no need to pepper "// end if" and "// end while" and "// end method" comments all over the code on every right curly-brace. IDEs that automatically comment are pure evil.
Koans and fables for the software engineer
The problem with comments is that the code is Dynamic, the comments are Static.
Someone can write code and write beautiful, fully descriptive comments, which are valid for about one iteration of the project. Then the same or other developers will come along and change code to match new expectation and functional requirements, and NOBODY ever updates the comments after the fact.
Also, comments can be pretty useless. I tire of seeing comments and summaries on classes which basically paraphrase the name of the method or function call like: /// This method returns true when a connection is established
void bool IsConnectionEstablished() {...}
I mean the above summary is a waste of everybody' time and not worth the bytes it consumes in the source code.
Code should be self evident and any software developer worth their salt should be capable of being able to follow a logic path through the software given it was written with any amount of competence.
The problem today is there are TOO MANY wannabe software developers that see code development as a way to make a quick easy buck but lack the fundamental skill levels to be a talented software developer. This is why there exists Agile process and software patterns, unit testing and gobs of "value added" frameworks, etc. It's because you can no longer have teams of talented software developers working on a project, you have a bunch of code monkeys that punch in code. Therefore you required external influence to ensure a project comes together efficiently and is maintainable in the long run.
The problem is when these code monkeys are told they must document their code is when the whole system breaks down. Poorly written comments, wrong information, rapidly changing feature requirements that do not match code commentary.
I abhor ANY system or process that adds overhead to the software development process. Unit testing fails because if your code changes, you must change your unit tests. CODE IS NEVER STATIC. Google touches 60% of their entire codebase every 6 months because they are constantly optimizing and improving it. I have NEVER seen a system where code is written once and then becomes a static reusable module. The problem is that MOST teams using Unit Testing end up turning off the unit tests after some period of time because they become unsustainable, whatever motivation brought unit testing into the team environment is lost when deadlines are exceeded. Few managers realize that Unit Testing adds 20 - 30% or more overhead to software but plan development as if Unit Testing takes no effort. The software changes, but nobody wants to invest the time to ensure unit testing is updated to match the new requirements of the system.
Same with code comments. A team might become motivated to add commentary to a project, all developers diligently add comments and summaries, and then when deadlines approach that is all thrown out the window because nobody will ever maintain comments AFTER they are written.
Don't get me wrong. There are cases when a quick comment prior to a block of code can mean the difference between wasting an hour of intense forensic code analysis. I use comments whenever the code does something slightly unexpected or purpose not easily understood. Its a hint rather then a full blown documentation of the feature, but in general globing up comments into code is one of the most useless waste of times and potentially damaging initiatives a code team could ever embark on.
I would love a system that can be self-testing and self-documenting. Microsoft is working on a solution called "code contracts" which allows you to define the requirements of a functional block in code, which will then ensure the safe usage of the block with the code entering and exiting the solution. Because code contracts ARE CODE, any changes to the requirement of the code requires changes to the code contracts that are tightly coupled to that functional block. Because you describe the purpose of the
I haven't thought of anything clever to put here, but then again most of you haven't either.
Many programmers do documenting as a last step, which leads to comments explaining what the code does. However, I do not need a comment explaining waht the code does. That's the code for. I need comments explaining why the code exists. The purpose must be documented. On a higher level I need documentation explaining why the problem X has been solved with solution Y and which other solutions have been considered, but not used.
When I have a class JvmTypeParameter and there is no documentation about the used vocabulary, I do not know what the purpose of a parameter is for a type. Jvm tells me, it is for Java of the Java virtual machine. I do know what a type is, however I do not know what the developer thought when he used that name. Therefore I do not know what a type is in this context and what he or she thought could be a parameter of a type.
The answer is, a JvmTypeParameter is a reference to another type or set of types used in Java generics. For example List the String is such a type parameter in the above example. To understand what it is, you need a lot of context knowledge and that is normally missing from code comments and in most cases also from the documentation.
I'm not convinced about external worknotes at all, because they're probably stored completely separately from the code itself. What's wrong with saying "Further details in the'"Main Menu design' section of README.txt in this directory" in a comment if you don't want to include a large swathe of comments in a source file?
If worknotes.scripting.com goes down for any period of time or goes bust, then this guy's links to external worknotes aren't going to look too clever. Never mind that the example he did use has just 5 bullet points that could easily have gone into a comment surely?
I suspect one of the few useful things an editor or IDE could warn you about is if you've gone more than a screenful of code (or perhaps let the warning level be set in terms of lines of code) without a comment, though no doubt some programmers would turn this feature off anyway :-)
Documentation external to the code is pointless and worthless. It gets out of date, glosses over implementation details, doesn't directly reference code (only by function, normally, and functions can be HUGE) and doesn't state much that couldn't be found through introspection.
Documentation in comments has the opposite problem. It describes ONLY the implementation details, stays (pretty much, if you're good) up-to-date, stays with the function/method/class/objects being described, and states only things that you *CAN'T* see with just a brief look at the code.
And, in the end, the code is the master of what ACTUALLY happens.
So it's not really an easily solvable problem by some editor paradigm. External documentation solves different problems to in-code commenting, and are usually even written by different kinds of people, and neither of which tell you what's ACTUALLY going to happen.
If documentation was just-that-easy to fix, we'd have done it already. But it's more a political, professional, and personal problem than it is anything some magic "system" can fix.
And, to a trained programmer, hundreds of lines of comments are pretty much treated as whitespace whether they have collapsible trees of source or not. That's why we colour them that way, so they don't get in the way of real work. And also, we need them out of the way and have learned to ignore that colour when we're coding and ignore the code when we're commenting.
They are two separate entities, and you have to "context-switch" to comment or to code (usual procedure is code until it works, then comment it). And other documentation is entirely separate and a totally different ball-game.
Java's @Override is great. I says something that might be a comment in C++. But its checked at compile time too.
Java's JavaDoc is good to.... its parsed by the IDE so when you latter hover on a function you see its javadoc.
Adding Java's final or C++'s const on variables is another good "executable" comment.
A well commented code base is like a pool full of clean water. Poor/absent/misleading commented code is like piss. The value of having a pool rapidly deteriorates if someone's pissing in it, even if by volume there's far more water than piss. The only way you're going to keep the pool clean is if you have chemicals in the water that immediately lets you know if someone is pissing and can evict them, that is to say code review. But if you already have a pool of piss, writing good comments is like pouring a liter of water into it - it's still a pool of piss. The only thing you can do is empty the pool and start over and try to do better next time. So I'm more it depends on the state of the code - if it has good comments, write good comments. If it is salvageable, salvage it. If it is a lost cause, don't waste any time trying to band-aid it.
Live today, because you never know what tomorrow brings
Comments suffer from incurable bitrot. So when I need to understand code, I never bother reading the comments, since it is usually more confusing than the code.
Excuse me, but please get off my Pennisetum Clandestinum, eh!
My definition of self documenting code is code I've documented myself. Yes, there's things that are horribly obvious and don't need documentation. Then there's the other 95% of what's in the file. If nothing else saying the function of the next section of code and dependencies can really help when I have to go into it 6 months after it was written and change something.
I also use headers to document changes but that's a slightly different topic. At least a general idea of the changes (with defect number) is available for the next person so they can keep track of who did what, when they did it and why. There's some terrible changes that were made but were necessary due to whatever reason was in the defect.
Descriptive variable names (within reason) and decent whitespace also go a long way to making the code more easily understood.
If the next person doesn't want to read the comments then that's their decision. I put them in as part of how I code.
As soon as I saw that the guy wrote "UX" I knew I was probably dealing with an exceptional moron (how that one acronym has turned into such a reliable red flag, I don't know, but look around and try to tell me it isn't true), but I still had no idea just how badly the article would go. It's not even stupid. It's just .. nothing.
The guy's argument is really that his text editor's preferences are/were set to something he doesn't like.
I shit you not. His editor's preferences were something he considers to be not-quite-right, and he noticed that it wasn't working well for him, and then somehow that turned into a programming article.
I can't even follow through on my "UX" prejudice and say "Aha! See? The guy knows nothing!" because he's taking it to the next level, so that from now on when I see "UX" it'll be "Aha, See? The guy says nothing." Although now that I think of it, maybe that's what the "UX" red flag has really always meant, all along. Hmm. Ok, you did give me something to think about.
As copyright owner of this comment, I authorize everyone to defeat any technological measure which limits access to it.
I worked at a (backward) company that didn't understand version control. Their solution was to litter the source code with meta-comments for version control - Thousands of them in just one file. They stayed there and accumulated forever.
Any real comments were in Japanese, and the file format was some strange character set that many editors couldn't work with.
There was so much bumph on the screen, you'd be lucky to see a single executable line of code at any one time. At every single point in the decision tree, these people had picked the worst possible path.
Don't imagine the idiocy stopped there either.
That sounds harsh, and of course it doesn't fit 100% of the time, but if you look closely enough it is true a frightening part of it.
The only thing you can trust is the code.
When I write comments it is usually to say "this code might look like an opportunity for this or that refactoring/optimisation. Don't do it becauase..."
Yes, ideally the code should express this directly, and commetns are an admission of defeat, but sometimes we are defeated.
sudo ergo sum
I write a lot of comments because it feels natural to me. For me, the *most* important obstacle to working with another's code (or my code that I haven't seen for a long time) is understanding the meaning behind it. With that priority, I sometimes write three times more lines of comments than lines of code.
It surprised me when I ran into someone who thought this was "too many comments." I came to understand that, for this person, the priority was to see as much code on the screen as possible. For him, my comments were "diluting" the code and making it harder to understand. I think I saw this reflected in the summary description when it mentioned "the clarity of comment-free code."
This was an important moment for me, in that I realized neither he nor I were "wrong," we just had different things that were important to us because we had different ways of understanding code.
::applause::
Some useful links for those who aren't familiar w/ it:
http://www.literateprogramming.com/
http://en.literateprograms.org/LiteratePrograms:Welcome
and best of all, Crowther's Colossal Cave Adventure as a literate programming novel translated by Donald Ervin Knuth:
http://www.literateprogramming.com/adventure.pdf
I've found literate programming to be invaluable for coding up infrequently touched systems which need updates from time-to-time.
William
Sphinx of black quartz, judge my vow.
Try programming in assembly language for a year or so. Then see if you still think comments are useless.
This is a valid example if you own or have access to the source code. But, in Java for example, in the case you just use an external non-opensource library, how the heck a Javadoc is useful if there are no comments at all on some important complex methods just based on the name and the parameters ? At some point, wouldn't it slow down the coding ?
The problem with comments is that they create a false sense of understanding.
For example: /** // bugfix#8859: we need to multiply all additions by 2 for some weird reason
* Adds two numbers together.
*/
function addNumbers(var num1, var num2) {
return (num1 + num2) * 2;
}
And so the API docs will read:
function addNumbers(num1, num2): Adds two numbers together.
The actual domain knowledge of what this function does is encoded in such a way as the inner meaning is lost. Some documentation tools "fix" this by including the source code so that the competent reader can spot the glaring problem here. But most BAs don't want to read code (or don't know how) and so the communication of what the function REALLY does is lost.
1) Write code so that it is easily understandable
2) where #1 is not possible, include a brief comment where necessary
3) Try to refine instances of #2 into instances of #1
4) ???
5) profit.
"impossible tradeoff between comments and the clarity of comment-free code"
There is no tradeof between uncommented code and commented code. Uncommented code does not add clarity.
I like my code commented if it isn't obvous what the code is doing.
Also, comments should help the developer, comments should not explain what I can read from the code.
Try digging around in 1M lines of code, and you will understand when and where comments is required.
They are required where the chain of thoughs itsn't clearly expressed by the code itself.
Comments aren't for you, they are for others who have to figure out what you've done. If their style and logic is different (which is almost always the case) then it will take a lot longer to figure things out without comments. This is why comments are important. It speeds up the learning curve.
The problem with comments is that they don't compile. The language does not complain if a comment is horribly wrong or horribly out of date. That is the problem of comments. Code folding is another problem. If you feel compelled to hide your own code, there is something horribly wrong with your coding style. And if you feel compelled to hide somebody else's code, it's broken. Fix it.
Nae king! Nae laird! Nae yurrupiean pressedent! We willna be fooled again!
FUNCTION fx_get_bar_from_foo
...
...
...
...
(
p_foo IN MYTABLE.MY_FIELD%TYPE
) RETURN MYTABLE.MY_FIELD2%TYPE
/**
* This sample function is only an example with comments.
* It may be right or it may be wrong but the comments in here
* allow me to come back years later and understand what I did.
* Yes it's a bastardization of Java and PL/SQL. Plus people
* at work love my code so far so I must be doing something right.
*
* @PARAM p_foo IN MYTABLE.MY_FIELD%TYPE my FOO field.
*
* @RETURN MYTABLE.MY_FIELD2%TYPE my BAR result.
*/
-- Variables.
v_return MYTABLE.MY_FIELD2%TYPE = NULL;
-- Cursors.
BEGIN
-- Check the parameter passed in.
IF NOT p_foo IS NULL THEN
-- Must be good, process it.
SELECT
MY_FIELD2
INTO
v_return
FROM
FOOBARS
WHERE
MY_FIELD = p_foo;
-- Check it against the magic cursor.
-- Log the request.
END IF;
-- Return it.
RETURN v_return;
EXCEPTION
WHEN OTHERS THEN
-- This isn't good, log and return nothing.
RETURN NULL;
END fx_get_bar_from_foo;
-- Use a good editor, either an IDE like eclipse or something like Notepad++, Kate, or Gedit.
-- Easter Egg Comment: The yoke is on you!
~~ Behold the flying cow with a rail gun! ~~
Amen, brother.
Without this ability there's an impossible tradeoff between comments and the clarity of comment-free code.
Are you fucking kidding me?
He can't figure out how to do it, so he falsely claims that it's "impossible"?
I wrote the following entry on perlmonks.org several years ago. http://perlmonks.org/?node_id=473080 It's nothing specific to the language, so I'll just copy verbatim here.
(Of course, the slash ecode tag and lameness filter fought my attempts to include the pseudocode example, where indentation is useful.)
[
We should have environments that compile the comments and ignore the code, because that is where the bugs are.
Who ever read a comment that read anything like the following?
tone
I thought comments were for people who can't code, and I don't want them in my code anyway so...
From my personal experience, I don't think it's a bad thing that the "editors display comments in such a way as" your brain is not bothered by them while parsing the code.
Comments are written in common language most of the time (pseudo-code in few cases) and it takes some effort to interpret them while you're trying to follow the data flow in the code. Graying them out or even collapsing them is a feature.
On the other hand, you when you look for them, I think most of the editors don't make it hard for you to access them.
With comments, I prefer that they explain why the code is doing something, not what it does (which should be evident from the code)
The thing I find frustrating about this debate and ones like it in CS is just how absolute people get in their statements... "I do things X way because it is right, if I have power over someone in hiring and they do not do X then I will not hire them or let them go!". This is pretty scary since what it means, at least in part, is people are not being hired or retained based on if they can do the job, but on the roll of the dice that they just happen to match up with the particular philosphy of the person above them... and expletive help people who are flexible and can adjust to local standards... they don't even get past the interview stage since 'well, what is your convention' is often the 'wrong' answer when you are asked how to do something.
I can recall years ago having to fill out a programming test for an interview that involved how you would make a 'card' and 'deck' class. I pointed out there are something like half a dozen ways to implement this, all of which are valid but are aesthetically differ t based off the local culture. This was considered the 'wrong' answer because the interviewer had a very clear idea of what the right way to make a 'card' class was...
From my blog:
http://madsoftware.blogspot.com/2007/06/my-confession.html
I have a confession to make. Forgive me. Wait, don't forgive me. I'm completely unapologetic. I am a programmer, and I don't write comments. I just needed to get that off my chest.
I don't believe in comments.
I have been writing a lot of fairly complex code lately. And all the while, the voices of dead Computer Science professors have been speaking to me. They repeat the mantra of good code commenting. I feel guilt, like when I go to church. Or when I don't make my bed in the morning. Of course, not one of them is able to give me any good suggestion of what a good set of comments is. They just tell me what isn't a good comment. So does that mean that anything else is a good comment? Like lots of swear words in the code. That's probably more useful than real comments, because they make me laugh and keep me from falling asleep at the keyboard.
Good comments, I'm told, are not just a rehash of what is already in the code. Well, if it isn't already in the code, then it isn't much use to the program is it? I don't believe in comments. I think they are mostly a waste of time. Maybe not for you, but for me they just make my life difficult. I have to make a context switch to English in order to write them. That takes time and just serves to confuse me.
Whenever I write English, I take the audience of my writing into account. Who is the audience for my comments? Some moron with a basic C++ book on his desk? Or the great man himself, Bjarne Stroustrup? Bjarne is pretty smart and will probably be able to figure out my code just fine without me, or my comments. Because he speaks C++. I speak C++ too, so that's how I like to communicate with computers and other people who speak the same language.
So I don't write comments. I'm one of those people who likes to use good variable names, good function names, and good file names. When I look at others' comments, I don't usually trust them, because they often don't make any sense. Or they are just plain wrong. That's just awesome. Like the time I first starting programming and I spent two days wondering why the second member of a pair of ints (pair) was always zero, even though the comments said it should contain some valuable piece of information. Actually, it was the first member, not the second one, which I finally figured out by actually looking at the damn code. Wonder of wonders, the code actually told me what the code did. Amazing.
I think that instead of comments we should put quotes of great authors at the top of all our code. That way, when people read our code, they will think that our code is profound, because we quote the greats of our time like, Dostoevsky, Helen Keller, or Dave Barry. And the best thing would be to just randomly pick those quotes so that when people try to make some connection between the code and the quote, they'll spend lots of time trying to figure out. Then they'll feel stupid, but won't want to admit it and we can fun of them when they can't explain the connection. And we won't have had to be smart at all, because all those people that we referred to are smart.
Have I even written comments? Of course, I slap all my comments in the headers, when I don't feel like writing documentation. Or when the function name is getting too long. Or when some fellow programmer makes me feel guilty for not following the religion of comments. What is the point of writing commments if the function name tells the whole story? Take vector for example, the size() function returns, guess what, the size of the vector. I know what you're thinking, that is completely non-intuitive. It's got to be commented. Look, if the function name can't tell you what the function does, then maybe you should change the function name. And if your function name gets too long, then maybe your function is doing too much.
Good, maintainable programs are easy to understand not because they hav
Mad Software: Rantings on Developing So
1. To document an API with methods and expected outcomes.
2. To document TODOs.
3. To document why a method is public (ie. for unit tests).
4. To document the reason for workaround code when working with an external third party web service or other type of api that sometimes returns inconsistent results where the information is sometimes available through other means in the system.
Jesus was a compassionate social conservative who called individuals to sin no more.
Necessary, but not too detailed. They should briefly summarize what you did, and perhaps how (again briefly) but MOST importantly "WHY you did what you did.
Please do not read this sig. Thank you.
Comments that describe why you are doing something or that explain strategy are exceptionally useful. Please include them. When I need to look at your code in two years, they will make me very happy.
Comments that describe how the language works (e.g. "//loop through the arguments") or what something is (e.g. "int i; // loop counter") have the possibility of being eliminated through careful selection of names, code organization, etc. Doing this will also make me very happy.
Also, please live within the language definition. Substituting "argv" with "CommandLineArgumentVector" when programming in C makes your code less clear because it no longer matches what is taught in every C book. Same goes for brace placement. If you want to call yourself a "C" programmer, your code will look like it came out of K&R.
I'll climb down from my soapbox now.
Just put them in a collapsable region (#region ... in Visual Studio), then expand them to read or collapse them to get them out of the way and, if you have coding to do, which you do, get back to work!
I've found that, usually, the one that is most affected by my own careless lack of commenting is my future self... the point is, commenting code well can help you directly, at a later date, when you go to take the lid off again and start wondering, "what the hell was I thinking here..."
I've found that comments never get in the way, and I always appreciate them when they're there. Just a short one is a whole lot better than nothing, and almost as good as a long one... please just give me a CLUE what was happening here!
Djikstra said, "Always debug the code, not the comments". No one updates the comments. Including me.
A guy above said that their team treats incorrect comments as a bug, and they're right in that approach. The whole point of high-level languages is to communicate with the programmer as well as with the machine; if the source code contains inconsistent instructions for the human and the computer, the program's current internal logic is flawed. Even if the binary executes without errors, changed the code won't be smooth because of those contradictions.
While the school of 'weave' and 'tangle' from literate programming proved to be too heavyweight to be practical, the future of comments is not to ignore them, but to better integrate with the IDE. Documentation generators like Javadoc or Doxygen were a big hit because they simplified building rich sets of deep, easy-to-navigate comments. Also coding features like design-by-contract and unit testing can be thought as forms of executable comments - they don't contribute to the program business logic, but they tell the programmers about its inner stable structure.
Programmers ignore comments not because it's the right thing to do, but because it's hard to do well. As tools for engineering comments along with code get better, we'll find programmers using them more and more during the early programming stages instead of an afterthought.
Singularity: a belief in the "God" idea with the "demiurge" relation inverted.
It is very difficult to write "self-documenting" code in assembler. Most variables are not even named (registers).
Also, people usually do assembler for a reason, either it is for heavy optimization or direct hardware access. In both case there is usually a lot of things behind the code that is not visible. For example situations where there is a good reason for doing b+a instead of a+b are much more common in assembler than in high level languages.
The more comments you have in code, the higher risk you have of time sucks and bugs (past, present, and future). Instead, use naming and syntax to make your code as human readable and comprehensible as possible. Bytes are cheap, there's rarely need for clever abbreviations; instead of getting clever with them, get clever with expressing your code closer to plain language. Think about the names of your nouns and verbs (and even adjectives and adverbs), and make sure they make sense to anyone who understands your problem domain.
In my humble opinion, broken code comments are almost as dangerous as broken logic, and should be treated as a bug if it's wrong. It's wrong if it's inappropriate, outdated, misleading, takes more than a line or so, or superficially obvious. If it needs more than a line or so, it should be documented, and the line in your code should brefly identify the problem and documentation location. I'd recommend that it refer to sections within a technical design document.
No technical person likes to spend time writing documentation. In my career this is a universal truth. I document my code and I write external process documents as well. I hate it, but I do it. Why? Because six months down the road when I've moved on and focused on something else a requirement changes in the old code. I have to go back and make changes quickly and be confident that my changes don't screw up anything else. I partially rely on the documentation I wrote to explain what the inputs are, what the output should be and why I did it that way. The other half of that equation is unit testing. If I document and I have a test to verify my code, changes on down the road are much easier to do with confidence.
I find people who say that code should document itself are full of it. I write programs because I need to manipulate inputs in a non-obvious way. I document it because it is non-obvious and I don't want to have to waste time figuring out why I did something a certain way 6 months ago.
You know what really pisses me off? People who believe code should be self documenting and therefore *REMOVE* all comments. I worked with one guy who actually setup scripts to remove comments from all source in the repository. He thought all of his code was self documenting too. He was wrong. Sorry, but I'm not a super genius who can immediately understand all the obfuscated functions and variables someone else thinks is obvious. Deciphering un or poorly documented code is a huge time sink.
"The avalanch has already started, it is too late for the pebbles to vote." -Kosh
I've looked at a bunch of code written by others in my years. Came across some complex code that said, "NOTE: This breaks 9/1/2014" with no further explanation. I have no doubt that it isn't correct.
After seening that comment, I started having fun with my comments in that product too. I added, "NOTE: Breaks in 2040, but I'll be dead by then." It was a bonehead 2 character year handler. After 2040, all 2 digit YY dates become 1940, 1941, ....
I'll be dead by then, I'm pretty sure.
Comments shouldn't be necessary except at the top of a file that explains the general purpose for the file/class. The code should speak for itself whenever possible. Descriptive functions/methods, classes and variables should be enough. Sometimes that fails for really complex needs so comments are required. I'm a believer that comments should explain entire functions - not a single line.
Functions should be shorter than 1 screen can display. Long functions are hard for our brains to keep track. Think about it - how many times have you needed to merge multiple functions into a single method - never. OTOH, you always need to split up functions into multiples - happens all the time. Somewhere around 10-20 line of code seem ideal for a function/method.
When writing the code, I know a spot is dodgy, and I can mark it as such.
It is a likely place to cause bugs. Why not fix it while writing? Usually there's no time to fix it.
So is it better to leave those out? Some corporate coding standards mandate no FIXME, TODO or XXX in the code. Thus people just remove them. Is the code better? No. Why? It takes a longer time to home in on the problem spots, as they are no longer clearly marked "HERE BE DRAGONS".
Put the comments there, and use your editor to hide them. Any sane editor can do that with a bit of scripting/tweaking.
Periodically this gets brought out, looks like it's time again:
http://www.fastcompany.com/28121/they-write-right-stuff
Fuck them all.
I'd rather not have code comments at all. I am working on your usual written-by-pieces-of-shit legacy code, and I have to deal with the following.
-Comments that only say who did what when. Jdoe, 2/7/2003. Yeah, that's useful, dude. //sets the TableDAO
-Comments that add no useful information, wasting tons of space. public void setTableDAO(TableDAO tableDAO) {
-Commented code! everywhere! Just adding to the bulk of the retarded thousand lines long methods.
And of course there's never any comment for the mysterious sections that may actually be useful. These assholes were mandated to comment their code, and they followed it to the letter of the law.
I spend a lot of time deleting these comments. No comments make for much more readable code.
What the fuck is going on on /. lately? This is one of many CS or programming related articles that have shown up in the past few weeks, and it's really ticking me off. I come here to read about Julian Assange, Apple lawsuits, and politics, not tedious minutia relevant to my job and life. Don't forget your roots, because I will ragequit if you guys turn this into a tech news website. Officially on notice.
In my code I have developed a certain style/guideline about comments
1) Always comment in detail the utility functions. They are the most likely to have obscure code, hacks, tricks, or otherwise confusing to read on first view.
2) Database functions should self document, both by the name of the function and a quick glance at the query. A function named Members_Load_All_By_Time( minutes, array ) kinda says it all.
3) Display functions get commented to break up sections; here is where navigation starts/end, here is where notes get displayed, etc.
4) Long If/Then/ElseIf/Else get one for each condition about why test for that specific condition.
5) If pulling in a feed, or otherwise getting a complex array/structure, have a comment block of what the input looks like. This could be an example of the XML, members to an array, or other non-standard information. Something to show what I'm working with.
6) If using a technique found on a forum or blog, include a comment to the URL/post, date it was published, name of author, and other info to get back to the posting. Not only to CYA in case of licensing issues, but check back occasionally to see if the author or a commenter has made an improvement. Or for me to submit an improvement I discovered.
As a side note, sometimes even better than comments is just good coding style. If the language allows it, use whitespace to your advantage; line things up, indent to show beginning and end of loops, and add blank lines to give visual breaks and convergence points.
Comments are there to tell you WHY they did something the way they did, not to tell you WHAT they did.
In my opinion, a two pronged approach of good commenting in the code and extensive testing make for a much more attractive package.
Is there some code that looks odd but accounts for edge case x? Write a simple comment saying as much, but write a test with the edge case in it. That way if someone hoses it, a test will fail.
You even have things like cucumber (http://cukes.info/) for ruby which creates documentation with the tests.
I like people who write "This is where the magic happens." Sprinkle some bitxie dust on a simple algorithm and poof...MAGIC?
Dave Winer has essentially worked solo on his code for the past 10 years. Why should I pay attention to what he says about comments? He doesn't collaborate.
As a mathematician who sometimes programs, much of my code is indecipherable to non-mathematicians and any degree of commenting won't change it. If you don't understand why there's an exponential function in that code for assigning probabilities to an event in the simulation, dumping an entire textbook into the comments won't explain it to you. Can I assume at least a certain level of knowledge so I don't have to write a textbook? Well, at the time, no - I knew the expertise of the person I was coding for, he simply couldn't grasp that. (He had told me so himself, too.)
If I'd been writing for people who have my non-programming knowledge, I wouldn't need to comment on that particular algorithm at all, it's pretty basic in the field. Should there be some comment left for people who don't know that discipline? Okay, sure - but honestly it won't explain it to them.
As has been said a few times, the principle reason for a comment is to explain why the code needs to be the way it is, not what it is doing. By this definition, a few things happen.
You get fewer comments in the code, because most code doesn't need explanation. Yeah yeah there are those pesky API calls that have to get called in nonsensical order and the fact that you're rounding down and not up because your ad campaign doesn't do partial credit to save money, or whatever other nefarious, legacy, or even sometimes malicious reasons there may be. Even legitimate code can be malicious.
But lets be real. This only works if people write sensible code to begin with. Code can be self-documenting. Those nay-sayers who complain that it cannot be simply don't know how to do it, or haven't yet seen a suitable example.
You don't need to write code that has 6 equations on one line. You don't need to write 200-line methods. You don't need to use variable names that obfuscate meaning, or worse, those that have no meaning at all. (int a,b,c,d = 0). You don't need to, but many of us as professional developers do. Why in the world do we do that?
I can spout all sorts of slander about being lazy and being macho, ignorance and horribly misguided job security, but i won't because it doesn't help. I don't care why we do it, i care why we should seek to write code that we can come back to a year later and just read.
Languages are pretty high level these days. The code they support can very nearly read like sentences. Why not?
I learned how to produce useful self-documenting code by doing TDD. TDD told me to write tests that describe the behaviour i wanted to achieve (not the implementation i was trying to test). I parlayed this into my code as well. Now i might have a class called calculator, with methods such as Divide, Mulitply etc. and tests which say Divide_Prevents_An_Exception_For_A_Denominator_Of_Zero() and Divide_Reports_Divide_By_Zero_Error() and other such things.
Why would i have to comment that? Does the compiler care how long my method names are? Is anyone reading those tests or methods going to need help to understand what is going on? Not likely.
Whether you believe you can truly write self-documenting code or not isn't relevant. I can't evangelize the benefits to non-believers. But how about just trying to achieve it? Even if you don't really succeed, you'll probably find your code a lot easier to understand even if you insist on putting comments in your code.
I'll bet you'll fall in line with everyone else eventually and find that comments aren't necessary, unless something unnatural is afoot. Then and only then, will you ever find a comment in my code.
nothing to see here..move along people. Just more nerd developers fapping at their egos
One issue I rarely see discussed are the different types of comments. Most languages and editors don't seem to differentiate between these common types of comments.
-Standard, inline comments //check for out-of-bounds /* send the user an email //0 indicates no fritz at all
* to let them know they've
* done something wrong
*/
int fritz = 0;
-Autodoc (or autodoc-style) comments, usually in class/function headers - whether or not autodoc is actually used /**
Given foo and bar object, produce woofObject by transmogrification
input foo int
input bar barObject
output woof woofObject
**/
function transmogrifyFooBarToWoof...
-Comment-out - code that is disabled by commenting /* here is some code we don't use anymore, but is here for reference
if (whatever) do something;
*/
-Todo comments (I tend to style these with #! or #? in php or //#? in other languages)
#!if the result is negative this will fail
#?should we be bounds-checking
Another annoyance with my editor (Eclipse, in my case, but most others I've tried also have this issue) is that I like to left-align my comment-out and todo comments for visibility - a habit that comes from COBOL, I guess.
I've only ever worked with one software engineer who, in my opinion, documented enough; I strive to match his standards in my own code but I know I don't always succeed.
Could you provide examples of what you mean, for the rest of us to learn from? Thank you in advance.
I don't think revision control has anything to do with it. It's a matter of taking the time to change the comments near a block of code when you change that block of code. Revision control neither helps nor hinders in this process.
He meant revision control like the proper business process of developing software and the procedures used to properly make revisions, and the adherence to or lack thereof; not the actual software used to implement it (CVS, etc.)
Knuth's CWEB has been around since the 1990's and it is everything one should want in tools for creating and maintaining proper code documentation. Rather than having comments take a backseat, become out of date or inaccurately reflect the implementation. The literary portion of software documentation is up front and coding is implemented to match the documentation. I will admit that what it does is a psychological trick, but it does seem to require less discipline to use and maintain a CWEB project than using code comments.
In the programming industry, I feel like there is very little "news" that is new and innovative. A lot of it seems like poor rehashes of earlier technologies. Be it CWEB, mainframe virtualization, LISP, Garbage Collection, etc. Most of this stuff seems to have been available decades ago.
^... which is utter stupidity. Only a wage slave would get the bright idea that loading themselves down with more and harder work is the way to profit. Never once does it enter into these clueless "programmers'" heads the idea of doing things correctly thus saving time and allow oneself to tackle bigger and harder problems, instead of always wading around in the muck picking up garbage. Fucking idiots. It's basically a reflection of our society as a whole, really. No big deal, it leaves the bigger, more challenging, and more interesting problems wide open for you and I to solve.
I have sometimes found this method ("Write comments, convert to code") useful.
Might be especially useful when discussing project requirements with non-technical clients. Obviously coders can't talk code with non-coders; therefore coders must use human languages when talking with non-coders.
-kgj
These comments about the visual relevance of comments is totally missing the point. The real issue with comments is that they lie. I've never seen a project use comments that doesn't go the same way: developer is all excited at first and committed to maintaining good comments in their code so they comment everything. Then it's time to debug and they start changing the code, but forget to change the comments. Two years later, new guy comes in and needs to make some changes to the project, tries to read the comments to understand how the code works, and at best winds up confused because the comments don't seem to agree with the code, and at worst ends up trusting the comments without checking the code and breaks stuff based on an incorrect understanding of how it works.
Just create yourself a new religion call Comment Driven Coding. ;')
But now that I think of it, comments could be avoid if you have well define unit test.
Anyway, I vote for little good comments instead of too much to be change when refactoring.
The "clarity of comment-free code" is pure, unadulterated bullshit.
If your code does not have comments (short of glaring syntax errors and obvious infinite loops) it cannot be debugged because there is nothing in human language describing what the code is actually supposed to be doing.
No amount of comments can replace full and proper design and implementation documentation. In fact the best comments are links to these documents. And don't go on about waste of time producing such documents, in over fourty years in the business I've seen plenty of evidence to support my view. Modern IDEs make it easy to update design and implementation notes and keep linked versions of these and the code in step, and multiple screens make it easy to have all relevant information in view at the same time.
Now get off my lawn and take your badly designed, badly written, and probably irrelevantly commented code away from my system.
nec sorte nec fato
The best comments are done with a speech-to-text converter.
Put a picture of some pretty movie star next to your screen (that shows your code). Pretend that she is just !fascinated! by you and your code. Turn on the speech-to-text so that everything that you say gets dumped into a text file. Pretend that you are talking to here and describe your code in all the detail that you can imagine. Describe everything. When finished, close the text file and include it with your source code. Way better documentation than any other method and faster also.
THis is weird, but it really works if your speech-to-text is working. Not 100% is OK, but at least 90%.
A while back I was looking through some source code for a linux device driver, one part said
"This is an ugly hack. I must have been on crack. Need to fix this soon"
If you're a good programmer, you comment, you comment well and you comment quite a bit. Period, end of frigging story. Anything else and you're shit developer, plain and simple.
Comments tell the story of the code. If you're one of those "the code explains itself" people, YOU ARE WRONG. The code tells you what the code does, and absolutely should be written as simply as possible to facilitate that, but it does NOT tell you what it's SUPPOSED to do, not WHY it's supposed to do it or HOW it arrived at its current form. Only comments can do that, and THIS is the stuff that professional developers know are most important.
Good commenting is identifiable by being able to pull all the CODE out and read the comments and be able to get the overall flow of the code, the overall picture of what's going on, without getting into implementation details. Yes, having to update comments along with code is a drag, but (a) good comments tend not to have to be changed just because the code changes, and (b) it's the price you pay for maintainability, which in a professional environment trumps all else.
Whether the comments are colored, collapsed, in a crazy font, spin and glow when hovered over, that sort of stuff is tangential. Writing them in the first place is what matters.
Let's stop debating comments already, ok? They're necessary, they aren't optional, and GOOD developers already know this. You shit developers can either get with the program or man the fryers at Wendy's because you shouldn't be working in this field if you don't get it.
This is one reason why "worknotes", to the extent that they are needed, should be maintained with the source code (i.e., in the same repository) even though the notes are separate files from the source code.
It should be impossible for the worknotes referenced in the source code to become unavailable while the source code itself is available.
In my experience with legacy code, most comments (if present) only bore a rather tenuous relationship to the code or the purpose of the code.
I've taken to treating comments as entertaining reading by the author(s) of the legacy code. Sometimes they foreshadow what's about to happen, sometimes they spoil the ending, sometimes they deceive, and sometimes they outright lie.
Code without comments IS a bit frustrating - but also freeing too. Without the comments adding chaos to the body of work, you can figure out what's going on without distraction.
Wrong.
If your the requirements for code change (or it is discovered that your previous unit tests didn't cover all of them completely and correctly), you must change the tests that exist to determine whether the code meets those requirements.
If your unit tests fail, you must change the code.
But you don't need to change the unit tests because you changed the code. That's backwards.
I've yet to see any place that does anything like unit testing at all -- whether in the bad test-last way or the good test-first way -- where the fact that writing unit tests takes time is not considered in planning and estimating. The good test-first places tend to be low-ceremony environments where the dev team does estimates which include unit testing as part of the overall development-time estimate, and the bad test-last places tend to by high-ceremony bureaucratic environments with top-down planning by management that explicitly breaks out unit testing. So, IME, this is generally false.
Let .. me get this straight... the linked article is essentially complaining about editor settings. most source code editors let you select the font, color, etc for each thing construct it recognizes... if the comments are not visible enough to you, edit one's editor settings...
perhaps it's a complaint on the default setting of an editor.
Good comments help capture what you're thinking; what you're trying to do with your code. That's far more important than the implementation. It's the 'why' not the 'how'. Anything that facilitates capturing the why is a good thing.
Case in point: regaining the knowledge of the Apollo program. they still have most of the designs of components, including multiple design revisions, but they never captured the reasoning behind the design changes. You can see that bolt moved a half-inch to the right, but you've lost why that move was important.
I started programming at age 12. That was back in 1980. I've been coding professionally for close to 20 years. I am a comment zealot. I'll tell you why too... I still maintain code that I originally wrote as far back as 1995. A whole lot of weird is introduced into a code base with that kind of lifespan. In a non-perfect world, deadlines, vocal clients, incompatible data organization, all kinds of things happen causing code to evolve in unexpected (and incomprehensible) ways. It's not optimal, and it makes me cringe when I see nice well thought out architecture get crufted up by some ugly kludge so we can ship on time, but it happens. So if you don't document what the heck is going on, right then, right there... Good luck 10 years down the road trying to figure out why you did some extraordinarily non-obvious thing... Comments augment code, good comments explain the "why" you did something screwy.
If you don't have comments you need to spend time reverse-engineering the code.
I suggest that it takes less time to update the comments than to try to understand code with no comments.
The most useful purpose of comments is to explain why something is being done, or being done in a certain way. In some cases (assembly coding, for instance) it can also be useful to have a comment explaining the overall algorithm.
Comments should also highlight any particular gotchas, possible areas of improvement, known shortcomings, etc.
handle comments perfectly. You can hide them, change the color, run reports on them, use a template.
And yes, comment your code.
Data, initials a description of what you expect it to do.
Update with changes, because regardless of your ego, you are capable of putting a small change that doesn't show up for a week..or more.
The Kruger Dunning explains most post on
In my experience/perspective, it seems to work best to, at a minimum, try one's hardest to write code that is as efficiently encapsulated as possible and self-descriptive using well-named functions, parameters, classes, methods and variables, along with clean formatting of processing structures.
And then have a "trigger" as to whether a comment is necessary. Such as:
1) Are you doing something so arcane that another programmer wouldn't easily figure it out? Arcane things like unusual business logic that a reader of the code might not be expecting. Of course, one way to solve arcane code is to find a way to further simplify the code, perhaps breaking it up and/or using functions.
2) Is there a limited use for what you've written? Is it necessarily partially hard-coded for now?
3) Is the code section really long so that commenting can better guide the reader around the monstrosity? (or you can break it down and/or use functions to clarify)
4) Does the code do something really special that you want to point out? Does it have a potential for re-use?
5) Have you had to write an anomaly workaround or something kludgy that for some reason needs to await further review and rewrite but also needs to go into production ahead of that time?
6) If a common function library, are the purpose, parameters and return value fully explained? Similar applies to common classes.
There may be other triggers I can't recall off-hand.
Even though IDEs can hide comments, they, like code, still have to be maintained. So efficiency of comments is important, although usually not nearly as important as efficiency of code.
Steve Magruder, Metro Foodist
I have developed/maintained software for some bigger companies like our National Trains' Company.
I came across code that was done by some guy comming from the java eco system.
It seems to me, like he was an amateur OR that java folks do lots of useless commenting.
Not that there were more commenting lines than code lines, but the comment itself was that trivial that it just obstructed reading the code.
Consider something like this (actually i cannot post the real function, but its pretty much the same triviality): /* /* if num1 or num2 is smaller than 0 return -1 */ /* add num1 to num2 and return */
* if num1 or num2 are both greater than 0 add num1 to num2 and return the result.
* in all other cases return -1
*/
int addNumIfPositive(num1, num2) {
if(num1 0 || num2 0 ) return -1;
return (num1 + num2);
}
Why would one need any comments at all?
Code comments should be helpful for people that maintain or extend existing functionality and not for people who cannot read code.
Comments should be used on code sections that are not clear from reading the code. eg some series of function calls, or exception handling, but PLEASE dont use them on trivialities or for people that cant read code!
I think if you have time to comment on comments, you obviously do not have enough work to do. However, commenting on comment comments is acceptable provided the comment on comment comments is thorough and engaging.
As I said, the file I got the code from is e100.c See lines 494 through 571. Also, there is no real difference between a .h and a .c file for the purposes of our discussion since both are comprised of two fundamental atoms, to wit comments and code. The purpose of a header file is to include certain elements of a program's source code that will be reused by multiple files so that they can share interfaces and data structures. When no such sharing is desired they don't belong in a header file. In this case the struct has file scope, and putting it in the .c file ensures that nobody else can or will manipulate elements of the struct. This is done in order to properly implement abstraction.
As you can see, what you don't know about what you are doing could literally fill a book.
I know exactly what it is, but you seem to be the one who cannot understand simple English. My statement is that the best thing one can say about your knowledge of software engineering is that you would probably do well emptying trash, mopping floors, and cleaning toilets.
Guns don't kill people; Physics kills people! - John Lithgow as Dick Solomon on Third Rock From The Sun
Lol,
an empty file also is a valid c-file. And contains no code.
Yepp, I did not read up the old posts so I missed the fact you got your example from a .c file and not an .h file.
Nevertheless most .h files compile to nothing if you compile them.
So the point about knowing nothing is kinda ridiculous ...
Meanwhile I lost track what the point of the argument was ...
You want to comment everything except the stuff that needs comments? (what exactly does that "cb" field mean in your code?)
I like to comment as few as possible ...
That makes me a janitor?
Sorry, in my country janitors don't clean toilets, mopp floors or empty trash ...
Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
Was there a point to be made, other than that you don't know better than to start a sentence with a conjunction?
It is not my code, first of all. It has been vetted by numerous Linux kernel programmers. That being said, it is a Command Block. This is something that you would know if you were writing an Intel Ethernet driver. It is completely obvious. It is not the kind of thing you would put in a comment any more than you would add /* i is an index in the for loop */.
Well there is room for innovation and improvement then! ;-)
Guns don't kill people; Physics kills people! - John Lithgow as Dick Solomon on Third Rock From The Sun
It is not my code, first of all. It has been vetted by numerous Linux kernel programmers. That being said, it is a Command Block. This is something that you would know if you were writing an Intel Ethernet driver.
If my boss assigned me tomorrow to work on an ethernet driver: I would not know that.
Rest for the other fields in that structur.
Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
On the exceedingly long list of things that you dont' know, that you would need to know in order to successfully modify the e100 Ethernet driver, that is the least of your worries. For example, you don't know that you shouldn't be starting by changing the code, and that by the time you knew enough about Intel Ethernet cards to actually start changing code it would be patently obvious.
The hilarious thing as that you started out claiming no commenting was necessary, and you are finishing up by complaining that things that need no comment are not commented. You really are a hilarious guy. Thanks for the laugh.
Guns don't kill people; Physics kills people! - John Lithgow as Dick Solomon on Third Rock From The Sun
I did not say "no comments are necessary". You put that into my mouth.
I always said, and repeated it: classes need a comment (for the class itself and for all their fields). A huge C-struct is nothing different.
I also said: all "public" methods of that class need to be commented (what is the method doing) and their parameters.
A c function that is supposed to be called (in other words is public) is similar to a "method".
Beyond that your code should be so clear that no further comments are needed. The rare exception you pointed out is something like allignment, I assume there are more.
In your case, nearly every field of that structure is a miracle. (Yes, I can conclude a little bit from it).
For example, you don't know that you shouldn't be starting by (1) changing the code, and that by the (2) time you knew enough about Intel Ethernet cards to actually start changing code it would be patently (3) obvious. ... I only need to understand what is going wrong
1) if I see the error, I make a breakpoint there, and yes I fix it.
2) I don't need to know EVERYTHING about e100 cards
3) does not matter, and I doubt it. I fixed enough bugs in commercial systems where it was important to finds and correct the bug in hours or less
A line like max = a b ? a : b; is obviously wrong, as "max" indicates I want the maximum. A line like m = a b ? a : b; looks right at the first glance ... you only realize later that malloc(m) allocates not enough memory.
Sorry, the time where c variables should have arcane obscure names are over since the compilers accept identifiers that are longer than 8 bytes.
To phrase it with some famous words: you may disagree but you would be wrong.
Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
ROTFLMAO. Thanks for that one. The fact that you think you can properly fix a bug in a commercial product in less than an hour makes clear exactly how firmly you fall into the clueless category. That is precious!
No. A line like max = a b ? a : b; makes it clear that you can't write a single line of C code that would actually compile.
So I've spent enough time going back and forth with you while you prove your incompetence over and over again. It is time for you to go on being happily clueless and wreaking havoc wherever you type, completely unaware of what a complete hack you are. Have a nice life.
Guns don't kill people; Physics kills people! - John Lithgow as Dick Solomon on Third Rock From The Sun
Lol,
the only one who is clueless is you, otherwise you had guessed that the "less sign" was eaten by the slashdot html filter.
If you consider me incompetent then come to my place and write a bit of code ;D If you would wrote code like the one you had posted you will be gone in no time.
Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
Again, you prove my point. You are unable to review your post before hitting submit, and unable to use an example that will render properly to make your point. This is a clear indication that you are > (i.e. more than) incompetent.
You work at a place that hires incompetents, so there is no chance I would even take the job.
Guns don't kill people; Physics kills people! - John Lithgow as Dick Solomon on Third Rock From The Sun
Well, as often as you use clueless ans incompetent it is obvious those attributes apply to you :) be happy with your constant insults ...
Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.