Search Results for: comment

About Commenting Code

I’m often asked about comments in code: when to do it, how to do it, what to put, etc. I’ve recently run into Steve’s post about when to comment your code, left a comment (!) there, and we got to expand our conversation in his podcast/screencast (link at the bottom). I’ve decided to create this post to consolidate the links and info shared during the interview, to make it easy for folks to find the material.

I remembered writing blog posts a couple of times over the years and it’s interesting to see how my opinion on this subject has changed over time.

The first post goes all the way back to 2005, with me asking “can you plesae put some comment on that Regular Expression?”. 15 years later, I still ask my smart friends to get me the RegEx I need, along some comments as to what each piece does!

In 2007, I was big into using Xml Comments, GhostDoct, and Documentor… I’m not anymore, as documented 10 years later with my post “XmlDoc Comments: Auto Generate and Hide the Clutter”. In nutshell, if we’re documenting a public API, yes, by all means let’s put in that documentation, but making it count: commenting the GetCustomers endpoint with “Gets the customers” doesn’t add any value to the effort!

My practice of making comments stick out as a sore thumb posted in 2010 still stands in 2020: I still set up all of my IDEs in that manner and it still produces exactly the outcome as I intended.

When I do want to drop a quick TODO comments in code (watch/listen to the podcast interview when it’s up to know why I might do that), I have templates on my IDEs to automate that: ReSharper in Visual Studio, User Snippet in VS Code, Live Template in RubyMine.

In regards to code that’s commented out, like so:

We should be using a source control system; if we ever want that code back, we have a way to bring it back. So just remove it!

Still using the example above, notice that each if-block is preceeded by a comment. Is it really necessary? How about removing the comment and extracting the expression into a method that tells us the question being asked?

There’s also the “narrator-style” comment:

Narrating every single line of code is very annoying (by the way, I think I wrote the code above many moons ago). If the comments were written initially as a placeholder for the steps that needed to be implemented, let’s make sure to get rid of it when we’re done.

Last but not least, some people say (I’ve said it myself) that comments should document “why” the code was written in such manner. I’d propose a variaton to that: how about documenting the why with some good specs (or tests, if that’s how you prefer)?

Now, I’m not refering to tests that look like this:

Such test doesn’t tell us the “why”; it tells us the “how”. I mean this kind of test (now you’ll see why spec fits better):

Summing it up, this is how I prefer to “comment” code:

If I do have a real need to drop an actual comment in code (“why do we have this query in the code that has to potential to perform badly”), I’ll probably drop a quick comment, with a link out to the issue tracker, where I’ll put more context about why the code was left like that, and where a Product Owner can decide when it’s appropriate to address the situation.

Any comments? 🙂

And for audio-only version:

https://www.weeklydevtips.com/episodes/code-comments-with-guest-claudio-lassala

Leave a comment

XmlDoc Comments: Auto Generate and Hide the Clutter

I mentioned how eager status code analysis is awful. A policy that forces developers to put XmlDoc comments is a good example of that.

This is how I see it: as I think through how I want to implement something I create an interface (created off tests I just wrote). The code might look something like this…

 

Right off the bat, VS is already showing me squigglies on the code I just wrote. I hover over it and this is what I see:


Right now I can’t even compile the code, and I don’t feel like typing Xml comments because I’m still thinking through my design and implementation. Parts of this interface are likely to be changed very quick, and any sort of documentation will become useless.

Since I need to conform with this policy, I use GhostDoc to just spit out the comments:


At this point I don’t really care whether the auto-generate comments make sense or not; I’m just satisfying what’s required in this development environment setup so I can get my immediate work done.

Of course, now what used to take just under 10 lines of code cannot even fit on my screen anymore and it requires scrolling!! That’s unacceptable to me. I can’t quite function seeing so much clutter! Fortunately, I’ve found this NoComment extension, which gets those comments out of my sight:


