UtterAccess.com
X   Site Message
(Message will auto close in 2 seconds)

Welcome to UtterAccess! Please ( Login   or   Register )

Custom Search
2 Pages V  1 2 >  (Go to first unread post)
   Reply to this topicStart new topic
> Comments To Code Percentage, Any Version    
 
   
JonSmith
post Dec 30 2016, 06:01 AM
Post#1



Posts: 3,145
Joined: 19-October 10



Hi guys,

Someone at work has made a pretty horrid tool in VBA and want IT to support it. I have many issues with it, one being really poor code commenting.
On analysis out of the 5,800 lines only 2% were code comments.

I analysed alot of my work and I average around 25-30% code comments. I was curious if I do more or less than the average coder. Obviously 2% is waaay too low but I want to gauge what others consider reasonable.

I was able to do quick checks doing Mz Tools statistics so I guess this is only a question that people with addin's such as that can answer?


JS
Go to the top of the page
 
Marsupilami72
post Dec 30 2016, 06:14 AM
Post#2



Posts: 429
Joined: 17-April 12
From: Germany


I just did a quick count on the routine i am currently working on - about 10% of the lines are comments.
Go to the top of the page
 
Jeff B.
post Dec 30 2016, 07:10 AM
Post#3


UtterAccess VIP
Posts: 9,860
Joined: 30-April 10
From: Pacific NorthWet


One reason for including comments in code is to help the poor sod who comes along later and has to figure out both "what" and "how" ... and sometimes that's me!

--------------------
Regards

Jeff Boyce
Microsoft Access MVP (2002-2015)

Mention of hardware or software is, in no way, an endorsement thereof. The FTC of the USA made this disclaimer necessary/possible.
Go to the top of the page
 
GroverParkGeorge
post Dec 30 2016, 07:58 AM
Post#4


UA Admin
Posts: 30,988
Joined: 20-June 02
From: Newcastle, WA


I just checked one project on which I am at least the third or fourth developer to work. It has about 26% comments, and about 23% blank lines. That means close to half of the actual lines in the VBA are comments.

Unfortunately, a lot of those comments are useless. That said, every change I make has a comment indicating when and why I made that change.

Other projects I work on are probably quite similar.

--------------------
Go to the top of the page
 
nvogel
post Dec 30 2016, 08:50 AM
Post#5



Posts: 804
Joined: 26-January 14
From: London, UK


I don't think there's any "right" percentage. Too many comments can even be a bad sign. If code is well laid out and meaningful variable names are used then fewer comments may be necessary.

"Change history" commentary is an example of where less can mean more. Assuming your code is in a suitable source control system and incremental changes are properly annotated when they are checked-in then adding such comments in the code itself is unnecessary and potentially misleading.
Go to the top of the page
 
jleach
post Dec 30 2016, 08:52 AM
Post#6


UtterAccess Editor
Posts: 9,768
Joined: 7-December 09
From: Staten Island, NY, USA


>> Obviously 2% is waaay too low <<

What makes you say that?

Generally speaking, comments are bad. It indicates that the code itself is unreadable and that it needs to be explained. If the code is unreadable, it's not good code. Comments create another layer of garbage that need to be maintained along with the code itself (which pretty much never happens... if I had a dime for every comment that explained something from 10 revisions ago and only serves to further confuse matters when someone would try to read it now...) As a matter of course I pretty much ignore any comments in projects I see.

If a person feels they need comments to explain their code, what they really should be doing is working on better code architecture: breaking up complex routines into smaller, more focal routines; adjusting naming conventions so they're very easy to read at runthrough. Code comments should be restricted for the very rare cases of "we had to do this way because [usually approach didn't work because ____]" or for (very)light overview of a complex algorithm. Module headers is another acceptable place for light commenting.

Keep a higher level documentation explaining what and why (NOT in code comments), and keep the code clean and well-structured, and comments will no longer be required except in very rare cases. Good code tells its own story without needing a translator at every turn.

