Sunday, October 23, 2011

Whitespace... it's free!

I was reviewing today's batch of source code submissions and I noticed that an awful lot of people were not making good use of their whitespace. Please observe the following rules in your code:

  • Thou Shalt Indent Consistently
    As I have mentioned in class, you must be consistent in your indentation level. All code within a code block should be indented to the same level. This also means that when you create a new code block (bounded by curly braces), you indent a level from the previous code block's level.

    While it may not look like such a big deal right now, you need to consider that at the moment you are writing very small programs to solve very simple problems. Once you move on to more complex problems and have to write your own classes and methods and have lots of branching decisions and looping constructions, code written like this just won't do. It is difficult to read and it takes additional time to figure out what lines of code belong in which code blocks.

  • Thou Shalt Insert Blank Lines
    Each bit of code is doing a job. When you change from one task to another, it is customary to insert a blank line. This groups your code within code blocks.

  • Thou Shalt Insert Spaces Between Variables and Operators
    Computer programs tend to be very heavily laden with calculations and comparisons. Let's face it: computers crunch through complex calculations very efficiently and that is why we use them. When you write an equation or a comparison of any sort, you need to have whitespace on each side of each operator, separating the operators from the variables.

  • Thou Shalt Comment Thy Code
    When you are writing your source code, you usually are very familiar with the problem you are trying to solve. You bang out the code quickly, test it, and field it. What happens a few weeks or months down the road? You have been working on other projects but a bug report comes in and you have to go back to fix the code. How quickly can you do it? Do you have to reaquaint yourself with every little detail? What was your thought process when you wrote the code originally? If your code is well and truly self-documented through judicious use of comments, you will be able to locate the problem area easily and implement your fixes.

Be consistent.
Comment your code.
Whitespace is free, use it.