You are on page 1of 36

Prepared By: Ashvin Gondalia

This document is for developers, integration specialists and any other


role that will need to code in Java J2ee

To provide specific conventions and recommendations for application


developers

To guide application developers and designers to develop the systems


that are maintainable, testable, readable and adaptable

In a nutshell, our motive is to improve developer’s java j2ee


programming and designing skills
 Use of static factory methods instead 
 public
Finalizeable
Overriding objects
equals(): are bothshould
result slowerbe to symmetric
allocate
Object pop()
b ={ new{ Byte((byte) 100);
of constructors public
Line 1:class
Byte Person
i.e. ‘x.equals(x)’
and slower
ifpublic
(size 0)bshould
to collect.
== {=Personreturn true.
Line static
2: Byte newEmployee()
Byte.valueOf((byte) {
100);
 Avoid creating duplicate objects

 ItOverriding
takesthrow
at least two garbage
hashCode(): collection
It should cycles
return same(in
return new
new EmptyStackException();
Person(Role.EMPLOYEE);
 Eliminate obsolete object references the best
integer case)
value
}} every
On before
call,for a finalizeable
theaabove
same Object.
code object
will return is
the same

 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();}

Object result = elements[--size];

elements[size] = null; // Eliminate obsolete

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:

 Overridden methods should be public class Person {}


properly designed
public class Employee {

private Person person;

public class Customer {

private Person person;

}
 Never call overridden methods  public final in
Call super class Quark {
constructor

Avoid explicitly setting the field  Never synchronize


public Quark(String aName, double aMass){

values in constructors  Avoid


fName = aName;
creating overloaded constructors in Serialization

fMass = aMass;
processes
 Avoid creating overloaded
constructors in serialization }
process
//private String fName;

//private double fMass;

//Avoid below

private String fName = null;

private double fMass = 0.0d;

}
 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 */

public void readExternal(ObjectInput in) throws

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

 Prefer to program in terms of while


 Use List(ArrayList
method iterator.hasNext()
testLst=
interface for ){
newbunch
iterating ArrayList(10);
of things
interface not implementation
String
 Use
Empty stemp
Set Map by =using
interface iterator.next();
Collections.EMPTY_MAP
for using selection of things

 Prefer to return empty collections and }method


 Use Map interface for doing caching, datamining
arrays instead of null
//for loop

 Preferred way of using Iterator for (String str : iListValues){

String stemp = str;


 Preferred way of rotating through
object’s elements }

//while loop

while (j< lList.size()) {

String stemp = (String)lList.get(j); j++;

}
 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

 Always close your IO Streams class and remove


InputStream synchronize
in = new method
FileInputStream(myfile);

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) { () {

 Stop threads through co-operation protected synchronized


minSize,
} ThreadGroup
while Object
tg = new initialValue
ThreadGroup
(!isStopRequested() () { 1");
("group
&& !isDone){

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");

 Improve performance of multi- };} tg = TimeUnit.MILLISECONDS,


} new ThreadGroup ("group 2");
threaded application using }public new
Thread t4 =LinkedBlockingQueue<Runnable>()
new String
} synchronized ThreadgetName()
(tg, "my thread");
{
ThreadGroup
); tg = Thread.currentThread
return name; ().getThreadGroup ();
 Use ThreadLocal when same thread
int agc =that
}/** Request tg.activeGroupCount ();
this thread stop running. */
is implemented using different data
objects System.out.println ("Active thread groups in " +{
public
publicsynchronized
synchronizedvoid
void setName( String
requestStop(){ _name)

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

 Avoid Null Pointer Exceptions assert


private
void (user
long !== null)
new :ArrayList();
"User cannot
listexpirationTime;
mySimpleTokenizer(String
ArrayList be delimiter)
s, String null"; {

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

 Performance issues with // check


for (int whether
sub
i = 0; i <=limit; the
i++)object is free or not
s.substring(i,j);
{
StringTokenizer
abstracti =boolean
j + 1; validate( Object o );
list.clear();
 Use interfaces so that the actual remove
// do the of
//Rest
somethingobject
with from
list... the pool
Substrings
underlying data structure can be
actually changed without impacting } abstractj =void expire( Object o );
s.indexOf(delimiter, i);
the client program
//} get the object from pool

abstract Object get();// Last substring


sub = s.substring(i);

}}
 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);

 Reuse Lists, HashTables Objects by iobject.set(list);


