Coding Conventions: Best Practices

Report
07 Coding Conventions
Objectives
•
•
•
•
•
•
•
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
2
Coding 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.
3
Coding 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.
4
Coding Conventions: Best Practices
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.
5
Coding Conventions: Best Practices
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.
6
Coding Conventions: Best Practices
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.
7
Coding Conventions: Best Practices
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.
8
Coding Conventions: Best Practices
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.
9
Coding Conventions: Best Practices
Checked vs. Unchecked Exceptions
Checked 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).
10
Coding Conventions: Best Practices
Checked vs. Unchecked Exceptions
Unchecked 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.
11
Coding Conventions: Best Practices
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.
12
Coding Conventions: Best Practices
Iterate without an index

Some programmers have a strong preference for using
a for-each loop or an Iterator instead of indexed forloops. Indexes have always been a major source of error,
and should generally be avoided if there is an alternative.
13
Coding Conventions: Best Practices
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.
14
Coding Conventions: Best Practices
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!
15
Coding Conventions: Best Practices
Declarations
One 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!
16
Coding Conventions: Best Practices
Statements
Each line should contain only one statement.
Example:
 argv++; // Correct
 argc--; // Correct
 argv++; argc--; // AVOID!
17
Key Points
•
•
•
•
•
•
•
•
•
•
•
•
•
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.
18
Resources
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_sta
ndards/java_standard.html
http://www.ambysoft.com/javaCodingStandards.html
19

similar documents