My 2cents (or, maybe just file this under Unpopular Opinions smile.gif )

Cheers,

--------------------
Go to the top of the page
 
GroverParkGeorge
post Dec 30 2016, 09:07 AM
Post#7


UA Admin
Posts: 30,988
Joined: 20-June 02
From: Newcastle, WA


While I don't disagree with most of your comments, I do think there is some value in noting changes in the code. After all, what you're suggesting as an alternative is a separate document that "someone" has to keep track of and maintain "somewhere". In a full-blown IT project that's par for the course. However, in most of the small-medium sized Access projects I've worked on, clients tend not to want to pay for real documentation. I can think of only one project where that was the case, in fact.

In the absence of reliable source control for Access, the only way I know to maintain some semblance of sanity is to note changes in the code for other developers. For example, in a project that has been worked on by different people at different times, and currently has at least two active developers, I put this one:


'============================================================================
' RVK-- by Grover Park Consulting 10/14/2016 13:19 Changed the way new items are added to the list, at the top rather than the bottom
'============================================================================

Since I have no way to implement source control here, noting things I changed is a second-best alternative. Hopefully, the other guy won't overwrite my changes just because he has an older, different, version.

Here's an example of the kind of comment for which I do have some contempt, though:


'$ PURPOSE: Set the Date of the blanket fee
'$
'$ REVISIONS:
'$ 07-27-95 Original Version
'$ 00.03.15, reformatted, MjB.
'

Note that the original code dates back to July of 1995, by the way. Really? Cool. 21 years of code tweaks makes this one of my favorite databases to support. On the other hand, what got "reformatted" in 2015 by someone else whose initials are MjB? I have no idea, nor do I really care.

On balance, therefore I'd prefer not to have to do it, but until MS decides to restore some sort of usable source control, code comments are handy enough, IMO.


.
This post has been edited by GroverParkGeorge: Dec 30 2016, 09:09 AM

--------------------
Go to the top of the page
 
jleach
post Dec 30 2016, 09:18 AM
Post#8


UtterAccess Editor
Posts: 9,768
Joined: 7-December 09
From: Staten Island, NY, USA


Yea, lack of good SCC in Access makes revisions a pain, and I think commenting can be good for that within VBA. Rarely do I get an Access project that uses comments that way though... most times they're peppered (or saturated) throughout the code itself, which doesn't really help anything, IMO.

With that said, I do feel that separate documentation is valuable on any size project. It need not be elaborate, though it does take some discipline to properly maintain.

Cheers,

--------------------
Go to the top of the page
 
GroverParkGeorge
post Dec 30 2016, 09:21 AM
Post#9


UA Admin
Posts: 30,988
Joined: 20-June 02
From: Newcastle, WA


Well, there's that pesky budget problem to manage, Jack. I just recalled a second project on which there was budget for documentation, but my little Access piece was one small corner of the whole thing. The client actually set up a Wiki for documentation and each developer, including me, was expected to manage our portion regularly (at least once a week, not "whenever"). But when the project budget is "as much under $5,000 as you can manage", it's hard to convince a client to include documentation. Far too many people consider it a "nice to have".

--------------------
Go to the top of the page
 
Doug Steele
post Dec 30 2016, 09:31 AM
Post#10


UtterAccess VIP
Posts: 21,444
Joined: 8-January 07
From: St. Catharines, ON (Canada)


You might be interested in a column my friend Peter Vogel (former editor at Smart Access) wrote a few years ago, entitled Why You Shouldn't Comment (or Document) Code. Follow the links at the top of the article too.

--------------------
Go to the top of the page
 
GroverParkGeorge
post Dec 30 2016, 09:50 AM
Post#11


UA Admin
Posts: 30,988
Joined: 20-June 02
From: Newcastle, WA


Hmm. Thanks, Doug. Sometimes I tend to lose perspective a bit. "WHY" is useful. "WHAT" is often not so useful.

--------------------
Go to the top of the page
 
