best practices - java

15
BEST PRACTICES - Java By www.PPTSWorld.com

Upload: melia

Post on 05-Jan-2016

25 views

Category:

Documents


0 download

DESCRIPTION

BEST PRACTICES - Java. By www.PPTSWorld.com. Configuration. Use global-forwards/results Helps to avoid duplicate jsp files and redundancy forward mapping in all the actions in struts.xml E.g Global error pages Success message pages. Base class. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: BEST PRACTICES  - Java

BEST PRACTICES

- Java

By www.PPTSWorld.com

Page 2: BEST PRACTICES  - Java

Configuration

Use global-forwards/results• Helps to avoid duplicate jsp files and

redundancy forward mapping in all the actions in struts.xml– E.g

Global error pages Success message pages.

Page 3: BEST PRACTICES  - Java

Base class

• Have a Base class for each of the layers used• This will help -

– common operations need to be included in all the classes in each layer can be defined/implemented in the base class to reduce code redundancy

E.g. Methods to read data from properties

– Have base class implement multiple interfaces required, so that each subclass need not implement them.

E.g. In struts2.0 base action class can implement multiple interfaces like SessionAware, ServletRequestAware, ServletResponseAware, ServletRequestAware, etc.

Page 4: BEST PRACTICES  - Java

Application start up servlet

• Create a servlet class and have it invoked while application status up.

• Include methods – – To load static data from data base which is

frequently accessed. This will reduce the DB calls

– To read properties from property file. This will eliminate the I/O operation, when ever a property value is need to be read and used.

Page 5: BEST PRACTICES  - Java

Exception handling

• Define a Application level Exception handling mechanism, and configure struts global exception handler.

• Don’t throw multiple exception to the calling method in other layer’s class (e.g. business class method calling a DAO class method) to handle, Instead wrap to a user defined Exception and re throw, so that the calling method need not to handle multiple exceptions and also it eliminates the layer coupling.

• Don’t handle any exception other than in action layer Unless if you know what should be done on the exception condition (e.g it may call another business case on exception)

• Don’t handle all the exception in action class, let global exception handle the exception and forward to common error page unless if you want to catch a specific exception and show custom error message to the user.

Page 6: BEST PRACTICES  - Java

Logging

• Reduce unnecessary logger statements. More the logger statement lesser the performance

• Avoid logging same date in multiple places of a single sequence in same class

• Use appropriate logger level for logging information.• Don’t log each data in a separate logger statement instead

concat and log them into a single logger statement.• Have maximum only one INFO level logger statement in

layers other than DAO to identify data flow• DAO layer you method start time and end time can be in

INFO.

Page 7: BEST PRACTICES  - Java

Java Server Pages

• Use a global error page.• Always link to Actions, never to server

pages.• Use the action attributes tag to avoid

embedding Action extension.• Use s:url to reference HTML assets.• Use s:include to include pages

Page 8: BEST PRACTICES  - Java

Handle Duplicate Form Submission

• The problem of duplicate form submission arises when a user clicks the Submit button more than once before the response is sent back.

• Handle it by using the Token interceptor, tokenSession. This checks for valid token presence in action, stores the submitted data in session when handed an invalid token and prevents double submission.

• Don’t use button type as submit while submitting a form thorough script to avoid duplicate form submit.

Page 9: BEST PRACTICES  - Java

Use html:messages (instead of html:errors)

• For displaying error messages to the end user, use html:messages instead of html:errors

Page 10: BEST PRACTICES  - Java

Errors

• To display the error messages of different categories, define these categories such as FATAL, ERROR, WARNING, or INFO, in an interface

• In the Action or form-bean class, you can then use the following– errors.add("fatal", new ActionError("....")); or– errors.add("error", new ActionError("....")); or– errors.add("warning", new ActionError("....")); or– errors.add("information", new ActionError("...."));– saveErrors(request,errors);

Page 11: BEST PRACTICES  - Java

Errors (contd..)

• To display them according to those categories, use the following code:

<logic:messagePresent property="error"><html:messages property="error" id="errMsg" ><bean:write name="errMsg"/></html:messages></logic:messagePresent >

Or use:<logic:messagePresent property="error"><html:messages property="error" id="errMsg" >showError('<bean:write name="errMsg"/>'); // JavaScript

Function</html:messages></logic:messagePresent >

Page 12: BEST PRACTICES  - Java

Common best practices

• Use static methods for util class which contains commonly used util methods

• Don’t hardcode any value instead use Constance.

• Constance should be static final.• Have only one util class for an application• If server side validation is used for input

values, then use separate util class for action layer to hold only the validation methods.

Page 13: BEST PRACTICES  - Java

Common best practices - (contd..)

• Where ever passable use switch case statement then if else • Avoid iterating a collection multiple times• Avoid executing DB call with in a loop.• Don’t use static instance variable in action class (Struts 2.0)• Action Classes should not implement complex business

functionalities, rather delegate these to the Business/Service layer

• Don’t use instance variable to store transactional data in spring Business Service class

• Don’t use egger fetching (lazy=false) for one-to-many mapping in hibernate, instead use lazy fetching (lazy=true).

Page 14: BEST PRACTICES  - Java

Common best practices - (contd..)

• Don’t get hibernate session directly using session = getSession(); to execute query, instead use HibernateTemplate’s call back method.

Page 15: BEST PRACTICES  - Java

Common best practices - (contd..)

Incorrect code

Session session = getSession();String sqlQuery = "SELECT * FROM employee";

Query query = session.createSQLQuery(sqlQuery); List list = query.list();

Correct Code

String final sqlQuery = "SELECT * FROM employee"; List list = getHibernateTemplate().executeFind( new HibernateCallback(){

List list = null; public Object doInHibernate(Session session) throws HibernateException, SQLException{ Query query = session.createSQLQuery(sqlQuery); list = query.list(); return list; } } );