Now I can actually focus on what’s really important. Later, when I’m done with my design and implementation, then, and only then, I can review those Xml Comments prior to committing the work to the central source control repository.

Leave a comment

Claudio, those comments are ugly!!

The other day I was pairing with my buddy and co-worker Alan Stevens. We were reviewing some code, and at one point he said: Claudio, those comments are ugly!. At first I thought he meant how comments were worded, but then I realized he meant the way the comments were formatted:

uglycomment

You can see in the snapshot above that something really stands out, right?

Comments (which include code that’s commented out, but *not* XML Comments) are formatted in my environment in a very nasty way, and that’s on purpose. The thing is so ugly, it forces me to read it and find out what it’s all about:

  • It may be a TODO, so I want to make sure it won’t be forgotten (very often, a TODO is dropped in code to indicate some Technical Debt);
  • It may be code that’s commented out that should have been removed in the first place, instead of be sitting there as waste, polluting our code base with useless, distracting things. “But what if we ever need that code back?”, one might ask. Well, hello-oh, it’s 2010; people better be using some sort of Source Control System!!
  • It may be the means of a developer to explain some poorly written code; most times a simple “rename variable” or “extract method” refactoring can easily remove the need of the crappy comment;
  • In very rare situations, the comment is actually useful in explaining the intent of the code, so it’s a good thing that it stands out.

It comes a time when code may be tainted with so much useless comment that the mind just starts to ignore the warnings. What do I do? Just change the coloring to some other new ugly combination.  Smile

How about you: do you have similar approach regarding how you see comments in the code? Do you configure your environment so to have the editor visually indicate anything you deem important?

2 Comments

Xml Comments, GhostDoc, Documentor…

Here at EPS we’ve been getting more and more serious about the use of XML comments. Users of our framework always appreciate when we have good XML comments and always ask us to keep improving on it, so as much as possible we’re going back to legacy code and improving comments, as well as trying to write good comments for any new code we write.

Fortunately, there are tools to help us improve the quality of our XML comments. I’m listing here some of the ones we’ve been using.

Visual Studio

The code editor supports adding XML comments by typing /// (or ”’ in VB) right by the Type or member you want to put comments on. We can then set a property on the project (on the Build tab) to specify that an XML file has to be created with all the XML comments content upon every build. By default that option is unchecked.

XmlPropConfig 

We use different build configurations here, so we only turn that option on in our "Check-in Build", which is our most restrictive build. That option is off in all other builds because we want the local build process to be as quick as possible (if we’re in TDD-mode, we don’t want the compiler busy generating XML documentation files unnecessarily…).

When "XML documentation file" is enabled on the current type of build configuration for the project, the compiler lists warnings for every public type or member that does not have XML comments on it. In our check-in build we enable "Treat Warnings as Errors", which prevents the developer from even building the binaries in case there are missing comments.

WarningsAsErrors

Unfortunately, the compiler does not check whether there is actually anything within the XML comment tags, so a developer could get around the compiler error with something like this:

EmptyComments

That leads me to the next session…

Custom Rules for FxCop and Code Analysis

In order to make sure "smarty-pants" developers are aren’t fooling the compiler just by putting in empty comments, we wrote a custom FXCop rule that traps that, so that such violation won’t go unnoticed.

Not only we want developers to put comments on public members, but we also want them to put comments on private members. While the comments on the public members are helpful for people using the APIs, the comments on the private members are helpful for people maintain the code within the APIs.

Since the compiler only catches missing XML on public members, we also made our custom FXCop rule check for comments on private members.

Of course, those rules are no good if the assembly is not set to create the XML documentation file, so we also use a rule that checks to make sure every assembly has the xml file. We borrowed the rule from this article.

Why document private members??

The other day I was going through some code I found on the web (some very good code, by the way. I’ll be writing another post about it soon), and ran across this notFiredResult field somewhere. The usage or reason of this field wasn’t entirely clear to me, and IntelliSense didn’t give me much:

