Home Java Java-tips Principles_and_practices Style Programming Style Guideline

Ask Questions?

View Latest Questions

Advertisement


 
 

Programming Style Guideline
Posted on: July 27, 2006 at 12:00 AM
Motivation for programming guidelines

Java Notes: Programming Style Guideline

Contents

  • I. Motivation for programming guidelines
  • II. Comments, indentation, spacing, braces, ...
  • III. Naming conventions
  • IV. Error Handling
  • V. Visibility and storage type

I. Motivation for programming guidelines

Maintainability. If there's one idea that could serve as a guide to good programming, it's maintainability.

Low cost and more fun. Most of the cost of software, 80% is a frequently used number, is in the maintenance phase: fixing bugs, adding enhancements, adapting it to new systems, etc. That would be a good enough reason to aim for maintainability, but that's not really why I'm saying it. The same things that make software maintainable also make it easier and more pleasant to work on in the first place. Sometimes it takes a few extra key strokes or an extra moment of thought, but those are usually quickly repaid.

Factors. Three topics that cover a lot of the maintainability territory are:

  1. Readability - There is an astounding range of readability. Always keep it in mind.
  2. Simplicity - Don't add unnecessary complication and duplication. KISS.
  3. Convention - Program using standard conventions as much as possible. See RH story.

If a program is useful, it has to be changed!

If a program is useful, users want enhancements, bug fixes, etc. It's also necessary to update programs regularly because the computing environment continuously changes.

Someone has to change them, and surprisingly often, it isn't the original programmer. Therefore, one of the most important characteristics of real programs is that they must be readable and have a style that allows changes.

II. Comments, indentation, spacing, braces, ...

Comments

Header Comments

Program must have comments at top which identify it. Which include:

  • Name and purpose of the program. Identify the class and assignment, and what the program does. A single line is sufficient for most student programs. If you write a program that is not a fixed assignment, the documentation will have to be much more extensive.
  • Your name
  • Date

The exact format is, but all information must be there.

"Paragraph" comments

Statements are should divided into clear sections (like paragraphs), separated by a blank line, and a comment at the beginning telling what this "paragraph" does. Put the comments at the beginning or on the statements they apply to, not at the end of the section.

Avoid useless comments

Don't write comments unless they help explain why something is being done, or explain something that is not immediately obvious to the reader. Just paraphrasing the action of the Java statement makes the program harder to read. For example, the following comment is very bad, even tho it is a true statement.

    fishCount = fishCount + 1;  // Increase fishCount by one.  BAD
Use javadoc
For larger programs, the systematic use of javadoc style comments is necessary.
Declare variables (1) at first use or (2) at front with comments.

There are two good styles for declaring variables, and one bad style.

  • Good. Declaring variables when they are first used.
  • Good. Declaring variables at the beginning, one per line, with comments.
  • Bad. Declaring many variables in one declaration.
One variable declaration per line

Putting as many variables as you can on a line saves space (good), but at the expense of readability (bad). Variables declared on their individual lines are easier for a programmer to find, and allow writing a brief common following them. For example,

    int averageRain, n, currentVal, max;

Might better be written as follows

    int averageRain;   // Average rainfall over all time periods.
    int n;             // Number of time periods.
    int currentVal;    // Amount of rain in the current time period.
    int max;           // Maximum rain in any time period.
Space methods, inner classes, etc
Put white space between major elements of a program.

Indentation

Programmers universally agree that good indentation is required.

Blanks, not tabs
Use multiple blanks instead of tabs. Because there is no fixed specification of how big a tab is, when someone else looks at your program on their system, the alignment of statements is often quite different (and wrong). You would think that relative indentation would be preserved, but in practice the indentation is usually a mix of spaces and tabs, and the result is bad. Some editors, like NetBean's editor, has a reformat source command that will fix everything. Some editors have a "soft tab" option which automatically replaces tabs by blanks. Use it if you have it.
Use an IDE
Statements must be indented correctly. Every experienced programmer insists on this. Good IDEs will perform indentation.
Indent size 4
Four spaces should be used for each indentation level. Programmers use 2, 3, or 4 spaces for indentation, but 4 is the most common and the most readable.
Continued statements
Statements that must be continued over more than one line should indent the continued part two indentations is possible.

Spaces and newlines

There are standard ways to use white space (blanks, and newlines) to make programs easier to read.

Method calls and keywords, and the left parenthesis
  • No space between method name and the "(". Eg, "y = f(x)", not "y = f (x)".
  • One space between keywords and "(". Eg, "if (a < b)", not "if(a < b)".
Spaces in expressions
I've seen a number of rules about spaces in expressions. Use them to make expressions more readable. More specific guidance is needed here.

Declarations

One per line
Take advantage of this to add // comments to variables whose meaning isn't clear from their names, or where their range of values is important to understand. Textbook authors are under pressure to reduce the length of their programs so sometimes compress their declarations. All coding standards want one declaration per line.
Where?
Old? Sometimes you see advice that variables should be declared at the beginning. Partly this is a result of habits from older languages that required this style. The Sun guidelines suggest that local variable declarations should be made at the beginning of a method, not where they are first used.

Minimize distance between declaration and use. It is probably much easier to read code if the distance between declaration and use is minimized. This argues for declaring variables at their first use.

Inner scope. Generally variables should be declared at the innermost scope that they are needed at. This is way a for loop variable should be preferably declared in the loop header. All local variables are allocated when a method is entered, even if they are in an inner block, so there is no extra allocation penalty as is sometimes mistakenly claimed.

