Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Spring Framework | Web Services | BioInformatics | Java Server Faces | Jboss 3.0 tutorial | Hibernate 3.0 | XML

Tutorial Categories: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML


 

Java Tutorials


 

 

Struts Tutorials

Struts Resources

Visit Forum! Post Questions!
Jobs At RoseIndia.net!

Java Notes: Programming Style Guideline

Here is a big list of what I look at in trying to assess the quality of programs. These issues that are addressed here are at a moderately low level.

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

M A I N T A I N A B I L I T Y

Cost or fun. Most of the cost of software, maybe 80% on average, 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.

Breaking it down. We can make a top-down dissection of what makes for maintainability. 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.

Coding Guidelines - Based on Sun's Guidelines

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.

  1. Spaces, not tabs, should be used for indentation. Most IDE's and editors automatically convert tabs to spaces. Reason - there is no uniform definition of tab size, so tabbed source often looks bad.
  2. Declarations
    • One per line, as Sun suggests, but 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..
    • Sun suggests that local variable declarations should be made at the beginning of a method, not where they are first used. Altho this is a good style, declaring at first use is fine too.
    • Don't reuse 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.
  3. Braces to group statements
    • Always use them, even if there is only one statement in the scope. (Just repeating Sun's rule.)
    • 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 typically 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.
  4. Naming - This is perhaps the single biggest contributor to readability.
    • Instance variables are commonly given a special prefix to distinguish them from other local 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.
    • Arrays and other data structures should have plural names.
  5. Visibility and storage type.
    • Other than constants (static final), you should rarely have any static variables.
    • Instance variables should be declared private in almost call cases.
    • Don't use instance variables where a local variable does equally well.

Other thoughts

  • Program must compile, otherwise there will be no credit.
  • Indentation must be correct.
  • Identifier names must be meaningful.
  • Don't reuse a variable for more than one purpose.
  • Identifier names must conform to Java conventions:
    • Variable names start with a lower case letter. Eg, weight.
    • Class names start with an upper case letter. Eg, Calculator.
    • CamelCase is used for multiple words in variable and class names. fishWeight, FishCalculator.
    • Names constants are all upper case and multiple words are separated by underscores. Eg, FISH_PER_MILE.
  • Comments should be accurate. There should be an identifying block of comments at the front. If the names are good, you don't need many comments in the program.

1. Readability Problems

Naming - Very important

  • Names of variables, etc should make their use clear. Don't use meaningless or misleading names. In some cases, an arbitrary name must be used, but avoid that if you know what the meaning of the name is.
  • Case: Class names should start with an upper case character. Variable names should start with lower case. Constants should be all uppercase.

Comments, indentation, spacing, ...

  • Indentation. Statements must be indented correctly. Every experienced programmer insists on this. Good IDEs will clean up your indentation.
  • Header. Program must have comments at top which identify it. These comments should include:
    • Name of directory and file.
    • Purpose of the program. Include both assignment number, and what the program does. A single line is sufficient for most student programs. If you write a program the is not pre-specified for you, the documentation will have to be much more extensive.
    • Your name
    • Date

    I'm flexible about the exact format, but this information should be there.

  • "Paragraphs". 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 because they reduce readability. 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.
  • One variable declaration per line is a good rule to follow. 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.
  • No tabs please. 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.

2. Programming Style

Additions will be made as more programming concepts are covered.

Statements

  • Proper use of if and else else.
  • Use Loops. If you have code that is repeated, try to generalize it and make it into a loop (while, for, or do..while). Repeating code that should be in a loop is regarded as a major programming sin. Once you become comfortable with loops (and later arrays and methods), this will be easy.
  • Always use braces is advice that many good style books give. Avoiding them when the scope of an if or loop contains only one statement is somewhat error prone.

3. Correctness and Usability

Naturally a program must run and produce correct output. Unless there are serious problems, the quality of the user interface will not be important in the beginning courses.

Doesn't compile - no credit

Generally no credit will be given for a program that doesn't even compile.

Error Handling and "Happy Trails" Programming

Altho real world programs must handle problem cases, such as illegal input, students may ignore problem cases unless specifically required to do so. The more advanced the course, the more emphasis will be put on handling errors.

But if you do check for errors, observe the following.

  • Don't silently ignore errors. If you detect an error, make it known.
  • Don't print results that are wrong because you ignored bad input data.

If a program is useful, it will have to be changed!

If a program is useful, the users will 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. Grading will emphasize readability, programming style, and correctness.

Miscellaneous

RH Story

Conventions may not always match exactly how you think, but they have a big payoff in the long run.

I once worked with a programmer, RH, who had "unusual" style beliefs. He firmly held that the first clause in an if-else statement should be performed if the expression was false, not true!!! So, unknown to others, he made a private copy of the compiler and changed the code generation for if so it worked his way. Yes, every if statement in his modules worked the opposite of the way everyone else expected, even tho it looked like "regular" code. Unfortunately, he was a very productive coder. Epilog: He was fired when this was eventually discovered.

Ask programming questions?

 

 

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

1 comments so far (post your own) View All Comments Latest 10 Comments:

how to use switch and if loops

Posted by ashley on Saturday, 10.17.09 @ 14:04pm | #91845

  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification

Tell A Friend
Your Friend Name

 

 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright 2007. All rights reserved.

[an error occurred while processing this directive]