NoIntelliSense[5]

I then pressed F12 (or Go to Definition), and got to the field’s declaration:

InvalidXmlComment

Ok, that tells me something that’s more useful. I just wrapped up the existing comment into an actual valid XML-style comment, like so:

ValidXmlComment

And now I get that directly in IntelliSense:

GoodIntellisense

That’s such a simple change, but the removal of friction helps a lot when working on the code (the less I have to jump around the quicker it is for me to get the job done).

GhostDoc

This is one of the best free add-ins for Visual Studio: GhostDoc. This is a must-have tool to our developers here. 

GhostDoc does a pretty good job at creating initial XML comments. However, developers should ALWAYS make sure to verify what GhostDoc created, and edit it accordingly. For instance, if a method is named "MyMethod", GhostDoc creates documentation that say "Mies the method." (of course nobody should name a method like that anyways, but the point is that there are cases where GhostDoc can’t quite figure out the best way to write the comments, so the developer should always do some proof-reading).

Also, one feature I love bout GhostDoc is that it "inherits" XML comments from baseclasses and interfaces (when available). Say you override a method from a baseclass in .NET; you don’t have to type in the comment yourself, since GhostDoc will just grab the comments from the baseclass and paste it into your code.

Documentor

CR_Documentor is another plug-in for Visual Studio that rocks! When the Documentor window is being shown, it displays a preview of what the MSDN-like type of documentation will look like once you turn XML documentation into and more human-readable documentation. This helps a lot when typing the XML comments, since the developer can immediately see what the output is going to look like.

Even if you’re not planning to create the MSDN-like documentation out of your source code, the tool is also useful to improve the visualization of the XML comments within VS; a formatted HTML page is much easier to read then green comments in XML tags. Whenever I’m working with some code that I’m trying to learn about it, I have the Documentor window docked somewhere in VS:

Documentor1

Also make sure to check what’s available when you right-click on an XML comment once you get Documentor installed. There’s a bunch of little things that helps a lot composing decent documentation (such as options to add bulleted lists, sample source code, etc.):

Documentor

1 Comment

Can you please put some comment on that Regular Expression?!

Regular expressions are one of those things on the software development world that give me nausea when I come across them. Reading something like this in code just makes me shiver:
 
^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\’\/\\\+&%\$#_]*)?$
 
It seems to me like cartoon characters swearing: &$^%#&%@&$#**^&$. 
 