jleach
post Dec 30 2016, 09:58 AM
Post#12


UtterAccess Editor
Posts: 9,768
Joined: 7-December 09
From: Staten Island, NY, USA


Good article(s) Doug, they better articulate my points than I did.

A few things though:

>> I am not aware of any scientific studies that have been done to measure the effectiveness of various coding or comment styles. <<

Steve McConnel wrote about the subject of commenting rather in-depth in his Code Complete book (which every developer should read, IMO). I'm not sure offhand if this work was based on research, but most of his books do cite specific studies.

I disagree with this statement from the main article you linked to:

>> Refactoring is only reasonable if you're doing test-driven development (TDD). <<

For VBA, testing frameworks are about as readily available as SCC tools (ok, even less so). Nevertheless, refactoring should always be the "after working code is there" step, I think. (I wonder if the author is mis-using the word TDD here, as TDD is specifically the approach of writing tests before code, then coding until tests pass - I think he may have been speaking of unit testing more generically, which is surely a good thing, especially for refactoring, but refactoring is still reasonable in VBA, even without TDD (or even unit testing frameworks readily available))

--------------------
Go to the top of the page
 
JonSmith
post Dec 30 2016, 02:00 PM
Post#13



Posts: 3,145
Joined: 19-October 10



Nice to see its caused some discussion!!

nvogel, I wasn't looking for a "right" percentage. I was looking for an average. This is highly subjective so trying to find a "correct amount" would be dumb.



Jack, I have got to disagree with you fundamentally.
What you might consider readable code may not be readable to someone else. My code comment mentality is for each code block to explain the overall purpose of that code chunk and not for example that .copy would copy some information.

I would say if you are breaking your sections apart alot a description of the procedure is essential since when out of context of a larger procedure the behavior can make no sense. I don't always want to investigate 1000 lines of code to get the context needed to fix 5 lines worth.

Speaking first hand of having to fix alot of VBA tools created by others poor commenting is a huge time drain. I am an experienced coder, I understand all the VBA I see but I don't often know why the [censored] something is happening in some of the code I see until I slog through all the other lines around it.

An example is some awful code in Excel that was doing some rather messy SQL from a bunch of data sources, the SQL had loads of "", "", "", for its fields and none of the fields has fieldnames so I had to cross reference back the data to try and work out what was going where. It involved about 3 union queries. I followed it through until I found out it was simply summing column and column K. The empty fields were so it could be pasted into column A and the summed fields would be in the correct position. I re-wrote it to just use a simple formula and discarded over 100 lines.

If at any point the code had described that chunk as summing those columns I could have skipped so much time. It didnt. Now I see your point that if it had been written very simply at first the comments wouldn't be needed, I wouldn't explain what a sum formula does next to a sum formula, but I would explain a code chunk as it puts the totals of the relevant columns in.


I am curious Jack, since you feel comments aren't needed. Do you work with other peoples VBA often? Do others work with yours?


In the context of the issue I have at work, the department hired an external to build the VBA tool, its badly written in my opinion, they don't know how to code well (for example in the various class modules they have, and there is alot, they always use functions to return properties as they seem to be unaware of Get / Let), I also don't understand why most of the code will be doing the stuff it does as its about financial curves and I don't know how to do that. If I need to fix the thing I need to see what its supposed to be doing.
I have also come across things in the past that seem wrong to me, when I have no context of what they should be doing I then have to investigate alot, if I knew what it should be doing I can fix instantly.



Go to the top of the page
 
JonSmith
post Dec 30 2016, 02:06 PM
Post#14



Posts: 3,145
Joined: 19-October 10



To put it another way, I agree that if code is of a high quality and the person reading it is skilled in VBA then comments are of limited use and can sometimes be a hinderance to maintain.

However how do we measure quality? I don't want to go through 5000 lines of code to evaluate the quality and inevitability have to rebuild it as I go because the quality is not as high as needed for the aforementioned to be true.
Instead, if the code is commented, if it is of a low quality it is still readable without too much effort, if its of a high quality less skilled VBA coders will then have much more chance of understanding it.
Go to the top of the page
 
