Web Development

Assist future developers by writing comments and clean code

Tony Patton explains that thoroughly documenting your code either through written documents or code comments helps you and provides future guidance for developers working with the code.

I have preached about documenting code countless times with fellow developers, but I recently unearthed a strange fact: Many developers don't consider JavaScript or HTML coding, so they rarely document such code. Thoroughly documenting your JavaScript code either through written documents or code comments not only helps you, but it also provides future guidance for developers working with the code.

Document your code with comments

Written documentation is good, but I still like to include documentation in the actual code—just in case the written documents cannot be found. Documenting your code is also good practice, and it is easy to do on-the-fly as you are coding. Some languages like Java and C# provide special documentation features.

JavaScript does not include such features, but you can easily include documentation with comments. There are two ways to include a comment in JavaScript:

  • The /* (start comment) and */ (stop comment) character combinations allow you to include multi-line comments, so everything between the start and stop comment indicators is not executed.
  • A single line comment is created with two backslash characters (//). Any text after the two backslashes is ignored. These comments may exist on their own line or at the end of a line of JavaScript.

The HTML sample in Listing A includes JavaScript that demonstrates the use of both techniques. It is a simple HTML page that displays a message box when the page is loaded, but it includes plenty of documentation. You may prefer developing the next cool trick, but some of this time can be devoted to documenting your code. After all, great code does not necessarily innovate, but implements in a clean and accessible manner and keeps maintenance easy.

Weekly development tips in your inbox
Keep your developer skills sharp by signing up for TechRepublic's free Web Development Zone newsletter, delivered each Tuesday.
Automatically sign up today!

There is a point where you can include too much information when documenting your code. After all, each and every line of code does not require documentation. Here are a few guidelines for documenting your JavaScript:

  • Document all functions including their purpose along with description of its parameters and return value (if it exists). My simple example includes such information. I like to include the author and date, but you can choose to include this in the page documentation (since it's probably the same for the entire page), but that is the developer's and organization's preference.
  • Document any obscure or complex code to help future developers understand what it is doing.
  • Code changes should include a line detailing the change, as well as who made it and why. This can aid debugging and in tracking down developers.

These guidelines are not stringent and may vary among organizations; the key is to be consistent so all code follows a set approach.

Write clean code

Documenting your code is just one aspect of easing code maintenance. Another way you can help fellow developers is by keeping your code readable through the following additional techniques:

  • Proper indentation
  • Self-explanatory variable and method names
  • Consistent bracket placement for script blocks

While the specifics of code-display within the TechRepublic.com site negates indentation in the sample code in this article, you should indent your code according to developer and/or organization preference. Also, you will notice the variable and function names in the example are rather self-explanatory, so a developer could ascertain code functionality without accompanying comments.

The last item on the list is related to the placement of braces ({ and }) that enclose code blocks. I've worked with organizations that prefer the opening bracket on its own line and others where the first bracket is on the end of the first line of code in the block. The sample code uses the former approach, but the function could easily use the other technique as demonstrated by the code in Listing B.

HTML comments

In addition to JavaScript comments, you can include comments or documentation in HTML with HTML formatted comments. HTML comments use the following formatting:

<!-- This is an HTML comment -->

The sample code includes an HTML comment at the top of the page. Comment placement depends upon the project, but they can easily be used to omit portions of the page from loading/execution to assist with debugging.

Helping others

Developing readable code is a continual process that you should follow on a daily basis. After all, documentation is abhorred by most developers, so going back and documenting code after a project is complete is not on anybody's wish list. You can include comments and consistently format your code to assist future developers charged with maintenance or changes.

Miss a column?

Check out the Web Development Zone archive, and catch up on the most recent editions of Tony Patton's column.

Tony Patton began his professional career as an application developer earning Java, VB, Lotus, and XML certifications to bolster his knowledge.

About

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

163 comments
jimcakalic
jimcakalic

Clean code is one thing, consistent indentation (although code formatters usually take care of that), intention-revealing (and consistent) names, well-composed methods. But comments? Really? In 25 years of development in multiple languages (Microprocessor assembler, Basic, Pascal, COBOL, SCOBOL, TAL, C, C++, C#, Perl, Python, Java, Groovy, to name a few) I have rarely found code comments to be helpful. One of the first things I do when I start working on code is remove comments about what the code is doing. My experience is that such are typically wrong and misleading. They don't help me read the code. They get in the way of reading the code. Particularly unhelpful IMO are the silly getX, setX method javadoc that says "Gets the value of X" and "Sets the value of X". That's just a waste of time to type and to read. As I remove comments I also vigorously rename variables and methods because my experience is that people who find it necessary to express their creativity in comments don't have any left for good naming. The only comments I leave are those that reference requirements and those that describe something (design rationale, side effects) that cannot be gleaned from reading the code. One form of documentation I invest in heavily is unit tests. I would much rather inherit code that had significant unit test coverage than one that was heavily commented. How about an article on "Assist Future Developers by Writing Tests"?

MarkB29681
MarkB29681

I'm afraid we are getting side-tracked and terribly missing the point. Comments should state the INTENT of the code -- that should never (or at least, very rarely) change, and if it does, it's indicative of a whole new version probably. (Example: "This function transfers money from checking to savings account"). Code may change to fix bugs when that prevent the procedure(s) from actually achieving the goal stated in the comment(s). Now, if the GOAL was wrong from the start, that may necessitate a complete rewrite anyways...

sepahram
sepahram

I agree with Tony Hopkinson and those who think there's no need to "repeat yourself". I think the only part of code that may need some comments are (as the author put it) obscure and complex parts. BTW, keeping comments uptodate is a frustrating job. That's why they get obsolete after a few days!

deepsand
deepsand

In the real world, particularly that of big business, change is, [b]by necessity[/b], the norm. Documenting the [i]intent[/i] of a routine alone is far from sufficient. Without knowledge of the [i]content[/i] of the variables used within a routine, & of the parameters passed between routines, the only person who can effectively and efficiently modify an application is the original author.

Tony Hopkinson
Tony Hopkinson

CheckingAccount.TransferTo(SavingsAccount, Amount,TransferDate) This is all we are really talking about, don't comment the intent, code it.

ricardol_limon
ricardol_limon

I agree with mblackston, comments are to let clear what is the intention in that section of the code so a newbie in the staff or someone that needs to find or solve a bug knows where in the process hes correcting or debuging. Now i want to make a question on to the forum... What do you qualify or mean as "C13an C0d3" ? I have walk into people that bloats of writting clean code and for me is just like watching the linux matrix screensaver going WTF

deepsand
deepsand

Some languages, like COBOL, lend themselves quite easily to self-documenting program statements, [b]if[/b] the programmer chooses the variable names carefully [b]and[/b] follows a consistent naming convention. At the opposite extreme are machine code & assembly languages. Given the current widespread use of function libraries, where I/O parameters are, from the view point of the function, faceless by necessity, no program using such can be wholly self-documenting.

JimmyF
JimmyF

Unfortunately, what is clearly obvious to the person writing the code, is not always so obvious to a junior programmer who comes along to maintain it a year later. I often find that I write my best comments only after I am actually trying to maintain my own code later and realize which things I've already forgotten, or which conditions cause problems when debugging. It was all so clear when I wrote it... This is also a place where having another programmer read over your code can be helpful. If they can't figure it out, without you telling them, then it should be commented.

DPitz
DPitz

Good comments to even good code is essential. I agree that it is not necessary to write a comment that says "Add 5 to G" followed by "G = G + 5". Comments should be used smartly to describe why a particular approach was taken, what boundary conditions the code will or won't handle, etc. It's not just the line by line comment that is necessary, but moreover a "here's why I did what you are looking at". I say this with a lot of experience of maintaining my own code and maintaining the code of others. I deal with code that's a few hours old and code that's 20+ years old. Well written and well commented code can survive that long. And, it's easy to maintain because the developers took the time to document their assumptions, the limitations, etc.

Tony Hopkinson
Tony Hopkinson

is a refactoring opportunity. Code at it's level (think top down) should never be complex, making it or leaving obscure is just a recipe for disaster. So the first comment should be //Refactor this ASAP. Then you can use the javadoc stuff to report a start for your workload for the next iteration.

Slayer_
Slayer_

It was terrible, the original coder tried to do that separate GUI from data thing, so there is a bunch of events across classes and stuff making it near impossible to follow. A simple comment saying where the event code was would have saved me a lot of effort.

Tony Hopkinson
Tony Hopkinson

Course in his example it depends on what you mean by intent. //This routine transfers money between accounts. // This routine loads account1 from the database substracts amount, saves the account, loads acount2.... The top one given the routine is called MoneyTransfer is spurious, the second is plain daft. Chneg the code you have ti cgnge the comment and they both have the same amount of meaning.

xmetal
xmetal

Though there was a major revamping of our product in 1999 a lot of the core code for our Windows application goes back to the late 1980s. In total we now have over 500 source files and somewhere approaching 100 different developers have worked on it in total over the years. Most of the really old stuff is core to our product, being called by most and close to all functions (rendering, etc). Much of this old stuff is not commented well. We pray we never need to touch those portions. Comments describing the intensions of a particular code chunk can literally save hours of time, particularly people new to that portion of code. The hidden meaning here is that my code needs to work with other people's stuff, some of which may have been written 20 years ago. If we went through and "fixed" everything a new piece of code relies on just to allow the new code to be "clean" that would be both dangerous and a waste of time for both the developer and QA who would need to needless regression testing on things that have already been tested long ago. Most of our code is "clean" but the old stuff is written using old fashioned methods (ie: it does things that Windows APIs now give you for free) but it works so why "fix" it? This is my world. I suspect other people arguing against comments are working on far simpler or younger codebases with fewer colleagues involved, perhaps less turnover, fewer restrictions on backward compatibility and perhaps most importantly -- no respect or care for those that may follow after you.

Tony Hopkinson
Tony Hopkinson

The style of how you do it will change but C, C++,C#, VB, Pascal, Ruby , Python all can. Some languages like Perl prize terseness and (obfuscation in my opinion_, but apart from specific additions such as regex you can code readably in that as well. There are of course always limits, either syntactic, semantic or practical. But simply striving for readable code, will reduce the burden on code documenetaion, given how traditionally crap we've been at that as a profession this can only be a good thing. It's not a coincidence that we get swathes of spurious or misleading comments littered all of the code, it's because as a method of documentation it sucks.

Wayne M.
Wayne M.

Perhaps you could specify the languages that preclude clarity of code and perhaps explain your reasons for stating that most programs would require comments. I have worked with C, C++, VB, and Java, and each of these display the characteristics I feel are necessary to write clear code: a large maximum name/token length and the ability to call subroutines. It's been a while since I've written assembly, but, as these characteristics also apply, I think it may be feasible in assembly as well. It may be my own lack of experience, but I have never seen program development done directly in machine code. The point about function libraries escapes me. While I agree that many libraries are some of the worst offenders in propogating poor naming conventions, I have only seen two standard approaches used. One, create a shell around the library to permit replacement - in this case, the shell names are as good as you want to make them. Two, leave the library calls undocumented and expect developers to know or find the details elsewhere. For example, in C code, I would never expect to see a comment describing the operation of getchar() whenever it is used nor would I expect that it would be contained in any of the programming documentation. Poor library naming conventions are rampant, I just have never seen a mechanism other the a shell used to address this problem. General statements are nice, but once one gets down into the details, I have found that anyone who can write a clear comment can write code that duplicates the comment. Unclear code is not really improved by placing comments near it. Rather one needs to take the responsibility to restate the code in a clear manner. I am ready to entertain arguments to the contrary, but only if accompanied by specific examples, i.e., commented code that cannot be adequately replaced with clearly written code without comments. Please, provide supporting evidence for any assertions made.

Tony Hopkinson
Tony Hopkinson

biggest difference in our thinking. I would try to refactor first. If for various reasons you can't make the code understandable now, then you have no option but to comment. This is why I treat comments as a failure, not necessarily a personal one, but a failure of the process.

Tony Hopkinson
Tony Hopkinson

boundary conditions or merely documenting them? If that latter, I've seen that approach fall over big style on many occasions. Enforcing the boundary conditions either through an assert or an exception is the tack I take. Returning things like minus one I only use on things like indexOf methods in a list class, as you can almost guarantee that the next method you call with that return value will fall on it's arse. I try to avoid doing even that though. I've been around a wee while as well and the return an error code scenario so popular with c developers because it did not have exceptions, was proven to be a collosal failure in the real world. Not because people failed to return fail but because people failed to test for fail. If the approach isn't self evident based on the context, by all means comment it for now. Don't forget to add it to your list of things to refactor though.

Wayne M.
Wayne M.

Never, ever rely on a comment to enforce a data constraint. Doing so almost ensures that a software error will occur in the future. Failure to actively validate data constraints has led to NASA vehicle losses through numeric overflow and to security breaches through buffer overflow, to name some more spectacular failures. If a developer identifies a boundary condition in code, it is incumbant upon that developer to write a data validation guard that calls the standard system error routine and second to ensure that a test of the boundary condition is put into place. If the developer is in a test first design house, he would write his own test, if he is in an independent tester house, he must inform the testers of the condition. The developer is responsible for both ensuring that a defined error handling process is called for invalid data to handle current requirements, and to ensure that an explicit testing process is in place to ensure that changes to the constraints are properly tested in the future. This is a terribly important point and I hope that if one does not learn anything else from this discussion, that one realizes that using a comment to identify a data restriction is not a sufficient response. Never write such a comment and if one encounters such a comment in code, then replace the comment with a data validation guard and ensure the operation of the guard is tested.

sepahram
sepahram

I counldn't agree more. Although, there's always complex code out there, and when you have such a thing, your've got to explain it.

Wayne M.
Wayne M.

To continue the conversation, I have started a new branch at level 1 below. As time and interest allow, I will opine on comments, documentation, and project management.

Jaqui
Jaqui

The definition of between self documenting code is that even a comment is not needed. And as I stated, any real application will not be self documenting, it is to complex. a comment describing what a function does just before the function code is all the commenting that is needed. if the code is not clear, then the code needs to be rewritten. what defines clear code for this evaluation is the best question. I say that if an beggining to average programmer cannot understand the code then it's not clean / clear code. If Porject Managers were to have at least the basics of programming in the language being used, then they themselves could be the average programmer that reads the code to test for clarity and cleanliness. [ besides making it easier for them to get the project requirements across to the developers, and get the developers issues across to the client and the rest of the management team ] I don't think a Project Manager has to be a programmer on the team, but having at least some programming skill will not hurt the project. and as Tony said, have them required to provide extremely clear comments on everything, going to the point of over commenting for a couple of projects, then the teams will get the idea about what commenting is truly needed and where to put them. External documentation includes what Tony detailed, plus the end user manual, installation guides.... I really think that the development teams should be kept together for several projects, not put together on an ad-hoc basis. This would actually improve the performance after a few projects, since the team members will have a better understanding of each others strengths and weaknesses and be able to work with each effectively. like putting the people that can churn out good quality code on writing the code, those that can write clear comments on commenting it, those that are better at debgging doing that.. so that you are able to get to the testing stage of the project faster, with fewer issues. With the current typical style of teaming up on a per project basis the developers do not get this type of knowledge for years of working together, by making more permanent teams they will get this knowledge in months.

Tony Hopkinson
Tony Hopkinson

To me this should show the basic structure of the application. A few squares, circles and arrows and some labels usually does this. Sort of a process diagram, preferably using the same jargon. Documented project templates. Code here, resources there blah blah. Standard layout template. database layer source files prefixed with DB, forms with fm logic with bl. Document the exceptions on top of that. The idea being you give the next developer some sort of clue where the code is going to be. For instance if every form has got a method displaydata, you'll have a happy bunny working for you. Having him wade through 15 well commented, cleanly coded event handlers and they will think you are a muppet. Do this across all similar applications you produce and you'll get a measurable boost in team performance. So much so they will police it themselves. Getting code documentation right however you choose to do it requires some effort. If you want your coders to do it, it's got to be done in a way that realises them immediate benefits, ie during the project, not this after it rubbish that hardly ever happens.

Wayne M.
Wayne M.

Please describe the information and a suitable means of communicating that information where the source code is insufficient. Note the original article was focused on comments; if we are expanding the context, please define what comes under the category of "documentation"? I would also question whether the scope of someone being "able to have a full understanding of the program" is feasible nor necessary of anything beyond a classroom exercise. The purpose behind modularization, coupling, and cohesion is to break a program into individual parts that can be understood to the depth necessary. One can have broad, generalist knowledge of a program, or very detailed knowledge of limited parts. Having detailed knowledge of of the entire program becomes impossible as the program size grows. Will programmers continue to write code that is less than clear? Yes. The question, however, is how to address it. I assert that it is far more beneficial to have the programmers clarify the code rather than apending comments or writing text in a companion document. Will programmers believe code is clear when it is not? Yes. Given this belief, however, it is difficult for them to determine what to comment or document. It is only the realization that the code is unclear that defines a need for either code improvement, comments, or documenation. Why am I a hardliner on this? Because software is not a novel to be read for fun. The people who follow will have been asked to affect some change in the operation of the code. They must go in and change the code and only the code precisely specifies what the code does; the comments and documentation are only approximations. Developers and management need to take responsibility for ensuring the code is clear. As noted above, "If the code can be fully self-documenting, then it seems logical that that's the way to go." It is only fair to ask those who believe otherwise to cite some specific examples why code cannot be written clearly.

Jaqui
Jaqui

I've only ever seen one program where the entire code was self documenting. with no need for comments or additional documentation. the ancient applesoft basic language and the basic hello world. [pre] 10 print "hello world" 20 end [/pre] anything more complex will never document itself fully, though that is a good goal to strive for. as soon as you start positioning output, or use a single loop, you have made it less likely that it will document itself. add a conditional statement or error checking and you guarantee it will not document itself.

deepsand
deepsand

If so, quick, lock the doors, before they get away. I long ago observed that those who do nothing but crank out code are so narrowly focused that they are generally quite incapable of allowing of the possibility that there is any other person who could legitimately find their work lacking in any regard. Some of such have made their presence here, announcing their arrivals with claims such as "all coding can be made to be fully self-documenting" and "clean code is always understandable," with the implied, and to them self-obvious, conclusion being that if they can attain such a lofty goal then those who cannot are inferior to them. To them I would offer 1 simple challenge - do it in APL!

Tony Hopkinson
Tony Hopkinson

I continue in my brave attempts to do so though. If you use comments to explain obscure code when you could make it clear then you are creating problems not solving them. If you assume that because you can understand your code now, you or anyone else will be able to understand it in the future you are creating problems. There's much more than annotation and good naming practices to writing maintainable code. Adherence to standards, design templates, technical ability, familiarity with the environment all come into play. I'll use any technique to make my code more readable, which one I use is a practical decision though not a theoretical one. Part of that practical choice is unfortunately far to often one of resource. 'Self documenting' code is way of addressing some of the problem from the get go that does not inherently consume resources.

jmgarvin
jmgarvin

I've seen a TON of "self documenting" code that is neither self documenting or readable. Too many coders think clever hacks and gimicks are fun for the new guy to figure out. It isn't fun, it's a total waste of time. Sure, I can write a C program to parse your directory and assemble the buffered characters into hello world, or I could just print it to the screen with the typical printf...

deepsand
deepsand

If the code can be fully self-documenting, then it seems logical that that's the way to go. [b]But[/b], if that is not possible, then it also follows that, if another (or yourself at some far removed date) is to be able to have a full understanding of the program, there must then be some sort of additional documentation provided, to which comments are quite well suited for relatively small annotations. In the event that neither the code nor reasonably terse comments will suffice, then external documention is called for. Those who here irritate me most are those who insist that it is [b]always[/b] possible to write fully self-documenting code. I suspect that their experiences have so far been limited to a very few, possibly but one, language and platform.

Tony Hopkinson
Tony Hopkinson

after an initial splurge not many of the you must comment everything boys have come back. None of the line by line or pseudo code enthusiasts have, which is where my initial reaction came from. Both those habits drive me mad. Must've convinced them, even the ones who thought I was some newbie who once wrote a macro.

deepsand
deepsand

Which, of course, is of little help if the code itself is not adequately self-documenting.

Tony Hopkinson
Tony Hopkinson

The content of an admin script is code. If you had one piping executables and using parameters would you comment it? use the long -- form of the parameters? or simply rely on the fact that no one who couldn't figure it out should be anywhere near it. Regex is probably one of those places you really need a comment and very rarely get one, and you have to generate a good pile of dandruff to verify the comment and the expression match.

Jaqui
Jaqui

it is, to be specific, a code snippet. so it is code. I tend to use less powerfull tools instead of regex just for the ease of reading it. 25 lines of code are far easier to read than 1 15 character regex. :D

Tony Hopkinson
Tony Hopkinson

It could have had a readable interface, but the people who came up with it were more interested in extending the lifetime of their keyboards than their code.

Jaqui
Jaqui

is regex readable? not to me, I have to work my way through it and decipher it. yet for a lot of people it is readable. so now we have to define what is readable. :D

Wayne M.
Wayne M.

I have maintained old code bases, one being an embedded C system that had been acquired from a different corporation and extesnively modified and enhanced. I wouldn't estimate that 100 programmers touched the code, but the actual values was likly well over 50. I've found that poor organization, structure, naming conventions, and implementation cannot be commented away and that is why I am so adamently in favor of clean code. It is quite contradictory to excuse oneself from writing clean code because "that would be both dangerous and a waste of time" and then complain that previous writers did not provide clean code. It is time to actively address the cleaning up of code. If the old code base is stable, then simply wall it off and focus on low risk refactorings. One of the basic ones would be to rename those functions whose intent is not clear. This would immediately start to benefit those new to the code, as the intent would be front and center everytime the method was called, not buried in some comment somewhere below. Another step to take is to begin automating those regression tests. If my memory serves correctly, late 1980s code would be MS-DOS or pre-Windows 3.1 at best. With Vista looming on the horizon and probably requirements to maintain backwards compatibility with a list of old operating systems, one needs to get away from manual testing. There is a growing set of automated test tools, many for free, available at http://www.xprogramming.com/software.htm I have maintained old, large code bases and I suggest that if one wants to show respect and caring for those who may follow, then write the clearest possible code, clean up unclear code when it is found, and create create an automated test suite so that one knows whether the code is working, instead of "pray(ing) we never need to touch those portions".

bgersekowski
bgersekowski

Comments can lie. Comments can forget to tell you important information about that critical bug that they patched on August 15, 1989. Comments can send you on a wild goose-chase thinking that a particular piece of code works one way and then you finally bother to read the code and realize it sounds nothing like the comment said. If you do have to touch that old code, even if it was nicely commented, are you going to rely on that and hope for the best? IMHO, comments are a poor choice for this purpose and at best will give you a false sense of security. What you really need is an automated test suite. I realize that old legacy code that wasn't built with automated testing in mind can be exceedingly difficult to test. I've come across that problem on several different jobs, and lately, on a seemingly daily basis, but I'd suggest starting to think about how you might move in that direction if you haven't already. Once you start thinking about how to build automated tests, even if there aren't nice tools and frameworks that you can easily just plug in, you'll start to find that you get more and more ideas as you go, and over time, you can test more and more. You start to write code so it's easier to test, and in a few years, maybe you have a nice structured approach to building automated tests, and maybe you have enough test cases so you have at least some degree of confidence to make some changes to that old code because of some new change request that came in. Comments can lie. Tests don't. You either pass or fail. Sure the test could also be wrong, but how is fixing that any different from fixing a bad comment? At least the test provides me some value by telling me when my bonehead changes broke the product. A comment will never do that for me. Sure, there can be gaps in my test coverage, but if we get a bug report, that will identify such a gap, so I can add a new test that will for now and forever tell me that this bug is fixed now, and will remain fixed in the future. Adding a comment provides no such guarantees. With regard to the types of teams I've worked in, I've worked in large teams with high turnover, small teams with high turnover, large stable teams and small stable teams. I hold the attitudes I have specifically because I often *am* one of those who follow after you, and I do care about those that follow after me.

Tony Hopkinson
Tony Hopkinson

I'm currently working on code, parts of which were originally written for dos. The code is littered with useless or misleading comments. The design is now wholly unsuited to the requirements, if indeed it ever was suitable. I have serious doubts about that, but I'm not prepared to point the finger and question their professionalism, because I wasn't there. Refactoring is 'too risky' and would require too much testing resource. Re documenting the code would probably take longer than rewriting it and it will still be expensive to maintain. Whichever process you choose to document the code with, unless the business allocates the effort to maintaining and policing it, you will fail. As soon as they feel under pressure, quality and documentation are the first casualties. One of the reasons for going for readable code and understandable designs is they reduce the overhead for code documentation, and so give us more chance to help out the next developer or even ourselves in six months time. Hopefully that will clear up your misconception! I have got a budget for rewriting now, I intend to end up with maintainable code, because the environment I work in is driven by legislation, change is mandatory and policed Mer Majesty's Revenue Collectors. Given how heavily jargonised the artifacts are and that the definition of the jargon can change twice a year and that when it does the old definitions are still in force for past years.... Well you can see the problem. I'm looking for another way, whether the comment everything method failed from a technical or qualitative standpoint I'm not prepared to guess. Without any doubt at all, it failed from an operational one. Hmmm, feeling a Monty Python sketch coming on. You think thats' bad. I .... LOL

deepsand
deepsand

If the code can be written so as to be completely self-obvious, then by all means make it so; otherwise, comment it. When in doubt, comment; otherwise, you may be the one wishing that you had!

Tony Hopkinson
Tony Hopkinson

Do that and they'll invent a new Nobel prize and you'll deserve it as well. Worked in Fortran and Cobol, never Algol, too young (LOL). Add comments when you can't make your code self documenting not instead of is all I'm saying.

deepsand
deepsand

It is important to recognize that those languages most frequently mentioned here are [b]not[/b] the universal set of all languages. For example, how many here use APL, ALGOL, LISP or any of their derivatives? How many have ever used Assemblers? How many are even aware of the great number of assembler sub-routines they routinely use, with no idea of what's happening "under the hood?"

deepsand
deepsand

PUSH & POP are example of functions that have [i]implied[/i] operands, which are data neutral. They each map to a unique machine op code that performs a specific hardwired function within the CPU. POP simply moves that element presently on the top of the Stack to a Register; PUSH operates in the opposite direction. Thus, the Stack functions as a LIFO stoarge register. Neither the Stack, nor the PUSH & POP commands operate directly on the data. As the contents of the Stack can be anything that the programmers desires them to be, and as a particular data element's position in the Stack is dependent upon the PUSH & POP operations that have been executed subsequent to said data element having been PUSHed, it is not possible to know what is being PUSHed or POPed with annotations supplied by the programmer.

Wayne M.
Wayne M.

If the particular language has a POP instruction that requires no parameters, why isn't POP self-documenting? What further information is required by the writer of the program? What comment or other documentation would you have the developer supply?

deepsand
deepsand

There is a difference between data, knowledge & understanding. Code is data, and no system can provide any more knowledge re. data than that which the programmer has provided. And, without knowledge, there can be no understanding. My programming experience dates back to 1958-59; over the years I have worked with countless languages. And, while I have always given my greatest attention to writing clear & straightforward code where possible (difficult to sometimes impossible when working with resource limited hardware systems, such as embedded ones), using self-documenting names for variables, procedures, functions, file names, etal., I have on more than one ocassion come to later regret the absence of a comment to jog my memory.

deepsand
deepsand

the POP operator allows of [b]no operands[/b]; the phrase [i]theParameterList[/i] would still be a comment.

deepsand
deepsand

all applications would have sufficiently abundant resources such that performance issues were of no import; however, in the real one, that is not always the case. 2 examples that spring to mind are embedded applications and those which, while accepting or requiring external commands, require a small footprint owing to physical constraints, such as the platforms in space craft. And, in such world, we would still have the functions of systems analysis and programming performed by different persons, each with sufficient time so as to ensure that the result was both constructed and written in a clean & straightward manner, with self-documenting code to the full extent afforded by the language being used (which would, of course, have been selected with such in mind), with well written comments wherever such was not possible; in the real one we rarely have the opportunity for such.

Wayne M.
Wayne M.

I think we can conclude with two points of agreement and one of disagreement. We seem to have agreed that using a wrapper around poorly named library calls is a feasible solution. We seem to disagree on the measurable performance affects of an additional function call. If the issue is execution speed, I would only optimize out function calls based on a measured execution speed issue. If the concern is executable size, again I would wait for measurements to make this decision. In the case of a large amount of calls to the library method (resulting in the program growth), I would contend it is far easier to manage the wrapper method name than to ensure that the comment is replicated and maintained for every calling point. Lastly, we seem to agree that poorly named methods are a major source of programming faults. This is one of the reasons I feel so strongly about the need for clear, expressive code, especially method names. The method name and signature should declare precisely what the caller is to expect. Side affects that are not clearly defined and boundary conditions that are not actively validated invariably lead to program failures.

Wayne M.
Wayne M.

Let me try this approach. Would you concur that, for an assembly language programmer, that the following is self-documenting, i.e., no additional comments or project developed documents are required to understand this statement: POP theParameterList What additional information is required and how might it be provided?

Tony Hopkinson
Tony Hopkinson

someone was messing about in machine code and didn't know what POP did. I would expect a comment on what the code expected to be on the stack though.

deepsand
deepsand

A content neutral function performs a given transform on the input data without regard to the information represented by such data. And, the same such function may be used a multiplicity of times within the same program to achieve different ends. While I will grant that the use of shells can address the issue at hand, it seems that the use of comments is more appropriate, in that it adds no overhead to the executable. As for the relevance of the language of the function, it is my experience that, in the absence of adequate documentation, a lack of understanding of the inner workings and hidden mechanisms of a function can bite you in the ass.

deepsand
deepsand

The fact remains that an assembly language simply [i]substitutes[/i] a more readily remembered [i]symbol[/i] for an obscure one. Therefore, each "line" of code remains but a single machine instruction. What, for example, is self-documenting about the "[i]POP[/i]" instruction?

Wayne M.
Wayne M.

There are so many different assembly languages and assemblers that it would be helpful to hear what specific issues where commenting is a superior approach to clarity in code. I can only list some common capabilities that are provided in many assemblers. Memory locations can be named with high upper character limits. Hardware register locations can be assigned descriptive names and values can also be given descriptive names. There is no reason not to know what specific bit is being operated upon. Subroutines can be given descriptive names. The stack offsets for parameters can also be given descriptive names. Some assemblers for register-rich processors (68K for example) allow aliasing of registers with descriptive names. Granted, assembly languages have specific keywords and operators, but then so does every other language that I am aware of. It is my expectation that anyone programming in a particular language should be knowledgeable in that language. I would feel it inappropriate to expect a developer to write a language tutorial in comments. It would aid the discussion if specific shortcomings that are resolved through the use of comments were provided.

Wayne M.
Wayne M.

I am still not seeing the point as to where commenting is to be a preferred approach to addressing libraries. If a library function call is sufficiently obtuse to bring confusion, then I repeat my recommendation to write a shell for either the method itself or for the entire libary interface. The clarified name is now available to be used in all calling paths. The alternative is to expect programmers to write a descriptive comment every time the library method is called and force those reading the software to switch from reading code to read comments to reading code. I fail to see how this is a superior approach. I fail to see what is significant about the language that a library might be written in, much less what a comment should be expected to provide to resolve the issue. While I agree that it is unrealistic to expect a developer to always write code that will always be perfectly clear to those who come later, I do not see how having comments improves the situation. It is realistic, however, to expect a developer to write code that he believes, at that moment, to be sufficiently clear for those who follow. I would be interested in hearing where this approach falls short in addressing poorly written library interfaces.

deepsand
deepsand

A) [b]Function libraries[/b] 1) [i]Non-standard[/i] libraries cannot be assumed to be quickly & easily decipherable to follow-on programmers. 2) While the main body of code may be well written and easily undetstood, the use of non-standard functions, particularly if written in a different language (e.g., assembly), can make for difficulty re. understanding and modifying the main body. B) [b]Assembly languages[/b] By definition, an assembly language uses [i]pre-defined[/i] mnemonics to represent specific machine op-codes. Said op-codes operate using pre-defined [i]hardware[/i] features of the cpu (e.g., specified Registers, Memory Addresses, etc.) which are wholly independent of the content represented by the underlying binary data. By its very design, a true assembly language neither knows of nor cares about the nature of the bit that it's moving about, and does not provide the programmer with the ability to express such nature by way of his choice of instructions from a fixed set. A developer should never assume that all who follow him will possess all that might be needed to render his code wholly transparent.

Tony Hopkinson
Tony Hopkinson

Complex applications yes, even compex functions. Complexity should not be apparent until you try and consider large portions of it in detail. To me if you have to do that, the code is obscure, the design is coupled to an unfortunate extent and or is too exposed.