I just happened to run accross a little article (found at  that taught something I didn’t know about regular expression: one can put comments on them!
 
So, instead of having some cryptic code like this one:
Regex regex = new Regex(@"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}\s$);
One could make the world a favor and rewrite that code like so:
Regex regex = new Regex(@"
                                            ^                 # anchor at the start
                                            (?=.*\d)      # must contain at least one numeric character
                                            (?=.*[a-z])  # must contain one lowercase character
                                            (?=.*[A-Z]) # must contain one uppercase character
                                            {8,10}         # From 8 to 10 characters in length
                                            \s                 # allows a space 
                                            $                  # anchor at the end", 
                                            RegexOptions.IgnorePatternWhitespace);
 
That way, even my little brain can understand a freakin’ regular expression.
 

4 Comments

Time Will Pass Anyway

“Slow progress? So what, time will pass one way or another.” I don’t remember where I’ve read that quote, but I always think of it. Much like this one, which I’ve read on The Artist’s Way:

Student: “But do you know how old I will be by the time I learn to really play the piano/act/paint/write a decent play?”
Teacher: “Yes… the same age you will be if you don’t.”

Not far from what I’ve shared about the Search for Perfection.

When I release my latest song, an old friend told me this: “I see your videos and think they’re really cool, and I feel envious because I can’t get my stuff together like you do.

That comment inspired this post, which contains some of the things I’ve shared with him…

The main riffs for that song were written 10 years ago. I wrote the main ideas for the lyrics 5 years ago, and I finished the main structure of the song around the same time. I started recording the song in April this year. I’ve only finished lyrics, vocals, guitar solos around September/October, and the song was finally released in November.

Ten years.

I have many other songs that have been in-progress for years now: 5 years for two of them, 13 years for another, and there’s one sitting in the backburner that goes back to 1995.

Do all of my songs take that long from initial conception to release? No. Sometimes it takes me as little as 2 to 3 months. No specific reason; I may just feel like I have all of the parts and so it happens I have the time to get it all done quickly.

However little time I have, I record song ideas on my phone and store it away in a backlog. I write ideas for lyrics and put it away. Every once in a while, I listen back to those ideas, and if I feel an urge to work on any one of them, I make the time and make some progress. Sometimes I may be able to wrap it all up within a month, other times it may take me years. No biggie.

For me, it’s important to get it started, get the ball rolling. When it’s done, it’s done. Time has passed. Progress has been made. Results have been achieved.

Leave a comment

The Search for Perfection

“Perfection” has an expiration date. Yesterday’s perfect may be today’s “meh”.
Not to long ago, I was watching Tony Robbins’ interview with Shaun White. When they mentioned Shaun’s Perfect 100 Score at the 2012 Winter X Games, I looked for it YouTube. To me, it looked stunning. It’s just unbeliable that people can do that. As I scroll down the comments, I see this one: “Probably a 93 today”.

A perfect score yesterday won’t guarantee a perfect score today. Not without work towards progress. Yesterday’s competitors will learn from that perfect score. I like this sentence I’ve read in The Obstacle is the Way: think progress, not perfection.

Year’s ago, I’ve read Derek Sivers’ summary of the Art and Fear book. This passage has stuck with me:

The ceramics teacher announced on opening day that he was dividing the class into two groups. All those on the left side of the studio, he said, would be greaded solely on the quantity of work they produced, all those on the right solely on its quality.

His procedure was simple: on the final day of class he would bring in his bathroom scales and weight the work of the “quantity” group: fifty pounds of pots rated an “A”, forty pounds a “B”, and so on. Those being graded on “quality”, however, needed to produce only one pot – albeit a perfect one – to get an “A”.

Well, came grading time and a curious fact emerged: the works of highest quality were all produced by the group being graded for quantity. It seems that while the “quantity” group was busily churning out piles of work – and learning from their mistakes – the “quality” group had sat theorizing about perfection, and in the end had little more to show for their efforts than grandiose theories and a pile of dead clay.

“Better good today than perfect tomorrow”, comes to mind.

I keep those things in mind whenever I see myself with tons of ideas, but not starting them because I may not have what I consider ideal to get it done (“not enough time”, “not enough money”, “not enough skills”, etc.).

I have been putting out many songs over the last several years. Everytime I’m working on a new one, I may think “if I learn how to play the drums better”, “if I learn more music theory”, “if I learn how to sing better”. But I’m getting better at realizing I’m falling into that trap and quickly shifting into getting it started, working on it, getting it done, and moving on. Next time, it gets a little better, and so it does the time after that. Instead of waiting 10 years to have the perfect song (which I know won’t happen), I get done however I can, with whatever I have.

 

Leave a comment

The Importance of Technical Communities

Technical Communities may be the single most important factor I’ve had (and continue to have) in building my professional career. Yes, that’s how important I believe they are.

I first got involved with communities back in the late ’90s. I got a job where I got to work with FoxPro, which I knew nothing about other than that it looked similar to what I knew at the time: Clipper and dBase. That was also around the time the internet was becoming a thing in Brazil in the days of dial-up connections.

In order to get up and running on the required tech stack, I found online forums in Portuguese.

There were many resources in English for FoxPro, but not a lot in Portuguese. I knew some English at the time. Many Brazilian developers didn’t. So here’s what I did: I’d see people’s questions in the online forums, look up the answers in English on the web, and reply to the posts in Portuguese. Why did I get from doing that?

  • I learned a lot of FoxPro in a short period of time
  • I learned a lot of English
  • I helped other fellow developers

A member of the community invited me for lunch one day and gave me a couple of FoxPro books. I asked the reason for the gift, and he said: “If I help 100 people, maybe one of them will give me a hand in a moment when I could really use some help”. I have taken that lesson to heart and applied it to my life deliberately ever since.

Because I was answering so many questions, people thought I was an expert.

When a new version of FoxPro was about to come out, members of the community reached out to the Microsoft office in Sao Paulo to ask if there was going to be an official launch event. The MS manager said they could do that, but there were no MS employees in Brazil who were well-versed in FoxPro. The community member said, “well, problem solved: I know a guy”. Next thing I know, I’m presenting two full-day, soldout launch events. Attendance included people flying from other states (if you don’t know how big Brazil is, please pick up a map…)!

So that’s how I broke into technical public speaking. Next, I got into writing articles, creating a magazine, organizing conferences in a few different States, organizing study groups, creating training videos…

So much came out of the common need to learn a new tech stack, followed by the simple action of helping others along the way, with however little I knew of anything.

The fact that I’ve been living in the US since 2002 is directly related to this involvement with technical communities.

See why I have a cute fox as part of my office decor? Never forget where you come from!

Also, when some youngsters make smartass comments about the mention of FoxPro on my business card, I may just say: “sit down, kid, let me tell you a story…” 😉

Leave a comment

Building my Book Library

I’m slowly building my book library. I enjoy books in all shapes and forms: paperback, e-book, audiobook, animated book summary, etc. My library reflects that.

Most of my technical books are e-books. I usually get their PDF version and put it in a “Books” notebook in Evernote; its search feature goes into those PDF files to find what I’m looking for. Quick access when I need that information.

My fiction books are either paperpack or e-book (usually in Kindle format).

The non-fiction, non-technical books are well spread out in different formats.

I’ve been reading more and more of my e-books on Kindle (on my iPad), using its features to highlight and comment; I often review my notes and highlights.

I’m getting more and more paperback books. Sometimes, I end up getting them after either listening to the audiobook or reading the e-book versions.

I have books in my library that I’ve purchased over a decade ago and haven’t read yet. I also have been acquiring more books that I don’t know when I’ll read them, but I do want to have them readily available. I don’t ever want to be in a situation where I tell myself “oh, gee, I really want to read something, but I have nothing to read”. Seriously, dude? Just go to your library and pick something up!

When I get book recommendations from friends or from reading other books, I look them up on Amazon and add them to my “books wishlist”, and I add a note to remind me where the recommendation came from.

To keep track of my backlog, books I want to read soon, books I’m currently reading, and books I’ve read, I still use the same process I’ve described in 2016.

2 Comments

15 Year Anniversary!

Wow. It has been 15 years since I started this blog!

It’s kind of cool seeing the areas that stick out:

Productivity, Testing, Evernote… that sounds about right.

Fun Facts

  • Most popular post: A Good Example of Liskov Substitution Principle (Nov/2010). It’s such an old post, but it still gets many views. The 2nd most popular post doesn’t have even 1/3rd of the views .
  • Total Posts: 426
  • Average Words Per Post: 342
  • Year with the most posts: 2007, with 75. This is post #51 this year, should I look into setting a new record?
  • I can think of at least two occasions when I googled something and ended up finding the answer on my blog, having totally forgotten I had already run into the same problem and written about it.
  • While I don’t get lots of comments left on the blog itself, countless times somebody mentions one of my posts in conversations. My point: people are “listening”, and that’s why I write and post, regardless as to whether I’m generating tons of views and a buzz or not.
  • I still look at zero-based arrays and think “what the heck?”. 🙂

Leave a comment