DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

Clear code and less comments

Denzel D. user avatar by
Denzel D.
·
Jun. 30, 10 · Interview
Like (0)
Save
Tweet
Share
3.38K Views

Join the DZone community and get the full member experience.

Join For Free

I don’t know how many times I got to the problem that code shouldn’t be commented first, but written in such a way that only by looking at it you can catch the logic behind it. Then, comments can be introduced as an additional, complementary element to describe the most complicated parts of a program.

I remember reading my first programming books and almost at every step I’ve encountered the same advice – comment, comment and once again comment. And indeed, many beginner developers (and even developers with experience) tend to follow this advice. Now don’t get me wrong, I am not that kind of person that is completely anti-comment. I am commenting my code, but there are limits to what should and what shouldn’t be commented and placed inside the source file for reference purposes only.

What I am talking about is the possibility to write code that speaks for itself. Here is an example:

void LoadPlugins()
{
var catalog = new DirectoryCatalog("plugins");

var container = new CompositionContainer(catalog);
var batch = new CompositionBatch();
batch.AddPart(this);

try
{
container.Compose(batch);
}
catch (ChangeRejectedException exc)
{
Debug.Print(exc.Message);
}
}

This is a sample method used in a MEF-based application that loads a set of plugins from a folder called plugins. If you read through the code and you are familiar with MEF, you pretty much already see how it works. The variables are named in a way that pretty much explains what each one of them stores. If you follow through the code you can understand the process that is executed by the snippet. This kind of code can be considered self-documenting, since no additional documentation is required to describe it.

Now here is another example, already with comments, but try to understand their purpose:

private void button_Click(object sender, RoutedEventArgs e)
{
// Sets the storyboard
Storyboard settings = (Storyboard)this.FindResource("MainBoard");
// Begin the storyboard animation
settings.Begin();

//Check if locationSearchBox is empty
if (!string.IsNullOrWhiteSpace(locationSearchBox.Text))
{
Properties.Settings.Default.Location = locationSearchBox.Text; // Set the property to the locationSearchBox text
UpdateData(); // Call UpdateData
}
}

What this code does is it triggers a storyboard animation and saves a setting. After that, a method is called to update some data behind it. The main problem with this code is the fact that the naming convention is structured very pporly. For some reason, the storyboard is called settings, but at the same time it is looking for one inside the canvas that is called MainBoard. If the storyboard instance would have been created outside the method, how another developer is supposed to know what the Begin() method will do? In the existing context, it can do anything. The confusing name will create the impression that it actually works with settings.

Also, you can see here that the comments are completely redundant. Indeed, those could help, for example, when calling the UpdateData() method, so that another developer would clearly see what is updated. The current comment doesn’t add much value to the line. Unfortunately, comments like these are introduced a lot in major projects by various developers.

Now let’s take a look at the same piece of code, refactored and commented the right way:

private void button_Click(object sender, RoutedEventArgs e)
{
Storyboard settingsStoryBoard = (Storyboard)this.FindResource("settingsStoryBoard");
settingsStoryBoard.Begin();

// Update the user location data based on
// the contents of the location box.
if (!string.IsNullOrWhiteSpace(locationSearchBox.Text))
{
Properties.Settings.Default.Location = locationSearchBox.Text;
UpdateData();
}
}

Two comment lines and a piece of code that speaks for itself. Generally, I tend to stick to this exact technique.

Someone can say that developers are not the people who want to document stuff and that is the job for technical writers who later on describe the source code structure – after all, the developer did a lot of work on writing the actual logic. This is just an excuse – good developers can explain what their code does. Good naming and proper comment usage is a way to do that.

Before writing a program, mind a few things to make the code easily understandable by the people that will read it after you. After all, maybe you as the developer won’t be able to explain your own code after a few years (or even months) if you don’t follow some simple recommendations:

•    Use proper naming
Once you name your variables, classes, methods and functions properly, you will see that you will reduce the need in comments to the minimum. The code will become self-documenting.

•    Do not use redundant comments
Don’t comment a call unless you want to describe what that call is doing. This also applies to anything else, as I’ve seen comments to class initialization saying that it creates an instance of class T. This kind of comments takes space but after all won’t help much later on. Your comments should describe the process behind the commented line, not rephrase the line itself.

•    Don’t over-comment
Not every line should be commented. If there is a code block that performs a specific task, use block comments to describe that specific block instead of commenting every single call or initialization.

•    Don’t put non-code related stuff in comments
For example, licenses. I’ve seen source files that declare a single interface, but contain more than a hundred lines with the license attached to the code. If you need to reference a license, just distribute the code with a text file and reference the name of the file. Enough. I really want to see a person who will analyze the license put inside a source file. So far, I didn’t meet anyone that would do that.

•    Don’t try to avoid comments
With all this being said, comments are still needed. Don’t try to avoid them, but use them wisely.

You should also consider the fact that this article is nothing but a set of my own recommendations and opinions. You can adapt them to your own coding style, since it is highly dependent on how you code and what tools you use to code.

code style Clear (Unix)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • What To Know Before Implementing IIoT
  • Shift-Left: A Developer's Pipe(line) Dream?
  • Use AWS Controllers for Kubernetes To Deploy a Serverless Data Processing Solution With SQS, Lambda, and DynamoDB
  • Building the Next-Generation Data Lakehouse: 10X Performance

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: