Java Coding Conventions
description
Transcript of Java Coding Conventions
07 Coding Conventions
2
• Demonstrate Developing Local Variables• Describe Separating Public and Private Members during
Declaration• Explore Using System.exit• Demonstrate Validating Method Arguments• Describe Using Testing Framework • Distinguish Checked Vs. Unchecked Exceptions• Describe File Organization
ObjectivesObjectives
3
Coding Conventions: ResourceCoding Conventions: Resource
• Reference the Coding Conventions.pdf file on the Module 2 section of the Sharepoint site. • This is a booklet published by Sun that contains all of the
basic coding standards for Java.
• It is easier to learn to follow coding standards early in your work with a programming language.
• Familiarize yourself with the most basic coding conventions, and notice how Eclipse supports you in developing within these guidelines.
• The remainder of this presentation will present more abstract but equally important “Best Practices” for coding.
4
Coding Conventions: Best PracticesCoding Conventions: Best Practices
Declare local variables immediately before use• Defines their scope. • Decreases the likelihood of illegibility or error.
Fields should be private• Declaring fields to be public is usually incorrect, it does
not protect the user of the class from changes in class implementation.
• Declare fields as private. If fields need to be accessed by the user of the class, provide the necessary get and set methods.
5
Separate public and private members during declaration
• It is a common practice to separate the members of a class according to their scope (private, protected, public) It is the choice of the programmer which will come first.
Use Javadoc liberally• Javadoc is a great tool and should be used.
Coding Conventions: Best PracticesCoding Conventions: Best Practices
6
Use System.exit(0) with care on multi-threading
applications• System.exit should be used with care. The normal
method of terminating a program is to terminate all user threads.
Use interface for constants• Creating a class whose sole job is to define widely-used
constants is simple.
Coding Conventions: Best PracticesCoding Conventions: Best Practices
7
Validate method arguments• The first lines of a method are usually devoted to
checking the validity of all arguments. The idea is to fail as quickly as possible in the event of an error. This is particularly important for constructors.
Extra space in argument list• Some programmers feel that using extra spaces within
parentheses - as in ( this ) instead of (that) - slightly increases the legibility of code.
Coding Conventions: Best PracticesCoding Conventions: Best Practices
8
Use a testing framework Use a testing framework to ensure your class fulfills its
contract.
Use zero-length arrays instead of null If a method returns an array which can be empty, do not
allow it to return null. Instead, return a zero-length array. This simplifies the client, in that it never has to check for
null values.
Coding Conventions: Best PracticesCoding Conventions: Best Practices
9
Avoid empty catch blocks• It is not good to have an empty catch block. • When the exception occurs, nothing happens, and the
program fails for unknown reasons.
Be specific in the throws clause• In the throws clause of a method header, be as specific
as possible. Do not group together related exceptions in a generic exception class – this could result in a loss of important information.
Coding Conventions: Best PracticesCoding Conventions: Best Practices
10
Checked vs. Unchecked ExceptionsChecked exceptions : • Represent invalid conditions in areas outside the
immediate control of the program (invalid user input, database problems, network outages, absent files).
• Are subclasses of Exception. • Methods are obligated to establish a policy for all
checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow).
Coding Conventions: Best PracticesCoding Conventions: Best Practices
11
Checked vs. Unchecked ExceptionsUnchecked exceptions : • Represent defects in the program (often invalid
arguments passed to a non-private method). • Are subclasses of RuntimeException, and are usually
implemented using:• IllegalArgumentException.• NullPointerException. • IllegalStateException.
• Methods are not obligated to establish a policy for the unchecked exceptions thrown by their implementation.
Coding Conventions: Best PracticesCoding Conventions: Best Practices
12
Choosing the right collection• Sun documentation refers to ArrayList, HashMap, and
HashSet as being the preferred "primary implementations". Their overall performance is better, and should be used unless a special feature provided by another implementation is needed. These special features are usually ordering or sorting.
• “Ordering" refers to the order of items returned by an Iterator, and "sorting" refers to sorting items according to Comparable or Comparator.
Coding Conventions: Best PracticesCoding Conventions: Best Practices
13
Iterate without an index Some programmers have a strong preference for using
a for-each loop or an Iterator instead of indexed for-loops. Indexes have always been a major source of error, and should generally be avoided if there is an alternative.
Coding Conventions: Best PracticesCoding Conventions: Best Practices
14
File Organization• Each Java source file contains a single public class or
interface. When private classes and interfaces are associated with a public class, they can be placed in the same source file as the public class.
• The public class should be the first class or interface in the file.
Coding Conventions: Best PracticesCoding Conventions: Best Practices
15
Line Length• Avoid lines longer than 80 characters. They are not
handled well by many terminals and tools.
Variable Assignments• Avoid assigning several variables to the same value in a
single statement. It is hard to read. – Example:
fooBar.fChar = barFoo.lchar = 'c'; // AVOID!
Coding Conventions: Best PracticesCoding Conventions: Best Practices
16
DeclarationsOne declaration per line is recommended since it encourages
commenting.
Please Note: • int level; // indentation level • int size; // size of table is preferred over • int level, size; Do not put different types on the same line.
Example: • int foo, fooarray[]; //WRONG!
Coding Conventions: Best PracticesCoding Conventions: Best Practices
17
StatementsEach line should contain only one statement.
Example: argv++; // Correct argc--; // Correct argv++; argc--; // AVOID!
Coding Conventions: Best PracticesCoding Conventions: Best Practices
18
• Learn the traditional formats for naming variables, methods and other components of coding in Java.
• Notice the guidelines on indentation. • Remember that you will be working on projects in teams, and
following these conventions and standards will help to make your work much more “readable” for the other members of your team.
• Declare local variables immediately before use.• Avoid declaring or assigning values of more than one variable per line
of code.• Fields should be private, with setters and getters if needed.• Use System.exit with care.• Use an interface for constants.• Validate method arguments.• Use a testing framework.• Use zero-length arrays instead of null.• Choose the best collection framework.• Iterate without an index.
Key PointsKey Points
19
Helpful Websites:
http://www.javapractices.com/index.cjp
http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html
http://geosoft.no/development/javastyle.html
http://www.infospheres.caltech.edu/resources/code_standards/java_standard.html
http://www.ambysoft.com/javaCodingStandards.html
ResourcesResources