Session beans define a process or task. Software systems are made up of collections of
processes, and in many instances each process is composed of smaller tasks. This architecture
is exactly what session beans are designed to build. This is how you should design the business
logic of your software using session beans.
If you develop processes that are generic and reusable on many systems, you can use these ses-
sion beans independently, or develop more detailed session beans that string together several of
these processes. Think of a session bean that processes a credit card transaction or a session
bean with methods to provide several different billing mechanisms. This is certainly a useful
utility from which many systems can benefit.
Stateless Versus Stateful
Within the family of session beans there are two types, stateless and stateful. Session beans do
not have persistence, but that does not prevent them from having attributes and holding state.
The distinction between stateless and stateful is that a stateful session bean can have attributes
that hold a conversational state between method invocations. This state is necessary and must
not be lost between method calls. An example is an e-commerce shopping cart. When the cart
is created it will be empty, but eventually a call will be made to add an item, and then to
change the quantity of that item in the cart. More items can be added, but at some point the
user will want to check out. If all of the information about the items previously placed in the
basket is lost at some point during this process, the customer will be angry.
This is a great concept, but allowing a session bean to maintain state does not come without a
price. A stateful session bean is less efficient than a stateless bean for more than one reason.
One of the big costs comes from the fact that more stateful session beans need to exist simulta-
neously because they cannot be shared as readily as stateless session beans. How would you
like it if somebody else placed things in your shopping cart? The topic of bean pooling and
reuse will be discussed later.
Stateless session beans on the other hand hold no state that is required to be kept between
method invocations. After the method has finished processing, it returns and no longer main-
tains any information specific to the client that it just serviced. A session bean used to process
a credit card payment illustrates this. The method to handle this business process would take
all the necessary information as parameters, and would return success or failure. None of the
information needs to be retained by the session bean. This fictitious bean can also contain the
business logic to process a payment by check.
Each session bean in a system should be evaluated as to whether it needs to maintain conversa-
tional state. In most cases it will be obvious after the processes are clearly specified.