Ask Questions?

View Latest Questions



Posted on: July 27, 2006 at 12:00 AM
Human readability is extremely important



Purpose of this lesson:
  • Human readability is extremely important.
  • Especially important factors: Naming, indentation, conventions.

Humans must be able to read the programs

Source code is read by both the compiler, which doesn't care about your writing style, and people, who care enormously about your writing style.

ALL programmers insist that certain rules be followed. Some of the most important are:

  • Indentation. Statements which are contained within something else (a class, a method, a loop, etc) must be indented on indentation amount to the right. There are several styles for this; use one of them.
  • Meaningful names. Variables, methods, classes, etc must be given names that mean something to the reader. Use names like a, b, and c only when there is no inherent meaning in a variable -- it's just an abstract number.
    See Names for a more detailed discussion.
  • Conventions are important to follow. There are standard naming, formatting, documentation, and usage conventions for Java. the organization you work for may have additional conventions. Use of these conventions makes program source code much easier for others to read.

Who's going to read your code?

Instructor. If you're taking a programming course your instructor will care a lot about the indentation and meaningful names. Some instructors have a specific class standard for formatting your program. Others allow a range of standards. None allow chaotic code formatting.

Other programmers. If you work on a project that will ever involve other programmers, eg, for maintenance, you must write in a conventional style. Multi-programmer projects often establish a set of standards for all programmers on the project.

Yourself. Surprisingly many student programs use meaningless, deceptive, or multiple-use variable names. When asked what value is in that variable, they are often unable to tell me. Variable names should mean something clear to to the reader.

Tabs (no) or spaces (yes) for indentation

The problem with tabs is that there is no single definition of how much horizontal space a tab takes, so what you see in your program may be (and often is) very different from what I see when I look at your program. The indentation may be consistent, which isn't so bad, but if you tab to the comments then it usually doesn't work so well when I look at it. And the worst is mixing tabs and spaces because a change in the tab size guarantees things will not be correctly aligned. The programming convention for Java is to use 4 spaces.

Copyleft 2005 Fred Swartz MIT License