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

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

Virtual Brown Bag: June 2020 Summary

June was another month filled with Virtual Brown Bag meetings every Thursday. Lots of great discussions on a variety of topics. Here’s a summary and links to the videos. Enjoy!

June 4:
We talked about a bunch of stuff this week! Books, Connecting, F# Conf, WebForm/WinForm, Android crash, Racket, FizzBuzz, The QA’s Role in a Scrum Team. George brought up discussion on resumes and interviews It sparked many comments. We’ll bring it back next week. We have even mentioned FoxPro. 🙂

June 11
:
Great chat about resumes! We’ve lost the 2nd half of the discussion due to technical issues, but still, there’s good content in here.

June 18
:
We’ve continued our conversation from last week, talked a little more about resumes, and also job interviews, developer challenges, etc.

June 25:
We talked about upcoming free virtual events, Claudio’s “Trusting IT” call for feedback, the “Badass – Making Users Awesome” book, George’s code challenges, using generators, threading/pipeline operator, and the Rocketbook.

,

Leave a comment

Answering questions from my Scrum talk

I’ve had a great time giving my “Beyond the Daily Stand-up: An Intro to Scrum” talk at the Virtual Agile Shift yesterday (check out the conference: it’s going through the end of the month!).

There were great questions asked, some of which I was able to answer at the end of the talk, and some that I couldn’t answer as I ran out of time, but promised I’d post the answers to my blog. Hence this post!

Some of the questions make me want to write a full blog post for each, but in order to keep my commitment to answering them today, I’ll give the short answers now, but I’m saving the questions for future, longer posts.

Here we go!

What are your thoughts on Unified Engineering?

I had not heard of “Unified Engineering” before. When I first saw the question I thought it could be one of those things I knew about, but I just didn’t know that’s what it was called. That turned out to be the case.

A web search didn’t yield many results, but I’ve found this podcast from 2016 that had some references to it. Fortunately, there’s a transcript there and I was able to skim it to get a gist of it. If I haven’t misread it, my blog post from the day before my talk was exactly about that (The QA’Role in a Scrum Team), so those are my thoughts on it. 🙂

What should the Burndown be based on? Story Points? A count of stories? or is it based on hours assigned to tasks?

The Burndown represents the Sprint and it tracks the work to be done within the Sprint. That work is represented by the Sprint Backlog Items (the “tasks”), which are the way the team found to implement the user stories.

It’s very common for Scrum Teams to size those tasks in terms of hours, in which case, the number of hours is used when updating the Burndown chart. I’ve also worked on teams where we’ve decided to only track the number of tasks, instead.

The team decides what works best and has the autonomy to change the approach from one Sprint to the other, based on what the team believes the best approach is.

Is there a formula to calculate the velocity of the team?

It’s very common to calculate velocity based on the average of story points (if that’s how the user stories are sized) delivered by the team in the last 3 Sprints. We average it like that in order to account for fluctuations from Sprint to Sprint. For example, in one Sprint the team may deliver 60 story points, and then 50 on the next one. Why the drop? It could be because a team member was off sick for two days.

Also, as the team matures, the velocity tends to go up. Whenever the team formation changes (for example, a team member leaves and a new one joins in), the velocity tends to drop for a couple of Sprints. Averaging the last three Sprints help manage these fluctuations.

Who amongst the Scrum Team should take down notes for the feedback provided by the stakeholders during the Sprint Review (Demo)

That would normally be either the Product Owner or the Scrum Master, but I always encourage the other members of the development team to also take down notes where they see fit. They may see things that maybe neither the PO nor the SM picked up. It’s a group effort.

Where do Developers document what was coded?

Different people, teams, organizations do it in different ways. My personal favorite approach is a combination of things:

  • Write good specs (aka “tests”). I believe there’s a good example at the bottom of this post. I also have a whole set of posts around testing;
  • Add good comments to the Pull Request, referring back to the user story it implements. Include a link back to the user story in the tracking system used (Pivotal Tracker, Team System, Jira, etc…);
  • Add a link to the Pull Request in the user story on the tracking system.

With such approach, we can learn about things both ways: we may come to the user story to find out what code changes (pull requests) were made to implement the story, or maybe looking at the code changes (pull requests) and figure out what they were made (link back to user stories).

How should the information gathered from a 1/1 conversation between Dev and Business be shared with the entire team?

It would depend on the nature and outcome of the conversation. Here are some ways that could go:

  • If a new acceptance criteria has been come up, update the specs/tests;
  • If a user story has been clarified, update the user story on the track system to reflect that clarification (maybe a change in the wording?);
  • Bring it up at the daily scrum to share it with the team;
  • If a more in-depth discussion with the team is needed, book a meeting and share the information there;
  • Add comments to the user story in the tracking system;
  • Drop a note into whatever messaging system the team uses (Slacks, MS-Teams, email, etc.)
  • All of the above?

Pick the ones that work for the team and the business.

Are there agreed-upon roles and responsibilities for the various players? Ambiguity makes it more challenging – especially if Agile is new to the org

