Suppose you’re reviewing a modest-sized geocaching program composed of 6,000 lines of Java Code. It’s late at night, and you’re trying to figure out how a certain subroutine works. You know it asks the user for information about Longitude, but you aren’t sure how it works under the hood. Which of the below samples is easier to read?

Sample A?

Or…

Sample B?

Hopefully, you would say the answer is Sample B. Properly indenting code is an important part of any programming, or code maintenance in general. Without it, you end up with one long string of lines, sometimes looking like gibberish.

In general, every { and } character, which comprise blocks of code, should be on its own line, as follows:

Sometimes, people put the { character on the same line as the conditional or other expresson, such as:

However, nobody should write code like this:

Besides being really confusing, pretend the above line is line number 43. Suppose the program crashes with an error message targeting “Line 43”. Apart from looking at the type of exception or error message, it could be rather difficult (particularly on longer lines) to figure out which conditional is throwing the error. Alternatively, mathIsWorking could be a protected or otherwise read-only member. If you really have to condense the above code to one line, you should do something like this:

Many text-editing tools that are programmer-friendly have “Format” options. Visual Studio and Eclipse are examples of this – simply look through the menus for a “Format Document” option, and clicking it will automatically indent your code (and sometimes even put the { and } characters on their own line). However, it’s always best if a beginner learns to format code properly by herself or himself.

The main pattern that I’m depicting above, of course, is the concept that each block of code should be indented on an appropriate “layer”. This is similar to how you might see a “bulleted” list indented for each additional layer of complexity:

Types of Food

  • Fruit
    • Apples
    • Bananas
    • Oranges
  • Vegetables
    • Potatoes
    • Broccoli
    • Carrots
      • Raw
      • Steamed
      • Chocolate-Covered
    • Pizza
      • Cheese
      • Pepperoni

The code samples depicted above are only one way of indenting code. There are several indenting styles (the one I showed was essentially “Kernel Style”, named after the style most commonly used in the Linux Kernel.) However, as long as it’s readable, and not all unindented, it should be fairly easy to maintain and revise the code.

 

Share

Comments are closed.

Post Navigation