|
Member 10088171 wrote: and despite best efforts issues with code comments are missed even by best reviewers.
So are code bugs.
But reviews are on-going and the next go around is another chance to correct it.
|
|
|
|
|
The comments I add are generally for myself, especially if it's a method, control or a class I've never used before I find it useful to help me understand the implementation, especially if I know I will be using it again.
I don't add the obvious <c style="color:green;">// Add two numbers // Return obvious value but I might add the <c style="color:green;">// Add X and Y here or the later result will have a phase offset type comments.
I should add that I don’t recall the last time when someone stopped by or emailed with a request for an explanation as to how my code works or how to use it. (They may question the methods but not madness. )
It was broke, so I fixed it.
|
|
|
|
|
I find both these standards odd.
I've been using RCG (Ravi's Commenting Guidelines™) for 20 years and they have served me and my teammates well. The guidelines are simple:- Strip out all code within blocks (except block delimiters - i.e.
if , do , for , while and switch code boundaries). - The remaining code and comments should clearly represent the method's psuedocode. If it doesn't, you need to add comments.
The coding standard about declaring all local variables at the start of a method is complete nonsense, IMHO. To maximize readability, local variables should be declared on first use within the block to which they're scoped.
This would cause me to rewrite your example method thusly:
private MyClass MyMethod()
{
int count = 0;
foreach (MyFileObj file in _myFileCollection) {
if (file.Name.Length <= 20) {
file.CopyTo(@"C:\SomePath\" + file.Name);
count++;
}
}
MyClass someObj = new MyClass();
someObj.FileCount = count;
return someObj;
} /ravi
|
|
|
|
|
That's an interesting concept, and I may try and adapt that style of commenting. It's simple to understand and I believe it may work nicely. Even if they don't want to change it, I may adapt it for my personal coding standards. Thanks for the input, Ravi.
djj55: Nice but may have a permission problem
Pete O'Hanlon: He has my permission to run it.
|
|
|
|
|
When Code Complete was first published there was actually a chapter dedicated to this. The idea was that you would design your code with comments. It would go something along these lines...
step 1 was to write comments of how the code would work.
You could in theory then have a review meeting of just those comments. This in turn causes you to get a better understanding of what you are trying achieve.
step 2 was to add the code
-(int)add: (int)a b:(int)b
{
return a+b;
}
More importantly is that if you did step 1 properly then in theory someone else could do step 2 just by implementing your comments.
we did something similar at my first programming job out of college (20++ years ago) and it helped in slowing things down to get you thinking before writing. I don't follow it to the same detail today but I do find at times when I am working on something a bit complex to follow similar steps.
think of it like a mental dump of what you are thinking at the time you write the code. we have all asked the question when reading someone else's code.
What were they thinking when they wrote this piece of code?
I would take the time to learn more of how and where these standards started. there is generally a wisdom or history behind things like this and knowing that can help more than the actual standard itself.
you want something inspirational??
|
|
|
|
|
Very informative. I appreciate it. As previously stated, my manager has extensive experience with multiple languages. And I'm almost certain it came from quite a long while ago. Also, they have a lot of contractors (myself included) come through here. So I'm thinking the extensive commenting style may be in place to more or less protect future contractors and such from becoming easily confused. Who knows, I could be wrong.
djj55: Nice but may have a permission problem
Pete O'Hanlon: He has my permission to run it.
|
|
|
|
|
Matt U. wrote: These are just a few examples.
The examples you gave are excessive.
The declaration of variables at the top is actually a hold over from C programming.
|
|
|
|
|
But C# is not C. Is it necessary? I've learned throughout the life of this thread that it doesn't matter. It isn't necessarily good or bad. But does it benefit in any manner when coding in C#?
djj55: Nice but may have a permission problem
Pete O'Hanlon: He has my permission to run it.
|
|
|
|
|
Matt U. wrote: But does it benefit in any manner when coding in C#?
whether it benefits in any manner is only a question that can be answered by those who created the coding the standards you are speaking of. from a language perspective though it makes where the variables are defined if you referring to code performance getting improved.
you want something inspirational??
|
|
|
|
|
Matt U. wrote: But C# is not C. Is it necessary?
Of course not. I was merely providing a historical source for why someone would do that.
If you feel feisty you might ask if that is such a good idea why neither C#, Java nor C++ language creators didn't require it.
Matt U. wrote: But does it benefit in any manner when coding in C#?
It might make someone more comfortable. Or it might might have made someone more comfortable 10 years ago but that guy has retired now (or gotten a different job.)
|
|
|
|
|
I understand your point and I appreciate the insight. I'm just dealing with it, I have no control over it. It was simply against just about everything I've ever read/been told. But you live and you learn, right?
djj55: Nice but may have a permission problem
Pete O'Hanlon: He has my permission to run it.
|
|
|
|
|
Just to play devil's advocate a little, it is not necessarily the standard about commenting that is at fault, but the standard of commenting.
private void Process(MyFileObj myFile)
{
if (myFile != null)
{
myFile.StripBadData();
_myFileCollection.Add(myFile);
}
}
Certainly if someone really wrote code with names like 'myFileCollection' they'll need comments
Oh, and the thing you missed completely was a method comment which should have explained what 'process my file' means in business terms - as processMyfile is too generic in all but the smallest of applications.
MVVM # - I did it My Way
___________________________________________
Man, you're a god. - walterhevedeich 26/05/2011
.\\axxx
(That's an 'M')
|
|
|
|
|
A very good point indeed.
You might even extend that to the trivial example of commenting a statement like
i++;
For one you may want to comment on why you chose to use post-increment rather than the more efficient preincrement. Or, better yet, you might comment on why you need to increment this variable at this precise moment - or what it is counting anyway!
GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)
|
|
|
|
|
I see very little - if any - benefit in declaring all local variables at the start of a method. To the contrary, it's bound to cause problems:
1. Variables that are being used much later may not have to be allocated at all, depending on the flow of control. You may end up spending resources and processing time for the initialization (and release) of data you never need! This is specifically true if you make a sanity check on the method arguments (which you alwys should) and go for a premature return.
2. When you maintain the code, it's often useful to see how a local variable has been initialized. This gets harder when the variables are grouped a long way up, and you can't see at a glance whether it's being changed between the declaration and the spot you're about to edit.
3. You shouldn't keep a hold on resources that you no longer need: the only way to reliably and maintainably (is that a word?) free up the resources required by a variable is declaring it within a code block. I even sometimes use a code block as a means to denote a specific variable's lifetime! You (or your manager) might consider this just as a'nice to have' feature, but it quickly becomes a necessity when you program concurrent threads using locks. There's no way in hell you're going to keep your locks over an entire method!
P.S.:
4. How do you do exceptions? I suspect your manager has never implemented a catch block, did he?
5. Why do you think C++11 has been changed to end the lifetime of for loop counters at the end of the loop?
GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)
modified 14-Feb-14 6:11am.
|
|
|
|
|
I too am on a project (about a million SLOC) that forces outdated coding rules that stem from the 1970's. The project has been ongoing for almost 17 years. I have tried to change the rules to reflect more modern thinking but the tech lead won't change claiming that consistency trumps everything including common sense, and that "the customer wants it that way" even though the customer developers don't follow their own rules.
One thing that was not mentioned about function-top declarations - it wastes processor time and stack space (for those of us who develop embedded systems with constraints on such things). Why should a class object be unnecessarily declared and created at function top and destroyed upon function termination when it is only used in the very rare case of an error?
Following are justifications for function-top declaration and initialization used by our project, and my responses to them.
Justification: Uninitialized access errors are easy to catch, either by a good compiler, by proper testing, or by a memory access testing tool.
Response: Meaningless. A good compiler, proper testing, or a memory access tool will catch uninitialized access errors regardless of where the variable is declared. Furthermore, declaring and initializing a variable close to where it is first used reduces the likelihood of an uninitialized access error.
Justification: Default initialization often does not incur a large performance penalty.
Response: Maybe for simple bool or int types. But unnecessary creation and initialization of class objects, and the associated destruction of said objects, when multiplied by thousands of functions in the system, can begin to impact performance and memory usage.
Justification: Placing all declarations at the top of the block makes them easy to find.
Response: Placing declarations close to first use makes them easier to find! This may have been true back in the 1970’s when programming was done with punched cards, but today, any editor can find a variable in seconds.
Justification: In some cases, variables must be initialized within a sub-block (e.g. a variable given different values in each branch of an if/else construct), in which case the variable must be declared before initialization.
Response: The phrase “variable must be declared before initialization” implies that the variable must be declared earlier in the code, which may or may not be true, depending on the context. It is obvious that the developer must declare the variable in the next higher scope if the variable has use beyond the if/else construct. But if the variable has meaning only within the confines of the if/else construct, there is nothing wrong with the following construction which also emphasizes the short-lived nature of the variable:
if ( itemCount > 0 )
{
int i = itemCount;
…
}
else
{
int i = MAX_INT;
…
}
Justification: Maintenance often extends the usage of a variable beyond the area in which it was originally expected to be used.
Response: So? If that happens, the declaration is moved out to the next higher block scope. Furthermore, maintenance often deletes all code that references a variable, leaving a function-top variable declared but never used. A compiler may catch that if its warning level is set high enough, otherwise it will be missed and left hanging around in the code. However, if variables are declared close to first use, chances are that when the code that uses it is deleted/moved, the declaration will be deleted/moved as well.
An additional argument to be made for any { } block declarations is that over time, as the program is maintained, a variable initialized at function-top may have its value updated prior to when it was first used in the original code. For example (fictitious), when first written, myVar is function-top initialized at line 10 and first used at line 95 (85 lines away from initialization). Over time, a maintenance cycle used myVar at line 40 but failed to reinitialize it prior to its later use. A review didn’t catch it and neither did testing. The code failed in the field; the customer is angry. A scoped-down declare/initialize would/may have precluded this problem.
Variables should be initialized to a meaningful value. That's why they should not be declared and initialized until there is a meaningful value to use. Often times at function-top, you don't know what a meaningful initialization value is so it is initialized to essentially a meaningless value such as 0. In that case you might as well initialize it to a random value for all the good it does.
modified 30-Apr-21 21:01pm.
|
|
|
|
|
With respect to your first point, this is not good.
I can tell you what the code is doing by reading it. Why is it doing that is the question the documentation should answer.
The hardest part about good documentation is what I've called the "philosophical documentation." In other words, describe what you think the code is doing, and why you took this approach. Try to let a future developer (yourself included) get into your mindset when building this code.
About the variable declaration, it depends. If it is truly just declaring method-scope variables, that's probably not so bad.
If, however, the variables you declare require some potentially costly construction, then it's smarter to delay that until necessary. Your method might exit before hitting that constructor in some code path and save that cost, for example.
I agree there is something to be said for the idea of 'closeness'. I feel like it makes the developer continually think about scope, but it's probably not such a huge deal.
|
|
|
|
|
Defining the variables at the beginning of the code dates from the time of VB6. But I believe that currently the most common approach is to define the variable as close as possible to where it is being used.
|
|
|
|
|
There are always multiple views on this kind of thing.
Here's my 2 cents worth.
Excessive commenting is a plague in my view. They interrupt the natural flow of what might otherwise be beautiful code.
As a rule, I will take a functional block of code and block comment it in as much detail as I think is useful. The comment will usually be less about what it is doing than why and what for and any notes about anything strange/non intuitive that it is doing. But I'm really against small obvious comments with each and every line of code.
As for the variable thing, in previous C standards, top of the block declarations were the only option. In newer ANSI, I believe this has been relaxed although here we don't tend to use it.
At least in C++ you have the option of late declaration. For me, as an Eclipse user, pressing F3 to get to the declaration is second nature now and most decent development environments have such a facility. If you can't remember what the type is, a mouse hover will soon reveal that. Not so convenient for vi/emacs uses of course
I would note that putting the declaration of a variable at the point at which it is initialised/first used reduces the possibility of accidental use when uninitialised. It also guards against the abomination of using a single general-purpose variable (e.g. i) for everything in the function. It might be slightly more efficient (although most optimisers would be converting these general purpose items into registers anyway) it is always tempting the accidental use of whatever was left in there from the previous use. I prefer not to do this.
For a loop variable, declare it in loop scope, don't reuse the same variable all the time:
for (uint32_t loop = 0; loop < max; loop++) {} etc
In a block, declare it in block scope.
As I said, a lot of these general purpose items will be registers anyway.
|
|
|
|
|
Wow, some of the comments here against coding standards surprised me.
I am a huge fan of coding standards, and code reviews. Especially when everyone works on the software. But I started with professional Basic Plus (on a PDP/11), which required no indentation, so people did not do it. LOL. A 16 way If then statement without ANY indentation. Worse, one of the programmers actually removed MY indentation. He said if you can't read the code, you are not a real programmer.
We immediately adopted coding standards, and reviews. But pragmatically. Comments are OPTIONAL and NEVER increase the accuracy of code. But, in a review, ANY reviewer can request a comment clarifying a complex block of code. Or forcing a comment on a variable declaration whose usage must be understood.
Over the next few months, we noticed the rates of defects in the code were dropping. We also found we were all getting better at predicting problems just by reading the code.
So, I am all for coding standards and code reviews. But let me add, that ONLY to the degree that the rules make sense. One of the reasons to use a standard is that it is EASIER to teach a person to read structured code of ONE STYLE than to have to constantly switch styles. Most editors do the heavy lifting of formatting these days.
My only issue with the coding style you have described is that it requires USELESS comments.
Declaring variables at the top is required in other languages (Pascal/Delphi, COBOL). In C, I always liked blocked local variables.
So, while i understand your frustration, have you read "Code Complete" or "Writing Solid Code". One way to attack the problem, is to get your boss to read some of the modern books (you should read them first). On my teams, ALL developers are REQUIRED to read a batch of 6 books on their own time. This helps us all speak the same language and communicate better. Just a thought.
|
|
|
|
|
And I bet they completely ignore XML commenting and don't require it. (This does look like C#)
Declaring the variables at the top does sound reminiscent of C/C++.
One thing that drives me nuts is using #regions in C# to create a section for all of your fields, then another for delegates, then properties, then functions.... Sounds good until you have a data-object where each bit of data might have a field, an exposing property, and maybe an event or two to let people know when it's added/deleted/changed... and then someone wants to change or delete a property of the object and you have to go thru each region to find the methods and fields regarding that property.
|
|
|
|
|
They actually do require the #region separation. It's like this:
#region Variables
...
#endregion Variables
#region Fields
...
#endregion Fields
#region Properties
...
#endregion Properties
#region Constructors
...
#endregion Constructors
#region Methods
#region Private
...
#endregion Private
#region Protected
...
#endregion Protected
#region Public
...
#endregion Public
#endregion Methods
djj55: Nice but may have a permission problem
Pete O'Hanlon: He has my permission to run it.
|
|
|
|
|
Probably, your manager's main metric is lines of code (with the comments). The more lines, the more productive he (and you all) look. If this is the case, then your manager needs a serious education in modern software design(including coding practices).
If you really want to inspire your manager, write a full length paragraph for each line of code. (Pretend that you are writing software for the department of defense. They just love documentation, even if they don't understand what it does.)
|
|
|
|
|
...tempted to phone one of the phone numbers currently being spammed in the Q&A section just to see what it's all about?
One might be missing out on some valuable advice concerning black magic.
/Fredrik
|
|
|
|
|
hmmm - tempted to get my fax machine to dial it. Constantly.
|
|
|
|
|
Could get pretty expensive if it's premium number
|
|
|
|
|