Today was yet another day of spending too much time on a program, but this time the reason was almost stupid. I was just writing a simple program that converts a binary number to a decimal just to get my feet wet in C#. I was taking the input as a string and I decided to use a foreach loop to traverse through the string and fill a character array with each 0 or 1. The only nuance I needed with this loop is an index that will start at 0 and keep incrementing to the end of the string. Not even thinking, I initialized and incremented the index inside the loop and then went on my merry way writing the rest of the program. Of course, by initializing a variable inside an iterative loop, it will only get reinitialized on each run. When it was time to run and test the program, I spent the next half hour looking through my code, outputting intermediate steps to the console, and scratching my heading with the strange logical errors coming up. I finally found the problem child when I was changing some other code, fixed it, and found the rest of the program worked perfectly so I went and ate lunch. I realized something; I could’ve avoided all that heartache by commenting my code as I wrote it!
Up until now, Commenting is only something I would do if a professor or classmate was looking my code or if it was a program I had spent months working on, other than that commenting was a waste of precious time. But commenting is also a way to organize your code more; it’s writing down an exact plan of what you need to do for a function/loop/snippit. Commenting makes you take a step back and actually think about the purpose of what you’re about to write. It’s easy for me to say that if I had to write the program again, I would never initialize a variable inside an iterative loop only for it to be reinitialized because Hindsight is 20/20 but maybe taking that extra couple seconds thinking about the loop would have saved me that half hour later.