Java Programming Best Practices
Education & Research
“© 2008 Infosys Technologies Ltd. This document contains valuable confidential and proprietary information of Infosys. Such confidential and
proprietary information includes, amongst others, proprietary intellectual property which can be legally protected and commercialized. Such
information is furnished herein for training purposes only. Except with the express prior written permission of Infosys, this document and the
information contained herein may not be published, disclosed, or used for any other purpose.”
Confidential © 2008, Infosys
ER/CORP/CRS/<CourseCode>/003
Technologies Ltd.
Confidential Information
• This Document is confidential to Infosys Technologies Limited. This document contains information and data
that Infosys considers confidential and proprietary (“Confidential Information”).
• Confidential Information includes, but is not limited to, the following:
– Corporate and Infrastructure information about Infosys;
– Infosys’ project management and quality processes;
– Project experiences provided included as illustrative case studies.
– < Please list any/all other that is relevant>
• Any disclosure of Confidential Information to, or use of it by a third party, will be damaging to Infosys.
• Ownership of all Infosys Confidential Information, no matter in what media it resides, remains with Infosys.
• Confidential information in this document shall not be disclosed, duplicated or used – in whole or in part – for
any purpose other than _(Please insert as applicable)__ without specific written permission of an authorized
representative of Infosys.
• <Please include this point if applicable> This document also contains third party confidential and proprietary
information. Such third party information has been© Infosys
includedTechnologies Ltd.
by Infosys after receiving due written permissions
and authorizations from the party/ies. Such third party confidential and proprietary information shall not be
disclosed, duplicated or used – in whole or in part – for any purpose other than _(Please insert as
applicable)__ without specific written permission of an authorized representative of Infosys.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 2
anytime, anywhere!
Course Objectives
• To introduce the correct usage of some of the basic tenets
of the Java programming language.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 3
anytime, anywhere!
Session Plan
• Day 1
– Introduction
– Best Practices for Object Creation
– Best Practices for Classes, Interfaces and Methods
– Best Practices for Common programming tasks
– Best Practices for Generics and enums
– Best Practices for Exception handling
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential
anytime, anywhere!
Introduction
• Java Best Practices talks about how to do a “certain
thing” in Java “well”.
• “Certain thing” as defined above means the things that
we usually do with a language like create objects, design
methods, use exceptions or use any other language
features or library.
• “Well” means doing things in such a fashion so that the
code is readable, flexible and maintainable or perhaps
© Infosys Technologies Ltd.
even performs better in certain conditions.
• These practices have formed over two decades of Java
being around in the developer community.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 5
anytime, anywhere!
Best Practices for Object Creation
“© 2008 Infosys Technologies Ltd. This document contains valuable confidential and proprietary information of Infosys. Such confidential and
proprietary information includes, amongst others, proprietary intellectual property which can be legally protected and commercialized. Such
information is furnished herein for training purposes only. Except with the express prior written permission of Infosys, this document and the
information contained herein may not be published, disclosed, or used for any other purpose.”
Confidential © 2008, Infosys
ER/CORP/CRS/<CourseCode>/003
Technologies Ltd.
Object Creation Best Practices
• Creating objects in Java is an expensive operation, with
impact on both performance and memory consumption.
• The cost varies depending on the amount of initialization
that needs to be performed when the object is to be
created.
• So the first best practice is ©toInfosys
“lazy initialize”.
Technologies Ltd.
• This means don’t create objects until you need them.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 7
anytime, anywhere!
Lazy initialization
• Instead of initializing the names list at the time of
declaration, we deferred it to the point of first use.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 8
anytime, anywhere!
Avoid creating unnecessary objects
• The first rule here is to avoid using Wrapper objects if
you can use primitives.
• The method below unnecessarily creates 100000000
Integer objects!
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 9
anytime, anywhere!
Avoid creating unnecessary objects
• Strings are immutable objects. Never create String
objects as shown in the snippet below.
• A more reusable approach is this: Whenever you use this
approach JVM reuses the existing String object with the
same name. © Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 10
anytime, anywhere!
Avoid creating unnecessary objects
• You can avoid creating unnecessary objects for
immutable classes by invoking the static factory
methods.
• The constructor creates a new object each time it is
called, while a static factory is not required to do so and
won’t in practice.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 11
anytime, anywhere!
Remove obsolete references
• In a garbage-collected language like Java, one does not
normally have to worry about memory leaks.
• What is a memory leak in Java? An unused object but
still referenced.
• Defining a reference in the narrowest possible scope
takes care of memory leak.
• But whenever a class manages its own memory like
when you create a Cache or a Stack or a Queue it
© Infosys Technologies Ltd.
should be wary of memory leaks, which happen through
obsolete references not made null.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 12
anytime, anywhere!
Remove obsolete references
• Common problems to watch out for:
– Collection classes, such as HashMaps and ArrayLists,
are common places to find the cause of a memory
leak.
– When you register a class as an event listener without
bothering to unregister when the class is no longer
needed.
– Member variables of a class that point to other
© Infosys Technologies Ltd.
classes simply need to be set to null at the
appropriate time.
• Memory leaks in Java can be observed through careful
code inspection or a debugging tool called heap profiler.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 13
anytime, anywhere!
Classes & Interfaces Best Practices
“© 2008 Infosys Technologies Ltd. This document contains valuable confidential and proprietary information of Infosys. Such confidential and
proprietary information includes, amongst others, proprietary intellectual property which can be legally protected and commercialized. Such
information is furnished herein for training purposes only. Except with the express prior written permission of Infosys, this document and the
information contained herein may not be published, disclosed, or used for any other purpose.”
Confidential © 2008, Infosys
ER/CORP/CRS/<CourseCode>/003
Technologies Ltd.
Class design
• First design principle, use the lowest possible access
level consistent with the proper functioning of the
software.
• This design principle guarantees decoupling of the
classes.
• If a top-level package class is used by only one class
consider making it a nested class.
• All other members except the public API, should be
© Infosys Technologies Ltd.
made private unless another class in the same package
needs access to it directly.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 15
anytime, anywhere!
Class design
• A protected member becomes part of exported API that
needs to be supported forever.
• Never make instance fields public.
• With the exception of public static final fields, public
classes should have no public fields.
• Ensure that objects returned by public static final are
immutable.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 16
anytime, anywhere!
Class design
• Alternate approaches:
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 17
anytime, anywhere!
Minimize mutability
• An immutable class is a class that cannot be modified.
Implying that the state information provided at the time of
creation of the object is fixed for its lifetime.
• Some examples of immutable classes in Java library,
String Wrapper classes and BigInteger and BigDecimal.
• Advantages of Immutable classes:
– Immutable objects are simple.
– Immutable classes are thread safe, they require no
© Infosys Technologies Ltd.
synchronization.
– Immutable objects make great building blocks for
other objects example, they make great map keys and
set elements.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 18
anytime, anywhere!
Minimize mutability
• Disadvantage:
– Creating immutable objects is expensive esp. if they
are large, example like the BigInteger.
• How make a class immutable?
– Don’t provide any setter methods. Also, known as
mutators.
– Ensure that the class cannot be extended.
– Make all fields final. © Infosys Technologies Ltd.
– Make all fields private.
– Ensure exclusive access to any mutable components.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 19
anytime, anywhere!
Minimize mutability
• An alternative to prevent subclassing by marking the
class final is to
– Make all constructors private.
– And add public static factories to create objects.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 20
anytime, anywhere!
Minimize mutability
• Summary:
• Make a class mutable only if there is a good
business/design reason to do so.
• Always make small value classes immutable.
• If classes cannot be made immutable then restrict
mutability as much as possible.
• Try to make every field final, make it non-final only if
there is a good reason to do so.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 21
anytime, anywhere!
Favor composition to inheritance
• Inheritance is a powerful way to achieve code re-use but
it breaks encapsulation and therefore should be used
only when there is a IS-A relationship between classes.
• It is safe to use inheritance within the same package,
where the subclass and super-class are under the
control of the same programmers.
• It is also safe when inheritance is used for classes
especially designed and documented for subclassing.
© Infosys Technologies Ltd.
• Inheriting from ordinary concrete classes across
packages is dangerous and can make the code fragile.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 22
anytime, anywhere!
Prefer interfaces to abstract classes
• Advantages of interfaces:
– Since Java limits the inheritance to one class, abstract
classes cannot be used freely as type definitions.
– Existing classes can be easily made to implement a
new interface. It is difficult to change a hierarchy.
– Interfaces are ideal for defining mixins.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 23
anytime, anywhere!
Prefer interfaces to abstract classes
• Advantages of interfaces:
– Interfaces allow construction of non hierarchial type
frameworks.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 24
anytime, anywhere!
Prefer interfaces to abstract classes
• Advantages of interfaces:
– Interfaces contain only abstract methods but it is easy
to provide implementation assistance to programmers.
– It is possible to provide an abstract skeletal
implementation class to go with each non-trivial
interface that is exported.
– By convention these are called AbstractInterface,
where Interface is the name of the class they
© Infosys Technologies Ltd.
implement.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 25
anytime, anywhere!
Prefer interfaces to abstract classes
• One major advantage of an Abstract class over an
interface is its ease of evolution.
• For example, it is easy to add a new method to a
concrete class (providing a default implementation), all
existing implementations can access this new method.
• In contrast, it is not possible to add a new method to an
interface without breaking the existing code.
• So you must get the Interface right the very first time!
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 27
anytime, anywhere!
Interface anti-patterns
• Use interface to define only types, don’t use it to define
constants.
• Java library has several constant interfaces, example
java.io.ObjectStreamConstants. This should not be
emulated.
• Options for exporting constants:
– Make the fields public static final
– Define a noninstantiable© utility class with public static
Infosys Technologies Ltd.
final fields.
– If the constants are best viewed as an enumerated
type export them with an enum type.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 28
anytime, anywhere!
Common Programming Best Practices
“© 2008 Infosys Technologies Ltd. This document contains valuable confidential and proprietary information of Infosys. Such confidential and
proprietary information includes, amongst others, proprietary intellectual property which can be legally protected and commercialized. Such
information is furnished herein for training purposes only. Except with the express prior written permission of Infosys, this document and the
information contained herein may not be published, disclosed, or used for any other purpose.”
Confidential © 2008, Infosys
ER/CORP/CRS/<CourseCode>/003
Technologies Ltd.
Limit the scope of local variables
• “Limiting the scope of local variables” comes from the
more general rule of minimizing the accessibility of
classes and methods.
• What are the benefits of limiting the scope of local
variables?
– Your code is more readable.
– Less error prone due to oversight.
– It also improves the maintainability of the program
© Infosys Technologies Ltd.
• What are the ways to limit the scope of local variables?
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 30
anytime, anywhere!
Limit the scope of local variables
• Declare the variable only and only before its first usage.
– Makes the code readable and maintainable since the
maintenance software engineer is likely to know what
a particular variable is used for.
– Does not unnecessarily increase the scope of a
variable beyond the point where it is required, this
minimizes oversight and typical copy paste errors like
in the next slide.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 31
anytime, anywhere!
Limit the scope of local variables
• What is happening here?
© Infosys Technologies Ltd.
• Such errors can cause undefined behavior, which can
easily be avoided if the variables had been introduced in
the loop itself.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 32
anytime, anywhere!
Limit the scope of local variables
• Always remember to initialize the local variable upon its
declaration.
• If its not possible like in situations where the initialization
needs to be in a try-catch clause, then the reference
must be declared null (for a reference or the relevant
default for a primitive) before the try-catch block.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 33
anytime, anywhere!
Switch over to for-each loops
• The for-each syntax for iterating over a collection/array
was introduced since Java 1.5 and is a cleaner choice
over the traditional for loop structure.
• Because of its cleaner structure, this one is clean and
less error prone and therefore preferable.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 34
anytime, anywhere!
Use standard libraries
• It is always better to use a standard library class than
writing one yourself. This has been tested, debugged
and used by many others.
• Also, it will inevitably be more efficient than what a
programmer can do from scratch in a limited time frame.
• Using standard library again makes the code more
readable and maintainable and reusable by other
developers.
© Infosys Technologies Ltd.
• Keep yourself abreast of the additions in the language
after a major release.
• All developers must be at least familiar with java.lang,
Java.io and java.util packages.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 35
anytime, anywhere!
Doing exact calculations
• For doing exact calculations with decimal, choosing float
or double may seem to be the right choice. But it is not.
• Using float and double for precise decimal based
arithmetic is inaccurate because float and double were
designed for accurate approximations over a broad
range of magnitudes.
• Most precisely, never use float and double for monetary
calculations.
© Infosys Technologies Ltd.
• So what should you use?
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 36
anytime, anywhere!
Doing exact calculations
• Use int or long if you can manage the overhead of taking
care of the decimal yourself.
• Use BigDecimal if you want automatic accurate tracking
of the decimal and you don’t mind the little performance
price that comes because of using a class instead of a
primitive.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 37
anytime, anywhere!
Primitive types versus Wrappers
• Primitive types are int, long, float, double etc. Wrappers
are the classes that represent them as Objects.
• Since Wrappers are classes they are less efficient than a
primitive that stores only a value unlike the former which
is a complete class.
• So where ever possible, one should use the primitives
since they are much efficient than a corresponding
Wrapper.
© Infosys Technologies Ltd.
• Since Java 1.5, auto-boxing and un-boxing has been
introduced, it reduces the manual effort in converting
from a primitive to a wrapper and vice-versa
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 38
anytime, anywhere!
Primitive types versus Wrappers
• But this feature is also prone to errors, lets have a look:
• Comparing Wrappers using© Infosys
== isTechnologies
WRONG. Ltd.
Since it
compares the reference value and not the value
represented by the wrapper.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 39
anytime, anywhere!
Primitive types versus Wrappers
• What is the output of the following program?
© Infosys Technologies Ltd.
• Due to automatic unboxing, one can inadvertently
observe some unexpected Null pointer exceptions!
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 40
anytime, anywhere!
Primitive types versus Wrappers
• So as a rule always prefer primitives to wrappers unless
there is a compelling reason to do so. For example, the
collections library does not accept primitive types.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 41
anytime, anywhere!
Using String effectively
• String concatenation using the + operator.
• It is a convenience operation for small, fixed strings or
perhaps for generating a single line output.
• But it is very inefficient for concatenating large no of
strings since Strings are immutable. Every time + is
invoked a new String object gets created.
• String concatenation using + is both time and memory
intensive. Use with care.
© Infosys Technologies Ltd.
• For generating mutable Strings use the StringBuilder
class (as of Java 1.5), note that StringBuffer is obsolete.
• Note that concat method of String works the same as +!
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 42
anytime, anywhere!
Using String effectively
• Guess the time difference between the first code snipped
and the second one?
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 43
anytime, anywhere!
Don’t use Strings here
• As substitutes for aggregate types:
© Infosys Technologies Ltd.
• Parsing a String is slow and error prone.
• If an entity has multiple components it is best
represented as a class.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 44
anytime, anywhere!
Don’t use Strings here
• Always use the enum construct for enumerated types
instead of Strings.
• Strings should only be used for textual data.
• Don’t use Strings for values which are best represented
as another value type (primitives or another reference
types). For example, using Strings for numbers, boolean.
• If no appropriate types exists for a non-textual
information you have, create a class for it.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 45
anytime, anywhere!
Programming to an interface
• As far as possible, hide the implementation class details
in your code. This makes the code for flexible and
adaptable to change.
• Let us say you want to create an ArrayList, how would
you create it?
• Use an implementation class only when an appropriate
interface does not exist.
© Infosys Technologies Ltd.
• Also, when you work with classes that extend the parent
interface and add more methods (which you intend to
use) in that case, you have to work with the
implementation classes.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 46
anytime, anywhere!
Reflection Don’ts
• Don’t use reflection for accessing objects in a normal
application at runtime. See Notes.
• Reflection allows skipping the entire compile time
checking framework including exceptions.
• The reflection code is awkward and verbose.
• Reflective method invocation is much slower than normal
method invocation. Performance can slower from a factor
of 2 to 50!
© Infosys Technologies Ltd.
• However, when the class of implementation is not known
at compile time, reflection can be used in a limited form
to get its benefits.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 47
anytime, anywhere!
Using JNI cautiously
• Java Native Interface (JNI) allows Java applications to
call native code written in C and C++.
• Native method can perform some task before returning to
Java programming context.
• JNI use has serious disadvantages –
– Java code accessing native code through JNI is
susceptible to memory corruption with no stack trace.
– Java code accessing native code is also relatively
© Infosys Technologies Ltd.
non-portable.
– Native methods can reduce performance.
– JNI requires “glue code” which is clumsy, difficult to
read and difficult to write.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 48
anytime, anywhere!
Using JNI cautiously
• So why use JNI?
• There are following “genuine” reasons for using JNI:
– To access platform specific facilities.
– To access legacy code.
– It is rarely advisable to use JNI for getting increased
performance.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 49
anytime, anywhere!
Optimizing Do’s and Don’ts
• Two rules of optimization:
– Don’t do it.
– Don’t do it yet – that is not until a clear and
unoptimized solution is in sight.
• Don’t sacrifice sound design principles for performance.
– If a good program is slow its good architecture can
allow tuning but architectural flaws that limit
performance are impossible to fix without rewriting.
© Infosys Technologies Ltd.
• However, performance has to be thought about during
the design process and not as an after thought and not
even as a driving force.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 50
anytime, anywhere!
Optimizing Do’s and Don’ts
• Try to avoid design choices that are typical performance
bottlenecks
– These are typically components that specify
interaction between modules and with the outside
world. Example API’s, wire-level protocols, persistent
data formats.
– While designing API, consider performance
consequences example, using Inheritance instead of
© Infosys Technologies Ltd.
composition, using implementation instead of an
interface.
• Consider profiling. This gives important runtime
information, which can help in deciding what to optimize.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 51
anytime, anywhere!
Optimizing Summary
• Let your goal be a good program not a fast one, speed
will come with good programs.
• Think about performance issues during design esp.
designing API’s, wire-level protocols and data formats.
• When your program is done measure performance.
• If its not fast enough, use a profiler and find the
performance weak link and go ahead and optimize that.
• While optimization start with top-level optimizations and
© Infosys Technologies Ltd.
then low level since the latter has low performance
yields.
• Repeat the process until you are happy!
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 52
anytime, anywhere!
Follow naming conventions
• Java Language specifications lists the naming
conventions, which are of two types: typographical and
grammatical (controversial)
• Why naming conventions
– An API that violates naming conventions could be
difficult to use.
– A program that violates naming convention is difficult
to maintain.
© Infosys Technologies Ltd.
– To sum up, naming convention violations can confuse,
annoy and may also cause errors in your program.
Don’t do it!
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 53
anytime, anywhere!
Follow naming conventions
• Summary typographical naming conventions:
Identifier Type Examples
Package com.infosys.enr
Class or Interface Date, List, Collection
Method or Field get, list, noOfItems
Constant Field MAX_VALUE
Local variable j, ref, value
Type Parameter E, X, T, ©V,Infosys
T1, T2Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 54
anytime, anywhere!
Methods Best Practices
“© 2008 Infosys Technologies Ltd. This document contains valuable confidential and proprietary information of Infosys. Such confidential and
proprietary information includes, amongst others, proprietary intellectual property which can be legally protected and commercialized. Such
information is furnished herein for training purposes only. Except with the express prior written permission of Infosys, this document and the
information contained herein may not be published, disclosed, or used for any other purpose.”
Confidential © 2008, Infosys
ER/CORP/CRS/<CourseCode>/003
Technologies Ltd.
Best Practices - Methods
• The general programming best practice is – find errors in
the application as early as you can after is has occurred.
• Doing this ensures early diagnosis of the problem and
consequently more chance of failing cleanly with the right
exception.
• Keeping this principle in mind the method parameters
should be checked before being used.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential
anytime, anywhere!
Checking input parameters
• For non-public methods, the parameters should be
checked using assertions to ensure that only valid
parameters are passed.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential
anytime, anywhere!
Checking input parameters
• For public methods –
• The parameters should be checked before use and if
invalid an appropriate exception should be thrown.
• The checked exceptions thrown should be documented.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential
anytime, anywhere!
Checking input parameters
• Constructor parameters should be especially validated to
prevent construction of an invalid object.
• However, there could be exceptions to this general rule
of parameter checking when the method computation
implicitly validates the parameters.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential
anytime, anywhere!
Method/constructor design
• Determine what restrictions should be placed on the
input parameters.
• Check for the restrictions before using the parameters
and throw appropriate exceptions in case of violations.
• Once more, document the exceptions being thrown.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential
anytime, anywhere!
Making defensive copies
• When you want to protect the invariant parts of your
class, it is important that you make defensive copies of
each mutable parameter to the constructor and mutable
methods.
• Defensive copies are made before parameter validity
check and the check is performed on the copy instead of
the original. See the code below.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 61
anytime, anywhere!
Making defensive copies
• What happens now?
• This is how it can be prevented:
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 62
anytime, anywhere!
Making defensive copies
• Clone method of Object class should not be used to
make a defensive copy.
• But the previous class is still modifiable!
• Getter methods should return the copy of the fields.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 63
anytime, anywhere!
Returning empty Collections and Arrays
• If a method returns an Array or a Collection, don’t return
null for an empty array or a collection.
• Doing this requires the client code to do an extra check
for null.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 64
anytime, anywhere!
Returning empty Collections and Arrays
• Correct way of returning an array from a Collection.
• Correct way of returning a copy of a Collection.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 65
anytime, anywhere!
Generics and Enums
Best Practices
“© 2008 Infosys Technologies Ltd. This document contains valuable confidential and proprietary information of Infosys. Such confidential and
proprietary information includes, amongst others, proprietary intellectual property which can be legally protected and commercialized. Such
information is furnished herein for training purposes only. Except with the express prior written permission of Infosys, this document and the
information contained herein may not be published, disclosed, or used for any other purpose.”
Confidential © 2008, Infosys
ER/CORP/CRS/<CourseCode>/003
Technologies Ltd.
Best Practices - Generics
• Don’t mix and match raw types with Generic types.
– Although the compiler allows it to pass, this defeats
the purpose of Generic classes.
• Remove unchecked warnings during compilation of
Generics code.
• Only when all unchecked warnings are removed can the
code be called really typesafe.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential
anytime, anywhere!
Best Practices - Generics
• If you are 100% sure that your code is typesafe and you
still get an unchecked warning during compilation, then
you can use @SupressWarnings annotation to stop the
compiler from generating the warning.
• @SupressWarnings can be used ranging from a local
variable declaration to an entire class.
• Use this annotation on as small a scope as possible.
Avoid using it on an entire class.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential
anytime, anywhere!
Best Practices - Generics
• Arrays are covariant while Lists are not. So prefer using
Lists to arrays, this can ensure that your code is type
safe and any type error is not deferred to runtime.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential
anytime, anywhere!
Best Practices - Generics
• Arrays ensure type safety at runtime since the type
information is carried into the byte code so an improper
type in an array throws an ArrayStoreException at
runtime.
• In case of Generics, the type information is available only
at compile time (for compatibility with legacy code) and
not at the byte code level.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential
anytime, anywhere!
Best Practices - Generics
• Therefore, it is illegal to create Generic arrays because it
is not type safe.
• For example, consider what happens if Generic arrays
were legal?
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential
anytime, anywhere!
Using enums
• The first rule here is to use enums instead of int
constants where ever applicable.
• Enums are used to represent fixed set of constants like
Bands in Infosys, Product type, seasons of a year.
• The older technique as represented here has some
serious disadvantages:
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 72
anytime, anywhere!
Using enums
• Firstly, there is no type safety.
• Secondly, it can do pretty little by way of offering any
ease of use.
• For example, if a method expects WINTER, and you
pass SUMMER, the compiler cannot flag.
• A code that compares SUMMER to WINTER using ==
also will work.
• Even (SUMMER-WINTER)©works! Infosys Technologies Ltd.
• Also, consider that Java does not provide namespace
protection for int constants.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 73
anytime, anywhere!
Using enums
• Again, if the library changes the int definition of a int
enum constant, the client code using them needs to be
recompiled to work correctly.
• Also, there is no simple way of producing a printable
version of an int enum pattern.
• There is an alternate and more problematic version
called the String enum pattern.
• In addition to the disadvantages of int enum pattern, it
© Infosys Technologies Ltd.
can possibly lead to poor performance due to String
comparison.
• Or possibly some novice programmers hard coding the
String constants in their code instead of using field
names.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 74
anytime, anywhere!
Using enums
• As of java 1.5, Java provides a construct called enum,
which is the best choice for fixed constants along with
the functionality of a full fledged class.
• Here is how the simplest version of enum looks:
• Internally, enums are classes that
© Infosys exportLtd.one instance for
Technologies
each enumeration constant via a public static final field.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 75
anytime, anywhere!
Using enums
• Enum types are instance controlled i.e. you cannot
create instances except that of enumerated constants.
• Enums provide compile time safety.
• Enum constants provide their own namespace.
• It is possible to reorder or add new constants to the
enum definiton without affecting the clients.
• Printable versions of enums can be obtained by invoking
toString method. Default is©the name of the constant
Infosys Technologies Ltd.
itself.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 76
anytime, anywhere!
Using enums
• By default, enums override all the Object methods and
also implement Serializable and Comparable interfaces.
• Since enum is a class, it can have arbitrary fields and
arbitrary methods, constructors and can implement
arbitrary interfaces.
• It is beneficial to add fields, methods to enums when we
want to associate data with the constants.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 77
anytime, anywhere!
Using enums
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 78
anytime, anywhere!
Exception handling Best Practices
“© 2008 Infosys Technologies Ltd. This document contains valuable confidential and proprietary information of Infosys. Such confidential and
proprietary information includes, amongst others, proprietary intellectual property which can be legally protected and commercialized. Such
information is furnished herein for training purposes only. Except with the express prior written permission of Infosys, this document and the
information contained herein may not be published, disclosed, or used for any other purpose.”
Confidential © 2008, Infosys
ER/CORP/CRS/<CourseCode>/003
Technologies Ltd.
Designing Exception handling
• Exception handling is an in-built feature in Java to handle
errors.
• If used correctly it makes the code more robust, easier to
maintain and read.
• If used incorrectly, fixing bugs and maintaining code can
become a nightmare. © Infosys Technologies Ltd.
• In Java, there are three types of throwable classes:
Checked exceptions, Unchecked Exceptions and Errors.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 80
anytime, anywhere!
Using Exceptions
• Never allow exceptions to bubble out from the finally
clause.
• The finally clause should normally have code that does
not throw exception.
• But if the finally clause does throw an exception, log it or
handle it, never allow it to bubble out.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 81
anytime, anywhere!
Using Exceptions
• As a good practice group the log messages together,
regardless of the level.
• This is more efficient besides ensuring that the logs will
appear together even in a multi user, multi threaded
environment.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 82
anytime, anywhere!
Exception chaining
• An application often responds to an exception by
throwing another exception. In effect, the first exception
causes the second exception.
• It can be very helpful to know when one exception
causes another. Chained Exceptions help the
programmer do this.
• The following are the methods and constructors in
Throwable that support chained exceptions.
© Infosys Technologies Ltd.
– Throwable getCause()
– Throwable initCause(Throwable)
– Throwable(String, Throwable)
– Throwable(Throwable)
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 83
anytime, anywhere!
Exception chaining
• Exception chaining allows to attach the underlying cause
of a problem to the thrown exception.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 84
anytime, anywhere!
Designing Exception handling
• Rule of thumb for designing API that throws exception:
– If the API user can take some meaningful action from
the information available in the Exception object,
declare the exception as Checked.
– If the API user cannot do anything meaningful after
this exception is thrown, declare it as an Unchecked
exception.
• Rule of thumb for dealing with exceptions across
© Infosys Technologies Ltd.
application layers:
– Implementation specific lower level exceptions should
never propagate to higher levels.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 85
anytime, anywhere!
Designing Exception handling
– For example, a low level Data Access exception
should not propagate to higher level like a Business
layer because it makes no contextual sense there.
• There are two options to deal with this situation
– If the Business layer can do a recovery from the low
level exception being thrown in Data Access layer
(very unlikely) then wrap the low level exception into
another more meaningful business level checked
© Infosys Technologies Ltd.
exception.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 86
anytime, anywhere!
Designing Exception handling
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 87
anytime, anywhere!
Designing Exception handling
– Another option is to wrap the low level exception from
another layer in an unchecked RuntimeException
when you are sure that a client can do nothing to
recover from it (most likely scenario).
– This approach saves the client the burden of handling
something it can do nothing about anyway.
© Infosys Technologies Ltd.
– See next slide for example.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 88
anytime, anywhere!
Designing Exception handling
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 89
anytime, anywhere!
Designing Exception handling
• Don’t do this in your business layer. It merely suppresses
the exception. Instead, follow any of the two approaches
discussed before.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 90
anytime, anywhere!
Designing Exception handling
• Never create unnecessary custom exceptions.
– If your new exceptions don’t have useful information
for Client code, don’t create them! Like the one below:
– If you are not adding any extra information just use
the standard exceptions©already defined
Infosys Technologies Ltd. in the Java
library, makes the code more readable.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 91
anytime, anywhere!
Designing Exception handling
• Create new exceptions when you provide extra
information to the client through additional methods in
your exception class. See the code below:
• If the client can do nothing ©meaningful
Infosys Technologiesabout
Ltd. the
exception, you should throw it as an unchecked
exception.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 92
anytime, anywhere!
Designing Exception handling
• The API’s you write must declare the checked and
unchecked exceptions it throws.
– Note: Document those unchecked exceptions that the
caller might reasonably want to catch.
– It allows the caller to convert an implementation-
dependent unchecked exception to some other
exception that is more appropriate to the caller's
exported abstraction.
© Infosys Technologies Ltd.
• For documenting exceptions @throws Javadoc tag can
be used.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 93
anytime, anywhere!
Using Exceptions
• There are certain Best Practices to be followed when we
use the API’s that throw exceptions.
• try-finally clause should be used to clean up resources
like files, database connections or network sockets.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 94
anytime, anywhere!
Using Exceptions
• Exception traces are exceptionally valuable tools for
debugging but make sure that they are logged only once.
• Logging the same exception at multiple places, confuses
the developer who is trying to analyze the log file.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 95
anytime, anywhere!
Using Exceptions
• Never suppress or ignore exceptions. Don’t do
something like this:
.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 96
anytime, anywhere!
Using Exceptions
• If you do not want to do anything about a checked
exception, convert it to an unchecked exception and
throw it again
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 97
anytime, anywhere!
Using Exceptions
• Do not use exceptions for flow control.
• Stack trace is very important in debugging and expensive
to generate. Using exceptions for flow control means that
stack trace is ignored and hence lost.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 98
anytime, anywhere!
Using Exceptions
• Never catch top level exceptions. By doing so we lose
the important contextual information about the error that
has happened.
• Catching the super class Exception, means that you are
catching even the unchecked exceptions
(RuntimeException extends from Exception). This makes
debugging very hard.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 99
anytime, anywhere!
Using Exceptions
• If you encounter an exception, either Log or Throw but
never both!
• Logging and throwing in multiple log messages confuses
the maintenance developer and makes debugging very
difficult.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 100
anytime, anywhere!
Using Exceptions
• Never throw Exception.
• It defeats the purpose of using checked Exceptions.
There is no useful information you are conveying to the
caller of your method!
• Declare the specific exceptions that your method can
throw.
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 101
anytime, anywhere!
Using Exceptions
• Bad wrapping. The code below destroys the stack trace
and with it any means of getting at the source of trouble.
• Always remember to throw the exception along:
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 102
anytime, anywhere!
Using Exceptions
• Don’t return null from catch clause. Null should be
returned in a normal course of execution and not as a
response to an exception. (example return null if the
username was not found)
© Infosys Technologies Ltd.
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 103
anytime, anywhere!
References
• Effective Java Second Edition by Joshua Bloch
• http://blogs.sun.com/CoreJavaTechTips/
• https://confluence.ucdavis.edu/confluence/display/UCDS
AKAI/Java+Coding+Best+Practices
• http://www.agaveblue.org/musings/exceptionhandling.sht
ml
• http://www.javapractices.com/home/HomeAction.do
• http://www.javaworld.com/javaworld/jw-02-2001/jw-0223-
© Infosys Technologies Ltd.
performance.html
We enable you to leverage knowledge
© 2008, Infosys Technologies Ltd. Confidential 104
anytime, anywhere!
Thank You
Confidential © 2008, Infosys
ER/CORP/CRS/<CourseCode>/003
Technologies Ltd.