Java Best Practices
Java Best Practices
reclaimed.
instance
Overriding
return of toString():
a Byte objectUse
with StringBuilder
value 100. So ifrather
you
Avoid using ‘finalizers’ publicelements[--size]; //obselete
static Person newManager() portion
{
are calling for 10000 times, the first line would
} Finalizers
than concatenation operator ‘+’.
are not guaranteed to run in any
return new Person(Role.MANAGER);
Tips on overriding general methods create 10000 object, whereas the second would
public
predictable
Overriding timeframe.
compareTo(): Class should implement
} Object pop() {
create only one object.
Comparable
if }(size==0) Interface.
{throw new EmptyStackException();}
return result;
}
Try to create immutable object and Less
How tomethods
create immutable
classes //Constant
Inheritanceinterface pattern -object/class:
Approach: do not use!
Don’t
Avoid
public provide
long any list
params
interface method
Constants that modify the
in methods
public class Person {}{
Try to use composition rather than
Use @doc
object.
static final String USERNAME = Person
“Cybage”;
inheritance public class Employee extends {}
No methods
static final are overridden.
String PASSWORD
public class Customer extends= Person
“Cybage123”;
{}
Avoid using constants interfaces
} All the fields should be private and final.
Design method signatures carefully Prefer using ENUMs or separate Constants file.
Composition Approach:
}
Never call overridden methods public final in
Call super class Quark {
constructor
fMass = aMass;
processes
Avoid creating overloaded
constructors in serialization }
process
//private String fName;
//Avoid below
}
Implement serialization after a good /* @serialData Write email and name field as
transient private Thread animator;
judgment objects
Decrease flexibility
InvalidClassExceptions while deserialization
as String. */
public
Increase
Help likelytrack
to keep
void
hoodofof bugs and
different security holes
versions
writeExternal(ObjectOutput out)
Use transient keyword for
unnecessary variables that need not Reduce
Class such as Dates, overhead
performance BigInteger and most
be read from/written into streams. throws IOException {
collection classes and classes such as Thread
out.writeObject(email);
Think about data security should not be serialized.
out.writeInt(name);
Practice to control your serialized }
data using Externalization
/* Read in the data that we wrote out * in the
Don’t ignore serialVersionUID
writeExternal method & in same sequence */
IOException, ClassNotFoundException {
email = (String)in.readObject();
name = (String)in.readObject();
}
When to use which interface
List
Suppose lList
Preferred
Derive
Empty / =HashMap
aUsage:
list
size
ArrayList Set ifArrays.asList(sArray);
comprises
by
you
using
know of
in [a,b,c,d,e].
Collections.EMPTY_SET
advance
instead of Vector / HashTable
//iterator
Then After
method
Use List
plain loop
invoking
testLstCollections.rotate(list,
Arrays = new ArrayList(10); 1)
If possible than set the initial capacity
of collections appropriately
this
AvoidIterator<String>
listthis:
Empty
Use willList
comprise
Explicit iterator = lList.iterator();
of [e,a,b,c,d]
by using Collections.EMPTY_LIST
Synchronization
//while loop
}
Use synchronization when needed
Improves instead
In case ofperformance
BufferedReader
Flatin
File.seperator newofBufferedReader(new
‘/’ or ‘\’
= processing
file
Buffer your IO Streams Create
In caseyour own
of DB custom BufferredInputStream
FileReader(“test.txt"));
connection processing
try {
Prefer to use java.io.File utility
methods in = new BufferedInputStream(in);
in.read(..... )
} finally {
IOUtils.closeQuietly(in);
}
Use ThreadPoolExecutor for public
public class
class MyThread
ThreadPoolExecutor extends
tpe =
ThreadGroupDemo
synchronized
void run() { int getId() Thread
{{ {
managing multi-threading
private
new static
static
return ThreadLocal
ThreadPoolExecutor(
public id; void
boolean tl =[]new
main=(String
isDone false; ThreadLocal
args) { () {
publicreturn
Thread t1new
maxSize,
= new
synchronized Integer (sernum++);
//business
Thread
void (tg,logic…
setId( "thread
int _id ) {1");
Synchronize access to all the mutable
fields in a multi-threaded application } Thread
this.idkeepAlive,
t2_id;
=//if = new Thread
finished, to true….
(tg, "thread
set isDone 2");
tg.getName
this.name = () +" = true; thread group: " + agc);
_name;
fIsStopRequested
} } tg.list ();
}}
}
Create object pool for boosting the
The Use
public @NotNull
abstract
StringTokenizer
loop st and
class @Nullable
= ObjectPool
new { annotations“|");
StringTokenizer(str,
speed of your application
Use
Below
for (int Assertions
// manage
i code
= the
would
0; i < – be
limit; This
pooled is our
{object
more
i++) best friends
duration
faster pool
thaninabove
the
Assert.notNull(user,
//// manage
String subthe with"User
locked
= null;
do something cannot
and free
list... be null");
object in the pool
Avoid unnecessary method calls and
create methods that can alter objects } Assert.hasLength(user.getLastName(),
private
int i =0;Hashtable locked, unlocked; "User
without making copies
must
//int
Above have
create
jcode a lastobject
awould
new name");
=s.indexOf(delimiter);
be faster if // written
First substring
as below
Reduce object instances
abstract
while(list
ArrayList Object
j >= create();
0) { ArrayList();
= new
}}
Use StringBuffer instead of concat ‘+’ for(int ifor
Code1 = 0; i < test.length;
appending string i++) { concat operator:
using
operator values[1] = null; // gets null value
Stringlist.add(1);
str = new String (“Cybage ");
try {
Create less number of temporary object.set(list);
str += “Software";
objects in a loop i = 0;
list = new ArrayList();
[ByteCode Summary: Creates 3 objects]
while(true)
list.add(1); {
Prefer adding items to a collection in
one call // Concatenate and store in values[0]
object2.set(list);
Code2 for appending string using stringbuffer:
} values[0] = values[0].concat(values[i + 1])
Use exceptions only when you need
StringBuffer str = new StringBuffer(“Cybage ");
them i++;
Above implementation could be improved for better
str.append(“Software");
}
Never create static String using ‘new()’ performance as below:
operator [ByteCode Summary: Creates only 1 object]
} catch (ArrayIndexOutOfBoundsException e) {
list.add(1);
returnvariables
throw
your new blahException(“is
new null");
“java.io.FileInputStream.FileInputStream(String
FileOutputStream(fileName); s)
Use Encapsulation
} catch
}throws (FileNotFoundException
UseFileNotFoundException”
try-blocks e) {
to delimit your operations
Manage the scope of your
Granularity
throw new ActionException(e);
of your exception handling
try-catch block
} Size of your code
Add validations in Exceptions
Number of exceptions thrown
byte[] header;
res.getOutputStream();
public
AJAX void init() side
on client {
ByteArrayOutputStream(12000);
Use
Use print() method instead of println()
public void init(ServletConfig
out.write(header);
scenario, config)
System.out.println(“INIT()”);
In multithreading { use
prefer to
Use ServletOutputStream instead of }//create
out.flush(); all the static data hererequest
same thread//
PrintWriter outflush the
= new header
PrintWriter(byteArray);
simultaneously for same
PrintWriter
and StringBuffer
out.write(navbar);
public sb = new StringBuffer();
void doGet(HttpServletRequest
response
If you use PrintWriter than initialize it
sb.append("<html>”);
out.flush();
request,HttpServletResponse
// flush the navigation
response)
bar {
with proper size
sb.append("<head><title>Hello
// write dynamic
out.println(“doGET()”);
data here
Flush data partly rather than at once
}world</title></head>”);
out.flush(); // flush the dynamic data
If you are using JDBC connection pools sb.append(“<body>”);
out.write(footer);
public void destroy() {
than write connection closing code in
destroy() method header
out.flush(); //= finally
sb.toString().getBytes();
System.out.println(“DESTROY”);
flush the footer
} jdbcConn.close();
Tips for using Asynchronous Servlet
public
} void service() {…}
} }
For caching, use Servlet API’s inbuilt Type Performance Description
options like HttpSession or synchronized(this){
HttpSession.setAttribute(String
Remove session explicitly name, Object
HTTPSession Good No Size Limit
ServletContext
codetime
Set session line1;
cacheableObject); out value
for(int
JSP
i=0;// code
Include:
understand
logic
Improves of header ori++)
i<messages.length;
productivity footer
{
Never mix business logic with
presentation logic </cache:cache>
String message
<jsp:include
Reusable
Keep = messages[i];
the page=“x.jsp"
code secure flush="true" />
%>
JSTL Include: Tips
Implementation
Prefer to use custom tags
<LI><%=
Keepmessage
<c:import simple%></LI>
iturl="./header.html"/>
Use JSTL in place of Java code
<%
} %>
Make it usable
Use JSP Data Caching
<LI>${message} </LI>
</c:forEach>
Preferred way of implementing database
<jsp:useBean
<jsp:useBean
<%@page
<%@ id="objectName"
id=“connection“
pageerrorPage="error.jsp"
session=”false” %> %>
connection pooling from JSP
scope="page|request|session|application"
class="oracle.jdbc.pool.
<html> />
Utilize JSP exception mechanism
OracleConnectionCacheImpl"
<body>
cods.setStmtCache (5);
Page.</title></head>
</body>
</html>
Pagination with JSP Refer Notes Section for the implementation
Prepared By: Dramil M Dodeja
SOAP based webservices SOAP REST
Complex to Simple to implement
REST based webservices
implement
describing
operation
divide
Top aDown
defined messages
would
large
in be individual
Approach
SOAPoperation
message andrather
definition
body user than
into would
Prefer to use WSDL rather than Java
to define your service interfaces
beWSDL
ablemessage
Meet tocan
in
individual
SOAD proceed
the be easily
with
Middle
chunks used
next for
Approach
headers operation
SOA
implementations
concurrently
Service Interfaces should be more
granular WSDL can be easily used to generate
ents/Process%20Manual/SDLC/Design%20Pro
cess/S_DEP_SEHG.doc