jleach
post Dec 30 2016, 02:44 PM
Post#15


UtterAccess Editor
Posts: 9,768
Joined: 7-December 09
From: Staten Island, NY, USA


I have worked with many other people's VBA code, yes. In general, when I inherit a brownfield project, the comments are bad and get ignore, often deleted as I work through the system. Bad comments are easy to write. Rare is the case I get a VBA project with worthwhile comments in it.

I'm not saying comments aren't needed or are across the board bad, but I do feel that most times they are. Few people seem to be able to strike the balance between good comments and bad comments (especially in the VBA world, but elsewhere also).


Here's an example procedure I use:

CODE
Public Function GetPendingUpdateCount() As Long
On Error Goto Error_Proc
'===============
    'variable declarations
'===============

    'function body

'===============
Exit_Proc:
    'cleanup
    Exit Function
Error_Proc:
    'handler here
    Resume Exit_Proc
    Resume
End Function



Aside from the "comment" lines that give visual separation to the anatomy of the procedure, there's no reason for comments (concerning separation of the anatomy of the proc: these help me quickly pinpoint the meat of the procedure - I typically don't care about the declarations (they're named so I don't have to), and I typically don't care about the cleanup or error handler: my eyes are trained to look at the signature or the body while skimming and ignore everything else).

I don't need a comment to explain what the code does. The signature does that.

I don't need a comment to explain how the code does it. I don't typically care how it does it, and if I do, I'll just read the code.

