EJB Layer Architectural Patterns 7 Poor reusability.The business logic that executed the"transfer funds" use case was embedded directly in the client.It therefore effectively psnado2hteoem ing of presentation logic with business logic is a poor application design for any serious deployment Poor maintainability.Usage of the Java Transaction API causes middle- ware logic for performing transactions to be interlaced with application logic.It is much cleaner to separate the two via declarative transactions, so that we can tweak and tune our middleware without affecting our business rules Poor separation of development roles.A common practice on large scale projects is to separate the development tasks of presentation logic programmers(such as servlet/jsp developers)from the business logic/middleware programmers(EJB developers).If business logic is coded in the client/presentation layer,a clear separation of roles is not possible.Business logic and presentation logic programmers will step on each other's toes if both program in the presentation layer. The takeaway point from our discussion is that we need a server-side abstraction that serves as an intermediary and buffers calls to entity beans Session beans are designed just for this. Therefore: Wrap the entity bean layer in a layer of session beans called the Ses- sion Facade.Clients should have access only to session beans not to entity beans The Session Facade pattern applies the benefits of the traditional Facade pattern to EJB by completely hiding the object model on the server from the client layer,by having a layer of session beans be the single point of access to the client.Figure 1.2 illustrates how an architecture can be improved by taking this approach.The Session Facade pattern further adds the benefits of enforc- ing the execution of a use case in one network call and providing a clean layer in which to encapsulate business and workflow logic used to fulfill use cases. The Session Facade is usually implemented as a layer of stateless session beans (although the pattern can also be implemented with stateful session beans)
■■ Poor reusability. The business logic that executed the “transfer funds” use case was embedded directly in the client. It therefore effectively becomes trapped in that client. Other types of clients (Java applications, applets, servlets, and so on) cannot reuse this business logic. This mixing of presentation logic with business logic is a poor application design for any serious deployment. ■■ Poor maintainability. Usage of the Java Transaction API causes middleware logic for performing transactions to be interlaced with application logic. It is much cleaner to separate the two via declarative transactions, so that we can tweak and tune our middleware without affecting our business rules. ■■ Poor separation of development roles. A common practice on largescale projects is to separate the development tasks of presentation logic programmers (such as servlet/jsp developers) from the business logic/middleware programmers (EJB developers). If business logic is coded in the client/presentation layer, a clear separation of roles is not possible. Business logic and presentation logic programmers will step on each other’s toes if both program in the presentation layer. The takeaway point from our discussion is that we need a server-side abstraction that serves as an intermediary and buffers calls to entity beans. Session beans are designed just for this. Therefore: Wrap the entity bean layer in a layer of session beans called the Session Façade. Clients should have access only to session beans not to entity beans. The Session Façade pattern applies the benefits of the traditional Façade pattern to EJB by completely hiding the object model on the server from the client layer, by having a layer of session beans be the single point of access to the client. Figure 1.2 illustrates how an architecture can be improved by taking this approach. The Session Façade pattern further adds the benefits of enforcing the execution of a use case in one network call and providing a clean layer in which to encapsulate business and workflow logic used to fulfill use cases. The Session Façade is usually implemented as a layer of stateless session beans (although the pattern can also be implemented with stateful session beans). EJB Layer Architectural Patterns 7
8 Chapter One App.Server App.Serve Client Client Client Network Client Client Client Direct Entity Bean Access Session Facade Figure 1.2 The Architectural benefits of Session Facade. To illustrate how this paradigm works and the benefits of this paradigm let's take our previous example.Our business logic for the transferring funds use case will now be placed in a session bean,which has a method called transfer- Funds(userpk,accountpk,accountpk,amount).The Bank Teller session bean thus performs bulk operations on Users and Bank Accounts,as shown in Figure 1.3. Since the BankTeller session bean is collocated with the User and Account entity beans.it should be hard-coded to communicate with the entity beans through their local interfaces,thus reducing the network c erhead required to execute this use case to just one call(the call to the BankTeller from the client). Also,all updates to the entity bean layer should run within the transaction initi- ated by the Bank Teller,defined in its deployment descriptor,almost always,with a setting of TX_REQUIRED.This effectively wraps the entire use case within one transaction,ensuring that all updates to the entity beans run within the transac- tion initiated upon execution of the transferFunds method on the Bank Teller. ankTeller Account 1 Account2 findByPrimaryKey(pk) Funds isAuthorized( Network withdrawFunds(amount) depositFunds(amount) Figure 1.3 The Performance benefits of Session Facade
Figure 1.2 The Architectural benefits of Session Façade. To illustrate how this paradigm works and the benefits of this paradigm, let’s take our previous example. Our business logic for the transferring funds use case will now be placed in a session bean, which has a method called transferFunds(userpk, accountpk, accountpk, amount). The Bank Teller session bean thus performs bulk operations on Users and Bank Accounts, as shown in Figure 1.3. Since the BankTeller session bean is collocated with the User and Account entity beans, it should be hard-coded to communicate with the entity beans through their local interfaces, thus reducing the network overhead required to execute this use case to just one call (the call to the BankTeller from the client). Also, all updates to the entity bean layer should run within the transaction initiated by the BankTeller, defined in its deployment descriptor, almost always, with a setting of TX_REQUIRED. This effectively wraps the entire use case within one transaction, ensuring that all updates to the entity beans run within the transaction initiated upon execution of the transferFunds method on the Bank Teller. Figure 1.3 The Performance benefits of Session Façade. transferFunds (userpk, account1pk, account2pk, amount) User findByPrimaryKey(pk) Account Home BankTeller UserHome Account 1 Account2 isAuthorized() findByPrimaryKey(account1PK) findByPrimaryKey(account2PK) withdrawFunds(amount) depositFunds(amount) Servlet Network App. Server App. Server Client Client Client F a c a d e F a c a d e Direct Entity Bean Access Session Facade Client Client Client Network Network 8 Chapter One
EJB Layer Architectural Patterns 9 The Session Facade pattern is the most fundamental EJB pattern in use today(which is why it is the very first pattern in this book).It not only pro vides performance benefits,but it also suggests a standard architecture for EJB systems-partitioning your J2EE applications in such a way that the boundary between the client and sever is separated by a layer of session beans,whose methods map to (and contain the business logic of)all the use cases in the application. Taking the Bank Teller example further,there are obviously more use cases involving a bank application than simply transferring funds.Using the Session Facade pattern,session beans would be created to group use cases with similar functions into one bean.Thus we can add other ancillary banking operations to the Bank Teller(such as withdrawFunds,depositFunds,getBalance()).Elsewhere in the banking application,use cases for different purposes would also be grouped into a session bean.For example,every bank has a Loans Department. Teller;therefore,they would be grouped into a LoanServices session bean.Similarly,a banking application would also need a session bean to encapsulate use cases related to investments.Using the Session Facade pattern,the architectural layout of this banking application would look like Figure 1.4. Clients Tier Session Facade Domain Model Session Bean transferFunds ClientA alance Client B Network onsinfo Figure 1.4 Grouping use cases into session beans architectural layout
The Session Façade pattern is the most fundamental EJB pattern in use today (which is why it is the very first pattern in this book). It not only provides performance benefits, but it also suggests a standard architecture for EJB systems-partitioning your J2EE applications in such a way that the boundary between the client and sever is separated by a layer of session beans, whose methods map to (and contain the business logic of) all the use cases in the application. Taking the Bank Teller example further, there are obviously more use cases involving a bank application than simply transferring funds. Using the Session Façade pattern, session beans would be created to group use cases with similar functions into one bean. Thus we can add other ancillary banking operations to the Bank Teller (such as withdrawFunds, depositFunds, getBalance()). Elsewhere in the banking application, use cases for different purposes would also be grouped into a session bean. For example, every bank has a Loans Department. The use cases required to model the operations of a Loans Department are not that related to the use cases on a Bank Teller; therefore, they would be grouped into a LoanServices session bean. Similarly, a banking application would also need a session bean to encapsulate use cases related to investments. Using the Session Façade pattern, the architectural layout of this banking application would look like Figure 1.4. Figure 1.4 Grouping use cases into session beans architectural layout. Session Facade transferFunds withdrawFunds depositFunds getBalance ... BankTeller Session Bean isPersonApprovable approveLoan createLoan ... LoanServices Session Bean buyStock getStockInfo sellStock buyBond sellBond getOptionsInfo ... InvestmentServices Session Bean Clients Tier Domain Model Client A Client B Client C Network EJB Layer Architectural Patterns 9
10 Chapter One The Session Facade pattern works so well,that often it is easy to abuse it.It is common to find projects in which the Session Facade is misused: Creating a session bean God-class.Often developers put all the use cases in a system in one session bean.This results in a bloated session bean and reduced development productivity,because all the developers need access to this one class.Session beans should be split to house groupings of related use cases. Placing domain logic in session beans.A well-designed object-oriented domain model should contain all of the business/use case logic in your application(Fowler,2001).Most Session Facade methods should simply delegate to the appropriate entity bean,unless the use case involves workflow logic that needs to operate across different beans that may not be directly related. Duplication of business logic across the facade.As the project grows, often session bean methods contain duplicate code,such as executing logic to checkCreditHistory,which could be part of the workflow for any number of use cases.The solution is to add a layer of services(imple mented as session beans or plain Java classes)that encapsulate this reusable,use-case-independent business logic.This services layer is hidden from the client.As projects grow in size,it is useful to have reg- ular refactoring sessions in which such duplicate logic is found and extracted. The following are the benefits of the Session Facade pattern: Low network overhead.While the session bean layer does add an extra layer to call through,the client can now transfer funds in just one net- work call,rather than six network calls.On the server,the session bean communicates with entity beans via local interfaces,thus not incurring any network overhead.Even with the entity beans only used for remote interfaces,most application servers would optimize on the communica- tions between collocated EJBs. Clean and strict separation of business logic from presentation layer logic.By using a Session Facade,logic required to execute business logic is completely wrapped behind methods on session beans.EJB clients need only worry about presentation layer issues and should never have to execute more than one method on an EJB to get a unit of work done.This strictly separates business logic from presentation laver logic
The Session Façade pattern works so well, that often it is easy to abuse it. It is common to find projects in which the Session Façade is misused: ■■ Creating a session bean God-class. Often developers put all the use cases in a system in one session bean. This results in a bloated session bean and reduced development productivity, because all the developers need access to this one class. Session beans should be split to house groupings of related use cases. ■■ Placing domain logic in session beans. A well-designed object-oriented domain model should contain all of the business/use case logic in your application (Fowler, 2001). Most Session Façade methods should simply delegate to the appropriate entity bean, unless the use case involves workflow logic that needs to operate across different beans that may not be directly related. ■■ Duplication of business logic across the façade. As the project grows, often session bean methods contain duplicate code, such as executing logic to checkCreditHistory, which could be part of the workflow for any number of use cases. The solution is to add a layer of services (implemented as session beans or plain Java classes) that encapsulate this reusable, use-case-independent business logic. This services layer is hidden from the client. As projects grow in size, it is useful to have regular refactoring sessions in which such duplicate logic is found and extracted. The following are the benefits of the Session Façade pattern: ■■ Low network overhead. While the session bean layer does add an extra layer to call through, the client can now transfer funds in just one network call, rather than six network calls. On the server, the session bean communicates with entity beans via local interfaces, thus not incurring any network overhead. Even with the entity beans only used for remote interfaces, most application servers would optimize on the communications between collocated EJBs. ■■ Clean and strict separation of business logic from presentation layer logic. By using a Session Façade, logic required to execute business logic is completely wrapped behind methods on session beans. EJB clients need only worry about presentation layer issues and should never have to execute more than one method on an EJB to get a unit of work done. This strictly separates business logic from presentation layer logic. 10 Chapter One
EJB Layer Architectural Patterns 11 Transactional Integrity.Our session bean encapsulates all logic to per- form the bank transfer in one transaction.The session bean thus acts as a transactional facade,which localizes transactions to the server side, and keeps them short.Transactions are also demarcated at the session bean method level,configurable via deployment descriptors. Low coupling.The session bean buffers requests between the client and entity beans.If the entity bean layer needs changing in the future,we may be able to avoid changing the client because of the session bean layer of indirection. Good reusability.Our bank teller logic is encapsulated into a modular session bean,which can be accessed by any type of client (JSPs,servlets applications,or applets).The encapsulation of application logic into session beans means that our entity beans can contain data and data access logic only,making them reusable across session beans in the same or even in different applications. Good maintainability.One should define the transaction declaratively in the Bank Teller session bean's deployment descriptor,rather than waenPeaa es us a clean separation of and reduces the likelihood of errors. A clean verb-noun separation.The session bean layer models the application specific use cases,the verbs in our application,while the entity bean layer models the business objects,or the "nouns,"in our application.This architecture makes it very easy to map use cases from a requirements document to a real EJB architecture The Session Facade pattern is a staple in EJB development.It enforces highly efficient and reusable design,as well as clearly separates presentation logi (the client),business logic (the session facade)and data logic (entity beans,and so on).Session Facade describes a useful architecture for implementing any type of use case;however,if a use case is asynchronous in nature,the Message Facade pattern provides a more scalable approach. Related Patterns Message Facade Data Transfer Object Session Facade(Alur,et al.,2001) Session Facade(MartinFowler.com)
■■ Transactional Integrity. Our session bean encapsulates all logic to perform the bank transfer in one transaction. The session bean thus acts as a transactional façade, which localizes transactions to the server side, and keeps them short. Transactions are also demarcated at the session bean method level, configurable via deployment descriptors. ■■ Low coupling. The session bean buffers requests between the client and entity beans. If the entity bean layer needs changing in the future, we may be able to avoid changing the client because of the session bean layer of indirection. ■■ Good reusability. Our bank teller logic is encapsulated into a modular session bean, which can be accessed by any type of client (JSPs, servlets, applications, or applets). The encapsulation of application logic into session beans means that our entity beans can contain data and data access logic only, making them reusable across session beans in the same or even in different applications. ■■ Good maintainability. One should define the transaction declaratively in the Bank Teller session bean’s deployment descriptor, rather than programmatically via the JTA. This gives us a clean separation of middleware and application logic, which increases maintainability and reduces the likelihood of errors. ■■ A clean verb-noun separation. The session bean layer models the application specific use cases, the verbs in our application, while the entity bean layer models the business objects, or the “nouns,” in our application. This architecture makes it very easy to map use cases from a requirements document to a real EJB architecture. The Session Façade pattern is a staple in EJB development. It enforces highly efficient and reusable design, as well as clearly separates presentation logic (the client), business logic (the session façade) and data logic (entity beans, and so on). Session Façade describes a useful architecture for implementing any type of use case; however, if a use case is asynchronous in nature, the Message Façade pattern provides a more scalable approach. Related Patterns Message Façade Data Transfer Object Session Façade (Alur, et al., 2001) Session Façade (MartinFowler.com) EJB Layer Architectural Patterns 11