Best Practices
Best Practices
In this section, I present best practices for servlets and particularly JSP pages. The emphasis on JSP
best practices is simply because JSP pages seem to be more widely used (probably because JSP
technology promotes the separation of presentation from content). One best practice that combines and
integrates the use of servlets and JSP pages is the Model View Controller (MVC) design pattern,
discussed later in this article.
Don't overuse Java code in HTML pages: Putting all Java code directly in the JSP page is OK
for very simple applications. But overusing this feature leads to spaghetti code that is not easy to read
and understand. One way to minimize Java code in HTML pages is to write separate Java classes that
perform the computations. Once these classes are tested, instances can be created.
Choose the right include mechanism: Static data such as headers, footers, and navigation bar
content is best kept in separate files and not regenerated dynamically. Once such content is in separate
files, they can be included in all pages using one of the following include mechanisms:
The first include mechanism includes the content of the specified file while the JSP page is being
converted to a servlet (translation phase), and the second include includes the response generated after
the specified page is executed. I'd recommend using the include directive, which is fast in terms of
performance, if the file doesn't change often; and use the include action for content that changes often or
if the page to be included cannot be decided until the main page is executed.
Another include mechanism is the <c:import> action tag provided by the JavaServer pages Standard Tag
Library (JSTL). You can use this tag to bring in, or import, content from local and remote sources. Here
are some examples:
<c:import url="./copyright.html"/>
<c:import url="http://www.somewhere.com/hello.xml"/>
Don't mix business logic with presentation: For advanced applications, and when more code
is involved, it's important not to mix business logic with front-end presentation in the same file. Separating
business logic from presentation permits changes to either side without affecting the other. However,
production JSP code should be limited to front-end presentation. So, how do you implement the business
logic part? That is where JavaBeans technology comes into play. This technology is a portable, platform-
independent component model that lets developers write components and reuse them everywhere. In the
context of JSP pages, JavaBeans components contain business logic that returns data to a script on a
JSP page, which in turn formats the data returned from the JavaBeans component for display by the
browser. A JSP page uses a JavaBeans component by setting and getting the properties that it provides.
The benefits of using JavaBeans components to augment JSP pages are:
2. Separation of business logic and presentation logic: You can change the way data is
displayed without affecting business logic. In other words, web page designers can focus on presentation
and Java developers can focus on business logic.
If you use Enterprise JavaBeans (EJBs) components with your application, the business logic should
remain in the EJB components which provide life-cycle management, transaction support, and multi-client
access to domain objects (Entity Beans).
Use custom tags: Embedding bits of Java code (or scriptlets) in HTML documents may not be
suitable for all HTML content developers, perhaps because they do not know the Java language and don't
care to learn its syntax. While JavaBeans components can be used to encapsulate much of the Java
code, using them in JSP pages still requires content developers to have some knowledge of Java syntax.
JSP technology allows you to introduce new custom tags through the tag library facility. As a Java
developer, you can extend JSP pages by introducing custom tags that can be deployed and used in an
HTML-like syntax. Custom tags also allow you to provide better packaging by improving the separation
between business logic and presentation logic. In addition, they provide a means of customizing
presentation where this cannot be done easily with JSTL.
1. They can eliminate scriptlets in your JSP applications. Any necessary parameters to the
tag can be passed as attributes or body content, and therefore no Java code is needed to initialize or set
component properties.
2. They have simpler syntax. Scriptlets are written in Java code, but custom tags can be
used in an HTML-like syntax.
4. They are reusable. They save development and testing time. Scriptlets are not reusable,
unless you call cut-and-paste "reuse."
In short, you can use custom tags to accomplish complex tasks the same way you use HTML to create a
presentation.
The following programming guidelines are handy when writing custom tag libraries:
5. Keep it simple: If a tag requires several attributes, try to break it up into several tags.
6. Make it usable: Consult the users of the tags (HTML developers) to achieve a high
degree of usability.
7. Do not invent a programming language in JSP pages: Do not develop custom tags that
allow users to write explicit programs.
8. Try not to re-invent the wheel: There are several JSP tag libraries available, such as the
Jakarta Taglibs Project. Check to see if what you want is already available.
Do not reinvent the wheel: While custom tags provide a way to reuse valuable components,
they still need to be created, tested, and debugged. In addition, developers often have to reinvent the
wheel over and over again and the solutions may not be the most efficient. This is the problem that the
JavaServer Pages Standard Tag Library (JSTL) solves, by providing a set of reusable standard tags.
JSTL defines a standard tag library that works the same everywhere, so you no longer have to iterate
over collections using a scriptlet (or iteration tags from numerous vendors). The JSTL includes tags for
looping, reading attributes without Java syntax, iterating over various data structures, evaluating
expressions conditionally, setting attributes and scripting variables in a concise manner, and parsing XML
documents.
Use the JSTL Expression Language: Information to be passed to JSP pages is communicated
using JSP scoped attributes and request parameters. An expression language (EL), which is designed
specifically for page authors, promotes JSP scoped attributes as the standard way to communicate
information from business logic to JSP pages. Note, however, that while the EL is a key aspect of JSP
technology, it is not a general purpose programming language. Rather, it is simply a data access
language, which makes it possible to easily access (and manipulate) application data without having to
use scriptlets or request-time expression values.
In JSP 1.x, a page author must use an expression <%= aName %> to access the value of a system, as in
the following example:
<someTags:aTag attribute="<%=
pageContext.getAttribute("aName") %>">
or the value of a custom JavaBeans component:
<%= aCustomer.getAddress().getCountry() %>
An expression language allows a page author to access an object using a simplified syntax. For example,
to access a simple variable, you can use something like:
<someTags:aTag attribute="${aName}">
And to access a nested JavaBeans property, you would use something like:
<someTags.aTag attribute="${
aCustomer.address.country}">
If you've worked with JavaScript, you will feel right at home, because the EL borrows the JavaScript
syntax for accessing structured data.
Use filters if necessary: One of the new features of JSP technology is filters. If you ever come
across a situation where you have several servlets or JSP pages that need to compress their content, you
can write a single compression filter and apply it to all resources. In Java BluePrints, for example, filters
are used to provide the SignOn.
Use a portable security model: Most application servers provide server- or vendor-specific
security features that lock developers to a particular server. To maximize the portability of your enterprise
application, use a portable web application security model. In the end, however, it's all about tradeoffs.
For example, if you have a predefined set of users, you can manage them using form-based login or
basic authentication. But if you need to create users dynamically, you need to use container-specific APIs
to create and manage users. While container-specific APIs are not portable, you can overcome this with
the Adapter design pattern.
Use a database for persistent information: You can implement sessions with
an HttpSessionobject, which provides a simple and convenient mechanism to store information about
users, and uses cookies to identify users. Use sessions for storing temporary information--so even if it
gets lost, you'll be able to sleep at night. (Session data is lost when the session expires or when the client
changes browsers.) If you want to store persistent information, use a database, which is much safer and
portable across browsers.
Cache content: You should never dynamically regenerate content that doesn't change between
requests. You can cache content on the client-side, proxy-side, or server-side.
Use connection pooling: I'd recommend using the JSTL for database access. But if you wish to
write your own custom actions for database access, I'd recommend you use a connection pool to
efficiently share database connections between all requests. However, note that J2EE servers provide
this under the covers.
Cache results of database queries: If you want to cache database results, do not use the
JDBC'sResultSet object as the cache object. This is tightly linked to a connection that conflicts with the
connection pooling. Copy the data from a ResultSet into an application-specific bean such asVector, or
JDBC's RowSets.
Adopt the new JSP XML syntax if necessary. This really depends on how XML-compliant you
want your applications to be. There is a tradeoff here, however, because this makes the JSP more tool-
friendly, but less friendly to the developer.
Quote 1: Avoid creating unnecessary objects and always prefer to do Lazy Initialization
Object creation in Java is one of the most expensive operation in terms of memory utilization and
performance impact. It is thus advisable to create or initialize an object only when it is required in the
code.
01 public class Countries {
02
03 private List countries;
04
05 public List getCountries() {
06
07 //initialize only when required
08 if(null == countries) {
09 countries = new ArrayList();
10 }
11 return countries;
12 }
13 }
Quote 2: Never make an instance fields of class public
Making a class field public can cause lot of issues in a program. For instance you may have a class called
MyCalender. This class contains an array of String weekdays. You may have assume that this array will
always contain 7 names of weekdays. But as this array is public, it may be accessed by anyone.
Someone by mistake also may change the value and insert a bug!
1 public class MyCalender {
2
But writing getter method does not exactly solve our problem. The array is still accessible. Best way to
make it unmodifiable is to return a clone of array instead of array itself. Thus the getter method will be
changed to.
1 public String[] getWeekdays() {
2 return weekdays.clone();
3}
Quote 3: Always try to minimize Mutability of a class
Making a class immutable is to make it unmodifiable. The information the class preserve will stay as it is
through out the lifetime of the class. Immutable classes are simple, they are easy to manage. They are
thread safe. They makes great building blocks for other objects.
However creating immutable objects can hit performance of an app. So always choose wisely if you want
your class to be immutable or not. Always try to make a small class with less fields immutable.
To make a class immutable you can define its all constructors private and then create a public static
method
to initialize and object and return it.
01 public class Employee {
02
03 private String firstName;
04 private String lastName;
05
06 //private default constructor
07 private Employee(String firstName, String lastName) {
08 this.firstName = firstName;
09 this.lastName = lastName;
10 }
11
12 public static Employee valueOf (String firstName, String lastName) {
13 return new Employee(firstName, lastName);
14 }
15 }
Quote 4: Try to prefer Interfaces instead of Abstract classes
First you can not inherit multiple classes in Java but you can definitely implements multiple interfaces. Its
very easy to change the implementation of an existing class and add implementation of one more
interface rather then changing full hierarchy of class.
Again if you are 100% sure what methods an interface will have, then only start coding that interface. As it
is very difficult to add a new method in an existing interface without breaking the code that has already
implemented it. On contrary a new method can be easily added in Abstract class without breaking existing
functionality.
Local variables are great. But sometimes we may insert some bugs due to copy paste of old code.
Minimizing the scope of a local variable makes code more readable, less error prone and also improves
the maintainability of the code.
Thus, declare a variable only when needed just before its use.
Always initialize a local variable upon its declaration. If not possible at least make the local instance
assigned null value.
Quote 6: Try to use standard library instead of writing your own from scratch
Writing code is fun. But “do not reinvent the wheel”. It is very advisable to use an existing standard library
which is already tested, debugged and used by others. This not only improves the efficiency of
programmer but also reduces chances of adding new bugs in your code. Also using a standard library
makes code readable and maintainable.
For instance Google has just released a new library Google Collections that can be used if you want to
add advance collection functionality in your code.
Quote 7: Wherever possible try to use Primitive types instead of Wrapper classes
Wrapper classes are great. But at same time they are slow. Primitive types are just values, whereas
Wrapper classes are stores information about complete class.
Sometimes a programmer may add bug in the code by using wrapper due to oversight. For example, in
below example:
1 int x = 10;
2 int y = 10;
3
4 Integer x1 = new Integer(10);
5 Integer y1 = new Integer(10);
6
7 System.out.println(x == y);
8 System.out.println(x1 == y1);
The first sop will print true whereas the second one will print false. The problem is when comparing two
wrapper class objects we cant use == operator. It will compare the reference of object and not its actual
value.
Also if you are using a wrapper class object then never forget to initialize it to a default value. As by
default all wrapper class objects are initialized to null.
1 Boolean flag;
2
3 if(flag == true) {
4 System.out.println("Flag is set");
5 } else {
6 System.out.println("Flag is not set");
7}
The above code will give a NullPointerException as it tries to box the values before comparing with true
and as its null.
Quote 8: Use Strings with utmost care.
Always carefully use Strings in your code. A simple concatenation of strings can reduce performance of
program. For example if we concatenate strings using + operator in a for loop then everytime + is used, it
creates a new String object. This will affect both memory usage and performance time.
Also whenever you want to instantiate a String object, never use its constructor but always instantiate it
directly. For example:
1 //slow instantiation
2 String slow = new String("Yet another string object");
3
4 //fast instantiation
5 String fast = "Yet another string object";
Quote 9: Always return empty Collections and Arrays instead of null
Whenever your method is returning a collection element or an array, always make sure you
returnempty array/collection and not null. This will save a lot of if else testing for null elements. For
instance in below example we have a getter method that returns employee name. If the name is null it
simply return blank string “”.
1 public String getEmployeeName() {
2 return (null==employeeName ? "": employeeName);
3}
Quote 10: Defensive copies are savior
Defensive copies are the clone objects created to avoid mutation of an object. For example in below code
we have defined a Student class which has a private field birth date that is initialized when the object is
constructed.
07
08 public Date getBirthDate() {
09 return this.birthDate;
10 }
11 }
Now we may have some other code that uses the Student object.
1 public static void main(String []arg) {
2
3 Date birthDate = new Date();
4 Student student = new Student(birthDate);
5
6 birthDate.setYear(2019);
7
8 System.out.println(student.getBirthDate());
9}
In above code we just created a Student object with some default birthdate. But then we changed the
value of year of the birthdate. Thus when we print the birth date, its year was changed to 2019!
To avoid such cases, we can use Defensive copies mechanism. Change the constructor of Student class
to following.
1 public Student(birthDate) {
2 this.birthDate = new Date(birthDate);
3}
This ensure we have another copy of birthdate that we use in Student class.
Here are two bonus Java best practice quotes for you.
Finally blocks should never have code that throws exception. Always make sure finally clause does not
throw exception. If you have some code in finally block that does throw exception, then log the exception
properly and never let it come out :)
Never throw java.lang.Exception directly. It defeats the purpose of using checked Exceptions. Also there
is no useful information getting conveyed in caller method.