The Scrum Framework lists the three roles: Product Owner, Scrum Master, Developers. Within developers, it’s up to the team to define the roles. A development team may start with a hard separation between QA and coder, for example, the QA person tests the work produced by the coder.

As the team matures its collaboration skills, the coder may start helping QA, by teaching them how to write automated tests, while QA may start helping the coders by helping them understand the acceptance criteria better.

The roles and responsibilities within the team may change as per the team’s needs and how it grows in maturity over time.

If the user stories are not completed till we release to production then the burndown will not go down till release is done typically at/after the end of the sprint

This question touches on the Definition of Done (DoD). The idea is to have potentially releasable increments at the end of the Sprint. If the DoD for user stories at the end of the Sprint includes something like “feature deployed to production” and that item hasn’t been checked off, then yes, this story rolls over into the next Sprint. If the team tracks tasks by hours, then the hours associated with deploying to production rolls over to the Burndown for next Sprint.

On the other hand, “deploying to production” may be part of DoD for release. Depending on how the business does things, a release may only happen after a number of Sprints, with an aggregate of features built during those Sprints, so at that point, the release’s DoD should include the “deployed to production” check.

Wrapping up

I saw the tweet below early this morning. What a great way to start off my day!!

 

Leave a comment

How to test private methods

A very common question I hear from developers is “How do I write tests for private methods?”. My immediate answer is “You don’t!”. Technically, if you’re in C# Land, you can instantiate the class and then use Reflection to call the private method. But please don’t!

Say you have some class like this one:

Of course, instead of comments, you’d have the actual code. You get the point.

You then decide to clean things up a bit and extract the “make sure all the ingredients are in” code into a separate, private ValidateIngredients method, like so:

That’s usually the moment when developers ask “how do I test that private method?”. If we have tests for the main method (DoTheMagic, in this example), then ValidateIngredients already get test coverage.

Quite often, when developers feel strong about having separate tests for a private method, there’s a clear indication that the private method should really be a public method on a separate class. Think Single Responsibility Principle.

Following the example above, we create a Validator class and move our validation logic in there:

And then we use that validator in the previously shown class:

You’ve probably noticed that we also introduced an IValidatePotion interface. Think Dependency Inversion Principle. One of the benefits here is being able to isolate tests for the AwesomenessPotion and AswesomenessPotionValidator classes.

2 Comments

Know Where to Look

Tired of bad news yet? Well, maybe you should be aware of where you’re looking!

I was born and raised in Sao Paulo City, Brazil. There was a time in my life where my morning rituals involved watching the local news as I got ready to leave for work. Every single day, no exception, the core of the news centered around how many miles of traffic jams we had and what kind of records we’re breaking that day.

Brazil, Buildings, City, Cityscape, Clouds, Sao Paulo

Starting the day off like that was a torture. I felt miserable even before leaving the house. I didn’t own a car at the time, so that wasn’t an option for my commute. I could take the bus, on a ride that could take anywhere between 1 to 2 hours (or more) on any given day, through a congested city, on a bus that was always crowded and many times I couldn’t even get in (I’d be hanging off the bus, nearly missing hitting trees and lightpoles on the way). I could ride my motorcycle, which would get me to work faster, but the stress level would still be higher due to the risks of riding in that chaotic city. But I had to make that choice at some point.

I’d then get to work and the co-workers would be complaining about traffic. Going back home, it was even worse (drivers’ skills certainly worsen by the end of such days).

Still, I tortured myself watching the news everyday. It felt like Groundhog Day. So why did I do that? No idea. All I know is that I’ve eventually realized I shouldn’t be doing that. I replaced that nonsense habit with something like listening to music that lifts my mood, and other activities of such type.

That was in the early 2000s. I remember thinking: “man, why do they only show bad news? Isn’t there anything good out there to be shown?”

What’s up in the air?

The air quality in Sao Paulo is pretty bad. But I didn’t quite know how bad, since that’s the only air I had known up to that point.

Skyline, City, Urban, Cityscape, Skyscraper, Building

I then move to Houston, Texas, in 2002. While Houston is one of the biggest cities in the US, it feels small to me compared to Sao Paulo. So one of the first things I just had to noticed was the kind blue sky. The next thing, the quality of the air: so, but so much better than Sao Paulo’s! I could actually feel it as I took some deep breaths.

Know where to look!

But why am I saying that? Well…

  • if all I eat is junk food, I may not be aware of what better foods taste like;
  • If all I listen to is bad language, what should I expect to come out of my mouth when I talk?
  • If all I watch is bad news, I’m probably doomed to think that life is really bad!

people can't see air, fish can't see water - IF PEOPLE CAN'T SEE AIR... CAN FISH SEE WATER... conspiracy keanu

So I’ve been making a point to myself to check what’s good out there as often as I can. Seeing examples of good people doing good things out there is always inspiring and that’s why life should really be about.

Here are some resources I follow on a daily basis:


TanksGoodNews

John Krasinski’s Some Good News

Upworthy

Intelligent Tuesday

Please, drop in a comment to suggest any resource you might recommend so I can check it out!

Leave a comment