I don't need a comment to explain how it's being used. The module in which the procedure resides tells me that (and I should not be looking at functions without realizing what module I'm in).

Let's pretend I have some nasty bit of regex, which is entirely readonly. I could put a comment above that stating what it's supposed to be finding. Or, I could move whatever it's finding/doing to a smaller routine (which also creates an abstraction point for me to swap out that functionality later).

Some code is downright ugly, and not much to do about it. Heavily nested quotes are sometimes unavoidable. That may warrant a single, short comment (in very terse form) stating the intent or reason. Occasionally we'll have to do something in a slightly unorthodox manner that what other (experienced) developers might expect, so we'll toss a comment in there stating why (again, in very terse form).

A module header describing the core intent/basic approach as well as revisions is acceptable, I think, but not often required.



The other fairly strong argument for comments seems to be in helping other people that come along. As it happens, I have some thoughts on this as well smile.gif

First, I myself am not one to dumb down my code so a lesser-experienced developer can read it. Instead, I just assume have that developer work on something slightly above his/her level and learn a few things. Commenting code to help the less experienced is just making things more difficult for everyone else, provided the person who wrote the code is capable of writing good, readable code! (which is a very related subject but an entirely different rant).

If an experienced developer writes clean, readable code, any lesser experienced person should have no trouble following without comments leading the way (again, a module header describing the general intent/approach is fine - I'm talking comments within the code body). If a person is supposed to work with a project and can't understand what GetPendingUpdateCount() is supposed to do, there's an issue. If I use a DAO.Recordset to obtain that count within that procedure, I do not feel in the least bit obligated to describe what a DAO recordset is and why I'm using it to do the job (unless I had to use it in some very unorthodox way which wouldn't be expected elsewise). If the would-be-developer doesn't know that, they have no business working on the same project as whatever customer I might have written this code for (on the other hand, I wrote a data macro management utility for the Professional 2013 Access Programming book, and that code was heavily commented simply because it was intended to not only provide a useful tool, but to show other developers how to do it: explaining what XML nodes are and why we have to loop them using NextNode instead of a For loop or the data structures within the xml that make up the data macro definition, etc - that's an entirely different context but serves to show that it's not all black and white regarding comments).


>> What you might consider readable code may not be readable to someone else. <<

Readable code should almost be readable by a non-developer, at least to the point of giving an outline of what's going on, should they have any interest. What I consider to be clean, readable code should be readable by anyone with a small amount of programming experience. On the other hand, the ability to effectively and efficiently read code is also a skill to be learned, but again, I'm more inclined to give people something to learn than dumb down my work. I've had highly technically able developers do amazing work in a functional sense, but the code is a nightmare to work with because they didn't understand and apply the subtleties of good, semantic naming conventions (don't even get me started on this). I've had others do work for me that weren't all that technically superior, but their code is easy to work with because they have a good sense of readability.

In any case, I do disagree with your statement, again provided the person who wrote the code is capable of writing good, readable code. Such code should be readable by just about anyone.

Regarding quality: tough metric, but I'd say that a large part of that is having clean, readable code, because clean, readable code is maintainable code, and if your code is clean and readable enough where you don't need comments, that means you've followed many other best practices in code construction as well, which overall lends itself well to quickly and easily determining with a reasonable amount of confidence whether the codebase you've inherited is well constructed or not. So, it's not [i]just]/i] about comments, but many other unrelated factors as well: when they all come together, the code should speak for itself, and then you have a project that is a dream to work on and it easily turns into one of your favorites. Unfortunately, this is all too rare.

Cheers (good topic!)

--------------------
Go to the top of the page
 
jleach
post Dec 30 2016, 02:53 PM
Post#16


UtterAccess Editor
Posts: 9,768
Joined: 7-December 09
From: Staten Island, NY, USA


(as you might have guessed, I'm very OCD about code cleanliness and readability... in the .NET world (where most of my work is) this is most often abused by being trigger-happy with interfaces, but it's very much the same concept I think: the bottom line is that bespoke business software must be highly maintainable, and the cleanliness of the code is a huge factor in this. In fact, within my own business, it is my largest internal focus when getting people up to speed - get the naming conventions down, stop with the stupid fluff code, keep it short, sweet, neat and clean, because in three months when the client wants something modified, I want to be in and out quickly and effectively, while understanding what we're doing the whole time. Code without comments is a strong indicator that we've met this mark, and I've not heard anyone complain about it (but that may just mean that they don't complain to me))

--------------------
Go to the top of the page
 
TheSmileyCoder
post Dec 30 2016, 04:49 PM
Post#17


UtterAccess VIP
Posts: 1,505
Joined: 19-January 12
From: Denmark, Copenhagen


I took over a project which had plenty of comments. Sadly they were all of the style
CODE
'Enable error handling
On Error goto ErrHandler

...


'Rest error handler
On Error Goto 0

Hey, if it was the first time I ever used an error handler, I might do the same, just because the syntax was new to me. But in 200 procedures, that same piece of useless comment? While the things that actually required a comment had none:
CODE
Private Sub Frame281_AfterUpdate()
  ExecStoredProcedure "myStoredProcedureVersion8"
End Sub


I tend to agree with Jack. I would say most of code is self-documenting, but I might for readability or "scanability" the ability to quickly scan for the piece of code to modify, I might add some small comments to each code block like below:
CODE
'Generate excel instance
      Dim ws As Worksheet
      Set ws = gfh_CreateExcelApp(1).Workbooks(1).Worksheets(1)
      
   'Export data
      Dim myRange As Range
      Set myRange = ExcelTools.RecordsetToExcel(rs, ws.Range("B2"))
  
   'Add calculation column
      myRange.Range(myRange.Cells(1, myRange.Columns.Count), myRange.Cells(rs.RecordCount, myRange.Columns.Count)).FormulaR1C1 = "=RC[-1]-RC[-5]"
      myRange.Range(myRange.Cells(1, myRange.Columns.Count), myRange.Cells(rs.RecordCount, myRange.Columns.Count)).EntireColumn.Hidden = True
  
   'Add the chart
      Dim myChart As Excel.Chart
      Dim chartRange As Range
      Set chartRange = ws.Range("J2", "R26")
      Set myChart = ws.ChartObjects.Add(chartRange.Left, chartRange.Top, chartRange.Width, chartRange.Height).Chart
      myChart.ChartType = xl3DBarStacked
      
      With myChart.ChartArea.Format
         .ThreeD.RotationX = 0
         .ThreeD.RotationY = 90
      End With
      
      
      myChart.PlotVisibleOnly = False 'This sadly auto-creates a series
      'So now we delete it
      Do While myChart.SeriesCollection.Count > 0
         myChart.SeriesCollection(1).Delete
      Loop
      
      myChart.Axes(xlCategory).ReversePlotOrder = True
      
   'Format chart
      With myChart.SeriesCollection.NewSeries
         .Name = myRange.Cells(1, 3).Value
         .XValues = myRange.Range(myRange.Cells(1, 0), myRange.Cells(rs.RecordCount, 0))
         .Values = myRange.Range(myRange.Cells(1, 2), myRange.Cells(rs.RecordCount, 2))
        
         .Format.Fill.ForeColor.RGB = 5154185
        
      End With


You might notice the only comment that is more "sentence" like in nature, is about the series being auto-created, and hence deleted. That is an example of something I felt required a bit of explaning.

--------------------
TheSmileyCoder // Anders Ebro (Access MVP)

~~~~~~~~
Blog: www.TheSmileyCoder.com
YouTube Channel: TheSmileyCoder
Go to the top of the page
 
jleach
post Dec 30 2016, 05:46 PM
Post#18


UtterAccess Editor
Posts: 9,768
Joined: 7-December 09
From: Staten Island, NY, USA


I might even go so far as to break down each task in that procedure to a separate procedure. A proc should do one thing and one thing only (and if it means that the one thing it should do is instantiate an excel object and pass that to other procedures in a series of calls to perform a larger task, that's fine: but each task (export, add calc, add chart, etc), would be separate procedures).

>> 'This sadly auto-creates a series <<

An example of a Good Comment. Notes something out of the norm happening and why we have to handle it.

thumbup.gif

--------------------
Go to the top of the page
 
JonSmith
post Dec 30 2016, 06:28 PM
Post#19



Posts: 3,145
Joined: 19-October 10



Interesting thoughts Jack.

I fear you are thinking I want things such as 'Turn error handling on' commented. This is not the case, I am talking more about general functional comments about what the proc does or what a code block does, for public variables sometimes why they are public and where they get used etc etc.

In your example of GetPendingUpdateCount() am I supposed to know the purpose from the name alone? Because I dont.... Whats an update count? Where does it come from?
What is getting updated? I have a background in healthcare and now work in finance, the businesses dont translate, I dont know alot of the financial technical terms. I have a proc to calculate shock values. I have no clue what shocks are but because I described the purpose of the proc in my proc headers I dont need to.

The commenting I do is more like the SmileyCoders which I think is a good amount that doesnt get intrusive.

I fear your reliance on naming conventions is too narrow and procs themselves often need a simple explanation. Not to understand the code, to understand why the code is there (like to calculate shocks and do x with them).
Considering you break your procs up so much I'd think its more important.

I actually really dislike segmented code when its segmented for the sake of it.
As far as I am concerned if any code is used repeatedly in different places then separate it, if its sufficiently complex to make the main proc cluttered / harder to read then separate it. In SmileyCoders example I see no need to break that apart unless any chunk is reused.
Go to the top of the page
 
tina t
post Dec 30 2016, 07:10 PM
Post#20



Posts: 5,182
Joined: 11-November 10
From: SoCal, USA


hi, guys, i really love it when a group of you get going on a topic like this. being a self-taught amateur, seeing professionals explain and discuss your various styles and practices helps me develop my own without feeling too lost at sea. thx! :) tina

--------------------
"you can't take the sky from me"
Go to the top of the page
 
2 Pages V  1 2 >


Custom Search
RSSSearch   Top   Lo-Fi    21st November 2017 - 12:25 PM