= 0; // Attempts to initialize i to 0
using clear() } catch (NullPointerException npe) {
list.clear();

 Use StringBuilder instead of //list.add(2);


Ignores the exception handling
StringBuffer object2.set(list);
}
 Maintain Relevancy 
iftry {Use
If (you
null ==
are variable
the
reading a||file
try-block variable.isEmpty())
to from
enhance
a physical {
the scoping
disk: of

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

 Log Exceptions only once


 Don’t declare local variables before use
if (log.isDebugEnabled()) {
 Use java doc liberally log.debug("My debug message”);

 Avoid using raw data types }

 Manage constants in a individual class

 Field are usually to be private

 In java file try to keep separation of all


public and private fields

 Use @Override liberally

 Use static imports rarely

 Prefer to use log4j (or logging framework)


instead of System.out.println
 Use file copywright contents Identifier Case Example Note
/* DO NOT ALTER OR REMOVE COPYRIGHT
Class
http://cybintranet:8085/QMS%202.0/Docume
/
Pascal StringBuilder
Follow Pascal and Camel Casing Structure
NOTICES OR THIS HEADER.
 nts/Process%20Manual/SDLC/Construction
Enum Type Pascal DayName
* Copyright 2011 Cybage Software India and/or its
%20Process/S_COP_JCS.doc
 Document References
Enum Value - FORECOLOR Note: Always Capital
affiliates. All rights reserved.
Exception Note: Always suffix
Pascal
•File: Sample.java IndexOutExp
Class with Exception
Note: Always prefix
Interface Pascal Icloneable
* Description: with I
Method Pascal toString
* Rev:
Namespace Pascal System.Web
* Created on 1/17/11
Parameter Camel repeatCount
* Author: Dramil Dodeja (dramild@cybage.com)
Private Never: prefix with _
Camel repeatCount
Field
•* Description & Usage or m_
Property Pascal ForeColor
*--------------------------------------------------------
Local _+
_index
Variables Camel
*/
JSP Servlet best practices

Prepared By: Ashvin Gondalia


 JSP
Servlet JSP
 Servlets
Development java scripting file (.jsp)
 Limitations of Servlet classes
 It’s difficult to write HTML (.java)
 It’s ineffective to design web
pages
 It’s inaccessible to non-
Deployment Manual Directly mapped:
programmers compile copy JSP files to
Specifica intended
lly directories
 JSP is a complement to Servlet
 JSP focuses on user interface and
mapped
presentation Execution No need Automatic
 JSP enhances the design of compilation;
capability of Servlet source automatic
 JSP pages can be written with any files reloaded; source
text editor, including HTML files (.jsp) are
editor necessary

 JSP versus Servlet


 Use init() method when you need to cache
the data in your web application public
public class servlet
ServletOutputStream
Avoidclass
ByteArrayOutputStream
 creating newextends
TestServlet
out = HttpServlet
extends
threads = new{ {
HttpServlet
byteArray

 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

 Choosing the correct session mechanism 


Hidden codeserver
Field line2;implementation
HttpSession.getAttribute(String
Application Moderate Noname);
Param Limit
in your application
code line3;
 Tips for HttpSession objects codeModerate
line4;
ServletContext.setAttribute(String name,
Cookies No Size Limit

 Prefer to disable servlet auto reloading } cacheableObject);


Object

Below is better approach


ServletContext.getAttribute(String name);
 For improving scalability, prefer to use URL Rewrite Moderate No URL Limit
thread pool of your servlet engine and code line1;
define the size as per application
requirement synchronized(this) {code line2; }
Persistence Moderate to
code line3; No Size Limit
 Minimize the amount of code in the Poor
synchronized block code line4;
 Don’t overuse the Java Code in JSP pages <cache:cache time="7200">
JSP without
leadJSTL
Directive
 May
Reusable Include
Eliminates
Component
to scriptlets
performance issue

 Choose the correct include mechanism <%


<%@ //syntax
include
 Code will
Separation
Simple code
not of
ofbe getting
file="filename"
easy
businessto &combo
%>
read andbox data
presentation

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

JSP with JSTL


 JAR your custom taglibs for safer and
easier distribution <c:forEach var="message“ items="${messages}">

<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>

 Turn off session if you need not to scope="application">


</body>
identify the user details
<% </html>
 Choose right scope in useBean action cods.setURL((String)session.getValue(“cStr"));
<%@page isErrorPage="true" %> <html>

 Reuse your JSP code using @include cods.setUser("scott");


<body>
directive
cods.setPassword("tiger");
<head><title>Error

cods.setStmtCache (5);
Page.</title></head>

%> Error is:"<br/>Exception:<br/></font>

<%= exception.toString() %>

</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

 SOAP versus REST based Not object oriented Object oriented


webservices Browsers cannot Browsers can handle
handle request s requests directly
directly
WSDL WADL
Layered Non-Layered
State-less Stateful
Cannot locate Can locate via URI
resource via URI
Less reliable More reliable as no
central store of
information
 Prefer to use ‘top down’ and ‘Meet in
the middle’ development approach  WSDL
Implement
Bottom
Service
System will
Up have
Stateless
interfacebroader
Approach
Specific because
should range
more
Information each
of be i.e.
granular
should


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

code skeletons for other languages like


 Prefer to implement Stateless rather
than Stateful C/C++.

 Avoid putting system-relevant


information into the body of your
SOAP message

 Avoid using SOAP-RPC messaging


 Asynchronous messaging will
improve throughput at the cost of No needto wait
 Consumer-Side
Save your
Transaction
Prefer timeprevious
and
Caching
implement
calls operation’s
areresponses
simple
heavy time
callscalculation
over
latency

network
forso
response
Widely tryfor
Provide-Side
check use
your to cache
Caching such
popular
SOAP calls or it’s
services
Webservice
 Always measure the performance of  Increases
Widely
Gateway
SOAP usethe performance
Caching
to read-only
responses services
your service
 Scales the end user experience
 Prefer to cache the responses

 Prefer to cache the transactional


SOAP calls by saving their session
states

 Prefer to use any caching mechanism

 WSDL should be simple, well


formatted and interoperable
 JavaBeans or EJB components
 Hardware – High Performance
 JavaBeans
 Perform validation of SOAP  Java–virtual
 EJB Less Performance
machine heap size
messages using parsers only when
required  Data sources connection pool and

prepared statement cache


 Optimize SOAP processing by
implementing the caching  Pass by value/Pass by reference – in EJB
mechanism
component as WS
 Prefer to retrieve the SOAP service
 HTTP keep alive connections
bindings from the UDDI registry by
optimizing it  Transaction logs

 Hot list of parameters to test the


performance of your SOAP based
webservice
 Good approach to design the URIs
For
For XML
Service
 example:
schema
URI:
example:
Encoded
Server URI
Driven should
should be relevant
http://www.test.com/abc1234
derive
Approach metadata
Think about URI Opacity  Validate
Check only required
the Transaction schema
Status URI: at the
/invoice/{module1_id}/customer/{id}
  Only
ClientURI’s path should be Opaque
/invoice/{id1}/customer/{id2}
Driven Approach
consumer end
http://www.test.com/abc1234
?view=status
Below
 Easy
Proxy are some
toDriven
understand tips
Approach while
what thissending
URI is for
 Think about Query String If new module is added, then you can
receiving XML over HTTP:
Extensibility easily create a new URI as below:
Sample of IPid1 -> XML:
module
Filtering
status
Always negotiate with the Server  URL
<statusid2 Mapping
state=“failed" timestamp="2011-
-> identification

/invoice/{module2_id}/customer/{id}
Driven Approach 10-05 T00:00:00+5:30"
 Time />
based filtering
<errorbased
 Cookie code="3" >
filtering
 Prefer to implement a Status URI to <message>A
 Duplication bad filtering
detection
check the state of your webservice request.</message>
<exception>line 3234</exception>
 Preferred way of receiving and </error>
sending the XML over HTTP
</status>

 Use OAuth to secure your REST


services
 Handle versioning using HTTP
headers  Use Service Version Number into the
HTTP header
 Your service interfaces should be
compliant with older and newer
UDDI versions
 Document References
 http://cybintranet:8085/QMS%202.0/Docum

ents/Process%20Manual/SDLC/Design%20Pro

cess/S_DEP_SEHG.doc

You might also like