Skip to main content

If you don't have an IBM ID and password, register here.

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

EJB best practices: The fine points of data validation

How to get the best performance out of your validation code

Brett McLaughlin (brett@newInstance.com), Author and Editor, O'Reilly Media Inc.
Photo of Brett McLaughlin
Brett McLaughlin has been working in computers since the Logo days (remember the little triangle?). He currently specializes in building application infrastructure using Java and Java-related technologies. He has spent the last several years implementing these infrastructures at Nextel Communications and Allegiance Telecom, Inc. Brett is one of the co-founders of the Java Apache project Turbine, which builds a reusable component architecture for Web application development using Java servlets. He is also a contributor of the EJBoss project, an open source EJB application server, and Cocoon, an open source XML Web-publishing engine. Contact Brett at brett@oreilly.com.

Summary:  Although data validation is a necessary component of all enterprise applications, data validation processes are generally poorly understood and badly executed. In this installment of EJB best practices, Brett McLaughlin explains some of the concepts behind data validation on EJB technology-based systems, and shows you how to avoid unexpected or incomprehensible error messages.

View more content in this series

Date:  01 Dec 2002
Level:  Intermediate

Comments:  

Anytime you're dealing with the business logic of an application, validation will become a factor. Your application must have a way to ensure that incoming data is in the right format, as well as to perform business-specific validation such as cross-checking purchase orders against inventory.

