Code Tips That Will Save Your Life #1

23 בספטמבר 2011

אין תגובות

Tip #1 : Document & Comment Your Code.

   
mmmm… liver, fava beans and bad code, my favorite.


"Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live."

 

You can never know when this phrase will turn into reality, so you'd better be prepared.
This is the beginning of what I expect to be a long series of coding tips and best practices that will help you write better code and might even save your life one day!

 

Tip #1 : Document & Comment Your Code


I really wanted to call this "Document & Comment Your Code Properly" but then I realized that you can't do properly something that you don't do at all.

I have seen code written by so many developers, and about 4 out of 5 had the same thing in common: They did not document their code.
Some didn't even write a single comment throughout several thousand lines of code, and some would write maybe a comment futilely explaining in 5 words the monstrosity of a recursive method they just wrote some 200 lines of code later.

This has to stop!
You may think your code is so clear that it does not need comments, but that’s because you just wrote it and it's fresh in your mind. Even the most well-written code can't be instantly clear to someone who isn't you, that is because it is written in code and will never match an actual language.

And if you think to yourself "If it was hard to write, it should be hard to understand", you might want to look for advise elsewhere.  

The good news for all you other .NET developers are that it's not that hard and part of the heavy lifting is done for you, saving you about half of the work.
Don't believe me? Go ahead, open a new project on Visual Studio, yes I will wait…

It's open? Good.
Create a new class; name it to your liking like so:

  public class CookieMonster

  {

      // A whole lotta nothing.

  }


Now for the cool part, put your text marker one line above the class declaration and type the character '/'  three times (yes Three).

  /// <summary>

  ///

  /// </summary>

  public class CookieMonster

  {

      // A whole lotta nothing.

  }

 

It’s a miracle you say? No, this is not some kind of witchcraft, this is XML Documentation, and it will be the only way you are going to document your code from here on.
Go ahead write some class description, don't be shy. You will see that you can add some more tags, like remarks, code usage examples and so on.

 /// <summary>

 /// The <c>CookieMonster</c> class is responsible for all

 /// cookie disposing (a.k.a: eating) in the system.

 /// </summary>

 /// <remarks>

 /// Beware:

 /// The <c>CookieMonster</c> may dispose of your cookies without a warning.

 /// Disabling cookies may result in exceptions and rage.

 /// </remarks>

 public class CookieMonster

 {

     // A whole lotta nothing.

 }

 

 

Let's try something new, add a method, maybe a property, you can do it, you do it all the time.

  public class CookieMonster

  {

      public bool IsFull { get; set; }

 

      public bool Eat(System.Net.Cookie cookie)

      {

          if (!IsFull)

          {

              cookie.BeEaten();

          }

 

          return false;

      }

  }

 

Now, do the same trick with the triple '/' above the property and the method.

 public class CookieMonster

 {

     /// <summary>

     ///

     /// </summary>

     public bool IsFull { get; set; }

 

     /// <summary>

     ///

     /// </summary>

     /// <param name="cookie"></param>

     /// <returns></returns>

     public bool Eat(System.Net.Cookie cookie)

     {

         if (!IsFull)

         {

             cookie.BeEaten();

         }

 

         return true;

     }

 }

 

Yes it also works for methods, properties and members!
And if you fill it up it will look like this:

 public class CookieMonster

 {

     /// <summary>

     /// Indication whether the <see cref="CookieMonster"/> is full

     /// </summary>

     /// <remarks>

     /// The <see cref="CookieMonster"/> is NEVER full

     /// </remarks>

     public bool IsFull { get; set; }

 

     /// <summary>

     /// Eats a single cookie, disposing it.

      /// </summary>

      /// <param name="cookie">

      /// The <see cref="System.Net.Cookie"/> to be eaten

      /// </param>

      /// <returns>

      /// Indication whether the cookie was eaten or not.

      /// <remarks>

      /// Note: the cookie is always eaten!

      /// </remarks>

      /// </returns>

      public bool Eat(System.Net.Cookie cookie)

      {

          // Checks whether the CookieMonster is full

          if (!IsFull)

          {

              cookie.BeEaten();

          }

 

          return true;

      }

  }

 

So this is nice and all, but why bother you ask?
Well try to write some code that uses this class, see anything different?


 

 

Indeed your eyes do not lie to you, that's full Intellisense right there.
But that’s not all, now comes the really cool part.


One of the nastiest jobs a developer can get is making a program documentation document. These are usually very long, very boring, very incoherent Word files that supposedly have all the information needed to maintain the said program. Usually they end up unread for months until someone new needs to update them, but never the less at one point or another your boss will ask you to write one.

Now let's say that the day came, the boss knocks on your door and says: "Hey there Johnny boy. We are a bit ahead of schedule so we have some spare time, how about writing a Word file documenting that module you have been working on for the past 6 months?  Great, send it to me on Monday, cheers."

And now let's say that you read this post 6 months ago,  thought XML Documentation is indeed a good idea, and commented all your code with it.

You just go to your project Properties -> Build -> And set the XML Documentation File field.  

 

 
Now build. You will find that in your bin folder appeared a new XML file containing all the documentation that was in your code.
Now you can do whatever you like with it, use your own XSL transformer to convert it into an html page, index and search on it, or use a third party application to convert it into the document type you desire, and these come in many flavors.

A very commonly used open source tool is Sandcastle, together with Sandcastle Help File Builder they create a very powerful tool that enables you to create MSDN like documentation or chm files from your XML Documentation.
So now you can go back to slacking off in peace while your boss thinks you are working hard on that document.

 

That’s it for now, this post has turned out to be much longer than I expected.
I hope you've found this helpful, and if not, well… you have the comment section for that.

For more info on XML Documentation check out the MSDN page.

And don't forget:
Code is usually easy to write, but rarely easy to read.

Josef.

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. (*) שדות חובה מסומנים