See Programming in the small - variable declarations (ivan.truemesh.com/archives/000596.html) for a discussion of this.

Don't reuse variable names
Never use a variable for more than one purpose. New variables are are basically immeasurably cheap in terms resources (CPU and memory), so don't make the program hard to read by reusing one for another purpose.

Braces to group statements

Always use them
Braces should always be used to enclose the bodies of the control flow statements, even if there is only one statement in the scope. This is a common rule. The reason is that the it's more error prone and harder to read if the use of braces is erratic. There are cases where this might be violated, but they should be few.
K&R or Allmann style
Sun's guidelines specify K&R style braces (opening brace on end of statement), but the Allmann style (opening brace directly below first character of statement) is also OK. Beginning programmers often like the Allmann style better because it's easier to match beginning and end. Experienced programmers often prefer the K&R style because more of the program is visible on the screen/page and the visually disruptive blank line doesn't separate the if from the true clause. Many IDEs (eg, NetBeans) will indent the program either way for you.

III. Naming conventions

Naming is perhaps the single biggest contributor to readability.

Names should be meaningful
. Don't use meaningless or misleading names. Certain short names are used by convention in loops. Eg, i and j for integer counters/indexes, iter for iterators, s for string value in an extended for loop, etc.

If names are well chosen, comments aren't so important.

Case
  • Start with lower case, continue in camel case : variables, methods, packages. Eg, fishWeight.
  • Start with upper case, continue in camel case : classes, interfaces. Eg, FishCalculator.
  • All uppercase, separate words with underscore : constants. Eg, MINIMUM_FISH_SIZE.
Instance variable prefixes
Prefixes are commonly used to distinguish them from other local/class variables. Typical choices are ("m", "m_", "f", or "_"). Other languages often call instance variables "member" variables or "fields", hence the use of those letters. I often use "_", altho this is sometimes criticised as violated the Java standard. Don't get too attached to one special way - if you go to work for an organization, they often have a rule about naming instance variables, and you'll have to use that rule.
Plural names
Use plural names for for arrays and other data structures.

IV. Error Handling

"Happy Trails" Programming

Real world programs must handle problem cases, such as illegal input, but beginning students may ignore problem cases unless specifically required to do so. The more advanced the course, the more emphasis is put on handling errors.

Error checking

  • Don't catch errors you can't handle.
  • Don't have empty catch clauses, except in a very few cases.
  • Fail Fast Philosophy. If your program has a bug in it, you want to find out as soon as possible. It's really bad when
  • Don't silently ignore errors. If you detect an error, make it known.

V. Visibility and storage type

The general rule is that variables should be private, and methods public. That's a good starting point.

Static/class
Other than constants (static final), you should rarely have static variables. Static methods are appropriate if they don't depend on instance variables.
Instance
Instance variables should be declared private almost always.
Local variables
should be used instead of an instance variable if it works just as well.

Exceptions

  • Don't catch an exception if you can't handle it.
  • Don't silently ignore exceptions.
  • Don't throw Exception - make it more specific.
  • If you create an exception object to throw, be sure to include a helpful exlanation in the constructor.
  • If you can handle a checked exception (eg, one of the I/O exceptions), that's generally better than adding a throws clause to your method/constructor and letting someone else handle it. But only do this if you can really do the right thing with it.
  • If you let an exception propogate upwards (eg, with a throws clause), it should be obvious to the caller what the problem was. If not, you should translate it into your own exception. For example, if a constructor can't initialize a dictionary, instead of propogating a FileNotFoundException, catch it and rethrow your own MissingDictionaryFileException. That let's a caller know what happened and give a meaningful error message to the user.

GUI Design

Look at typical user interfaces
You will see how they are arranged. Most programs use a standard system of grid, gaps, subpanels, and borders.
Window borders
An empty border is almost always appropriate around a window. When you drag components near the edge, NetBeans will automatically suggest a good placement.
Gaps
As with borders, NetBeans will suggest reasonable gaps between elements. Gaps between components are typically about 5 pixels, Between separate logical groups the gap should be larger.
Variable grid design
A typical design technique is to use a grid of rows and columns. Each row and column can be a different size, but all elements in a given row will be the same size, and similarly for columns. Elements may span several rows/columns (like rowspan or colspan if you know HTML).
Subpanels
Not only does the use of subpanels help layout related components, but the subpanels can easily be moved around to make the window layout easy to change. Sometimes a titled border on subpanels can make them more useful to the user.
Expandable
If the design contains elements that should naturally expand, please make sure they expand correctly.
More help
  • Sun has put their Java Look and Feel Design Guidelines (2nd Edition) book online at java.sun.com/products/jlf/ed2/book/. The Chapter 4 Layout and Visual Alignment section is very useful. Similar guidelines are available from Microsoft and Apple.
  • A good book is GUI Bloopers: Don'ts and Do's for Software Developers and Web Designers by Jeff Johnson.
  • NetBeans has some good tutorials on the use of their GUI editor. Take a look at www.netbeans.org/community/releases/50/index.html. There are links to tutorials on several other pages too, so you might want to navigate around a bit.

Optimization

  • Optimization: Your Worst Enemy by Joseph M. Newcomer has some nice, typical stories about why you be cautious about worrying about optimization early in program design an construction.

References

Sun's guidelines. Perhaps the most common coding guidelines are Sun's Code Conventions for the Java Programming Language, which can be read online of downloaded in several forms from java.sun.com/docs/codeconv/. My guidelines are basically theirs with a few changes.

Advertisement


DMCA.com