Rather than focus on validation processes (which are well-covered in other areas of the Java technology zone), we'll examine where data validation logic should occur in your EJB application code. In previous tips in this series, we've learned quite a bit about the components that make up an EJB technology-based application: the underlying session bean and its business interface; the value objects that transfer data between an entity bean and its clients; and the various delegate classes that act as a protective layer between the Web tier and the business tier. Validation logic could fit quite comfortably in any one of these components. In fact, you could place validation logic in multiple components, layering it throughout the application (although that wouldn't be advisable). So the question we're asking here is, Where is it most beneficial to place validation code in your EJB applications?

Types of data validation

The first step to figuring out where to place your validation code is knowing what type of validation you're dealing with. Data-format validation ensures that all data types (integers, floating point numbers, strings, and so on) are correct. It also confirms that variables are within the range of allowed values and that patterns match as they should. Data-format validation essentially deals with any aspect of validation that doesn't require the application of specific business rules.

Do you know the difference?

The ability to clearly distinguish between the two types of data validation is critical to good application design. Deliberate or unintentional mixing of the two types of validation can result in horribly architected classes and inefficient application performance.

Business-specific validation is based on a set of business rules (for example, ensuring that a supplied ISBN number matches an actual book in your database). It almost always requires access to the EJB layer, as well as other business-logic components in your application.


Data-format validation

Once you've determined the type of validation you're working with, the next step is to figure out where to place the code. Data-format validation logic can be placed as follows in your EJB apps:

  • The mutator (setter) methods on your business delegate.
  • The mutator (setter) methods on your bean's remote interface.
  • The mutator (setter) methods on your bean's info or value object.

For the purpose of this example, we're going to assume you're working with an EJB app that includes a business delegate. If that's so, you should be taking steps to ensure that all of your application clients (in the Web tier) are using the delegate for bean access rather than accessing the bean directly. And if that's the case, you can safely place all your data validation code in the business delegate methods, as shown in Listing 1.


Listing 1. Data-format validation in the business delegate


package com.ibm.library;

import java.rmi.RemoteException;
import java.util.Iterator;
import java.util.List;
import javax.ejb.CreateException;
import javax.naming.NamingException;

public class LibraryDelegate implements ILibrary {

      private ILibrary library;

      public LibraryDelegate() {
          init();
      }

      public void init() {
          // Look up and obtain our session bean
          try {
              LibraryHome libraryHome =
                  (LibraryHome)EJBHomeFactory.getInstance().lookup(
                      "java:comp/env/ejb/LibraryHome", LibraryHome.class);
              library = libraryHome.create();
          } catch (NamingException e) {
              throw new RuntimeException(e);
          } catch (CreateException e) {
              throw new RuntimeException(e);
          } catch (RemoteException e) {
              throw new RuntimeException(e);
          }
      }

      // No validation required for accessor (getter) methods

      public boolean checkout(Book book) throws ApplicationException {
	    // No validation required here; the object type
		//   takes care of it

          try {
              return library.checkout(book);
          } catch (RemoteException e) {
              throw new ApplicationException(e);
          }
      }

      public boolean checkout(List books) throws ApplicationException {
	    // Validate list
		for (Iterator i = books.iterator(); i.hasNext(); ) {
		  Object obj = i.next();
		    if !(obj instanceof Book) {
			throw new ApplicationException(
			  ApplicationException.VALIDATION_ERROR,
			  "Only Books are allowed in the input list");
			}
		}

          try {
              return library.checkout(books);
          } catch (RemoteException e) {
              throw new ApplicationException(e);
          }
      }

      // And so on...

      public void destroy() {
          // In this case, do nothing
      }
}

When it comes to data-format validation, you want to keep your validation logic as close to the client as possible. Data-format validation often triggers error pages or requires the client to re-enter incorrectly formatted data. In these cases you want to provide feedback to the client quickly, and with minimal cost to your processing overhead. By placing the validation logic in the business delegate, you've created the most natural error-handling scenario. When a client tries to query the delegate with data that is incorrectly formatted, an error is triggered and the request is sent directly back to the client, alerting the user of the problem.

Placing the validation logic in the bean implementation would create a much less efficient validation process. Rather than going directly from the delegate to the client, error messages would be passed from the bean implementation to the delegate, most likely as a RemoteException rather than an application exception. In addition to the cost of the remote exception, the delegate would have already paid the price of JNDI lookups, RMI traffic, and (possibly) additional business logic -- far too much processing power to spend on a single validation error!


Business-specific validation

Business-specific validation is a different case altogether. Business validation errors are generally more complex than data validation errors, and are rarely resolved by client interaction. Resolving business-specific errors requires the use of additional entity and session beans, as well as database access, all of which must be processed through JNDI and RMI transactions. That's a lot of overhead to put on a business delegate. A much better idea is to move this validation back into the EJB layer, specifically into the bean's implementation class.

When placed in that layer of the application, all of your RMI traffic should be local; most application servers will use in-VM optimizations to make bean-to-bean interaction extremely fast. You may also avoid JNDI access, since many beans will already have looked up related beans' home interfaces. Furthermore, your business delegate will already have handled any necessary data-format validation.


Conclusion

When deciding where to place your validation code, it's important to be able to distinguish between the two validation types. Data validation is a much simpler type of validation than business validation, and the general rule of thumb is to keep it as close to the client as possible. Business-specific validation is more complex and often requires several different transactions to complete. This type of validation should be located in the EJB layer, where it can piggy-back on existing processes as much as possible.

In the next tip, we'll look at additional ways to enhance your application's validation processes, and isolate the validation from your business delegates completely. Until then, check out the further reading in the Resources section, and I'll catch you online!


Resources

About the author

Photo of Brett McLaughlin

Brett McLaughlin has been working in computers since the Logo days (remember the little triangle?). He currently specializes in building application infrastructure using Java and Java-related technologies. He has spent the last several years implementing these infrastructures at Nextel Communications and Allegiance Telecom, Inc. Brett is one of the co-founders of the Java Apache project Turbine, which builds a reusable component architecture for Web application development using Java servlets. He is also a contributor of the EJBoss project, an open source EJB application server, and Cocoon, an open source XML Web-publishing engine. Contact Brett at brett@oreilly.com.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in

If you don't have an IBM ID and password, register here.


Forgot your IBM ID?


Forgot your password?
Change your password


By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)


By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java technology
ArticleID=10735
ArticleTitle=EJB best practices: The fine points of data validation
publish-date=12012002
author1-email=brett@newInstance.com
author1-email-cc=

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

For articles in technology zones (such as Java technology, Linux, Open source, XML), Popular tags shows the top tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), Popular tags shows the top tags for just that product zone.

For articles in technology zones (such as Java technology, Linux, Open source, XML), My tags shows your tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), My tags shows your tags for just that product zone.

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).